input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
NpgSQL resources and references <p>I have connected to my PostgreSQL database using .NET npgsql. I am programming in C#. Where can I find how to manipulate with this database using npgsql? Resources. Please don't send me <a href="http://www.npgsql.org/doc/index.html" rel="nofollow">http://www.npgsql.org/doc/index.html</a>, because it is very un-detailed, making it unhelpful.</p>
<p>NgpSQL tutorial would be an ideal situation.</p>
| <p>As is clearly stated in the docs, Npgsql is a standard .NET driver (ADO.NET), so any .NET database tutorial out there would do. You may also have missed the link to the MSDN docs: <a href="https://msdn.microsoft.com/en-us/library/h43ks021(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/h43ks021(v=vs.110).aspx</a></p>
|
Visual Studio Web Deploy Error at Start Preview <p>I am working on Visual Studio 2015 Web API project.</p>
<p>I have created Web Empty Project with API Option click. I choose Web Deploy option in process to publish web api app on server. I have created custom profile, provide the require detail and successfully pass the 'Validate Connection' but get error at preview page of publish Web Wizard.</p>
<h2>error</h2>
<pre><code>Web deployment task failed. (The specified credentials cannot be used with the authentication scheme 'Basic'.)
The specified credentials cannot be used with the authentication scheme 'Basic'.
Default credentials cannot be supplied for the Basic authentication scheme.
Parameter name: authType
</code></pre>
<h2>My Web.Config file</h2>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings></appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</code></pre>
<p>
</p>
| <p>Try setting the AuthType to NTLM in your publish profile (.pubxml):</p>
<pre><code><PropertyGroup>
<AuthType>NTLM</AuthType>
</code></pre>
|
How to interpret multiple Accept-* headers <p>My reading of <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="nofollow">RFC 2616</a> hasn't answered my question:</p>
<p>How should a server interpret multiple <em>Accept</em>, <em>Accept-Encoding</em>, <em>Accept-Language</em>, etc, headers?</p>
<p>Granted, this should generally be a rare occurrence, but far be it from me to assume every HTTP client actually does what it should.</p>
<p>Imagine an HTTP request includes the following:</p>
<pre><code>Accept-Language: en
Accept-Language: pt
</code></pre>
<p>Should the server:</p>
<ol>
<li>Combine the results, to an effective <code>Accept-Language: en, pt</code>?</li>
<li>Honor only the first one (<code>en</code>)?</li>
<li>Honor only the last one (<code>pt</code>)?</li>
<li>Throw a hissy fit (return a 400 status, perhaps?)</li>
</ol>
<p>Option #1 seems the most natural to me, and the most likely to be what the client means, and the least likely to completely break expectations even if it's not what the client means.</p>
<p>But is there any actual rule (ideally specified by an RFC) for how to handle these situations?</p>
| <p>1) You are looking at an outdated RFC. RFC 2616 has been obsoleted two years ago.</p>
<p>2) That said, the answer is 1); see <a href="https://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.2.2.p.3" rel="nofollow">https://greenbytes.de/tech/webdav/rfc7230.html#rfc.section.3.2.2.p.3</a>: "A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma. (...)"</p>
|
RESTful service in Karaf without blueprint xml <p>I am new to Karaf, hence was looking for resources to create a project for RESTful web services using felix annotations and without the use of BundleActivator class(i mean by an actual class that needs to be written by me, but its ok if some compiler or maven plugin does the same for me) and blueprint xml file. So far I got success in the first part(BundleActivator part) which now after compilation auto creates my MANIFEST.MF with import and export statements, creates the relevant XML file for each component class, and packages it into a a nice jar bundle which works very well when I deploy it on Karaf container. But what is not working is the RESTful services. The bundle is deployed correctly, but the REST urls are not exposed and hence I am unable to access them. </p>
<p>Please help me in getting this done. I don't want to write an XML file which needs to be modified everytime there is an addition or deletion of a rest service.</p>
<p>Thanks</p>
| <p>If you want to completely avoid blueprint then you should use cxf-dosgi. You simply annotate your rest service using jaxrs and publish it as an OSGi service with some special properties. </p>
<p>See the <a href="https://github.com/apache/cxf-dosgi/tree/master/samples/rest" rel="nofollow">cxf-dosgi rest sample</a>.</p>
<p>The example uses the standard DS annotation and the maven bundle plugin to create the DS component xml on the fly.</p>
<p>If you prefer to have blueprint at runtime then you can use the blueprint-maven-plugin. <a href="https://github.com/cschneider/Karaf-Tutorial/blob/master/tasklist/tasklist-persistence/src/main/java/net/lr/tasklist/persistence/impl/TaskServiceImpl.java" rel="nofollow">See this example</a>.</p>
|
call function in 'code behind' with AJAX in ASP.NET WebForms? <p>I want to get access to a method in code behind when I clicked an span in my view aspx:</p>
<p><strong>DEFAULT.ASPX VIEW CODE:</strong> </p>
<pre><code><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%-- MY SPAN --%>
<span runat="server" onclick="ShowChartSpider(this.id)" id="group_2" style="cursor: pointer" class="pull-right">My Span</span>
<%-- JAVASCRIPT CODE --%>
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("all correct");
},
error: function (data) {
alert("no");
}
}
);
}
</script>
</asp:Content>
</code></pre>
<p><strong>DEFAULT.ASPX.VB CODE BEHIND:</strong></p>
<pre><code><WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Sub MethodToCreateChart(sender As Object, e As EventArgs)
' My code to create the chart .....
End Sub
</code></pre>
<p>if I run the page, and inspects the page with the browser to see errors, none appear, but the code does not reach the breakpoint that I put in the method in codebehind.</p>
<p>What I´m doing wrong?
I would appreciate suggestions, thanks.</p>
| <p>Go to "RouteConfig.vb" under "App_Start" folder.</p>
<p>Change following line</p>
<pre><code> settings.AutoRedirectMode = RedirectMode.Permanent
</code></pre>
<p>To</p>
<pre><code>settings.AutoRedirectMode = RedirectMode.Off
</code></pre>
<p>i think your method code returning something like this.</p>
<p>Return Default.aspx/MethodToCreateChart</p>
<p>so me your MethodToCreateChart logic.</p>
<p>you can try with below sample method. your internal server error are coming because you are returning somethng from your method.</p>
<pre><code>Public Shared Function MethodToCreateChart(parameter1 As String) As String
Return "Hello " & Environment.NewLine & "The Current Time is: " & _DateTime.Now.ToString()
End Function
</code></pre>
|
Does using two Task.Run without await make them run in parallel? <p>I have just started dipping my toes in asynchronous programming. I tried to read a lot about Task.Run but I'm not clear on one question.</p>
<p>If I have to two continuous statements which use Task.Run, without await, will those two run in parallel?</p>
<p>Code example:</p>
<pre><code>Task.Run(()=> function1);
Task.Run(()=> function2);
</code></pre>
<p>Since I want a non-blocking call, Parallel.Invoke is not an option. I also don't want to wait for the context, so awaiting on Task.Run wouldn't make sense. Is this a good approach for fire and forget? </p>
| <p>It is possible that they will run in parallel, yes.</p>
<p>Of course, this assumes that there are resources that allow them to run in parallel - for example, that you have enough free threadpool threads, that you have multiple execution units, that they're not blocking on the same I/O...</p>
<p>Note that even though you don't await those tasks, it's usually useful to keep the <code>Task</code> references around - e.g. for error handling, completion notification etc. Purely fire and forget operations are rather rare.</p>
|
Has someone already used the XsdTypeImporterTask from XsdBuildTask.dll in MSBuild? <p>I used to convert XSD files to CS files using the XSD.exe program.
I made a custom MSBuild Task to do that and it works quite well.</p>
<p>Now, I try to find an MSBuild Task to do it because I don't want to maintain my custom task anymore.</p>
<p>I found the XsdTypeImporterTask from the assembly XsdBuildTask.dll which seems to do that, according to the <a href="https://msdn.microsoft.com/en-us/library/microsoft.build.tasks.xsd.xsdtypeimportertask(v=vs.110).aspx" rel="nofollow">MSDN documentation</a>.</p>
<p>However, that documentation is really poor and I didn't succeed to make it work, not even to import it in MSBuild :'(</p>
<p>I tried to Google and to StackOverflow this but didn't find anything about that.</p>
<p>Does someone on Earth use this Task?
Can someone help me using this Task?</p>
<p>Thanks a lot!</p>
| <p>Well, after succeeding to use it, I can say that someone used it: me.</p>
<p>This <a href="http://source.roslyn.io/#MSBuildFiles/C/Windows/Microsoft.NET/Framework64/v4.0.30319/Microsoft.ServiceModel.targets" rel="nofollow">page</a> helped me understand how to use it.
It works very well!</p>
|
Get-ADObject for DNS A-Record <p>how do I get the ADObject for a DNS A Record?</p>
<pre><code>Get-DnsServerResourceRecord -Name server1 -ZoneName Zone1.biz | Get-ADObject
</code></pre>
<p>does not work. I am just able to do this with "guessing" the DN. </p>
<pre><code>Get-ADObject -Identity "DC=server1,dc=zone1.biz,cn=MicrosoftDns,dc=DomainDnsZones,dc=domain,dc=biz"
</code></pre>
| <p>The object you get from the Get-DnsServerResourceRecord will mostlikely need to be filtered to pipe it.
Also, what kind of details do you need from the ADObject? Can get-adcomputer get the same data?
This one works fine for me :</p>
<pre><code>(Get-DnsServerResourceRecord -Name server1 -ZoneName Zone1.biz).hostname | Get-ADComputer
</code></pre>
|
Insert sections in a Moodle course <p>I am trying to create sections within a <strong>Moodle</strong> course using a <strong>script</strong> but I can not. I am using Moodle <code>course_create_sections_if_missing</code> function but can not get sections are displayed on the web but in the database they are created.</p>
<p>The code I'm using is as follows:</p>
<pre><code>if($numSections >0){
foreach ($sections as $nameSection) {
$idSection = checkSections($moodle_course , $nameSection);
if($idSection == -1){
m("crear section: ". $nameSection);
$maxSection = getMaxSections($moodle_course );
if($maxSection != -1){
m("max section: " . $maxSection);
$idSec = $maxSection + 1;
course_create_sections_if_missing($moodle_course , $idSec);
$res = updateNameSection($moodle_course , $nameSection, $idSec);
m("result update: " . $res);
}else{
m("There aren't sections for the course");
}
}else{
m("section already exists: ". $nameSection);
}
}
}else{
m("No sections for the course. ");
}
</code></pre>
<p>Note: the m ( "") function is responsible for displaying the text on the console.</p>
<p>the function <strong>checkSections</strong> is this: </p>
<pre><code>/**
* Check if there is a section.
*
* @param $course id of the course.
* @param $section name of the section
*
* @return id of section
*/
function checkSections($course , $section){
global $DB;
$id = null;
$sql = "SELECT id FROM mdl_course_sections where course = ? and name = ? ";
$sections = $DB->get_records_sql($sql, array($course, $section));
foreach ( $sections as $r ) {
$id = $r->id;
}
if(is_null($id))
return -1;
else
return $id;
}
</code></pre>
<p>the function <strong>getMaxSections</strong> is this:</p>
<pre><code>/**
* Returns the id of the highest section for a course.
*
* @param $course id of the course.
*
* @return max id of section
*/
function getMaxSections($course){
global $DB;
$id = null;
$sql = "SELECT max(section) as sec FROM mdl_course_sections where course = ? ";
$sections = $DB->get_records_sql($sql, array($course));
foreach ( $sections as $r ) {
$id = $r->sec;
}
if(is_null($id))
return -1;
else
return $id;
}
</code></pre>
<p>the function <strong>updateNameSection</strong> is this:</p>
<pre><code>/**
* Update the name of a section .
*
* @param $course id of the course.
* @param $nameSection name of the section.
* @param $idSection id of the section.
*
* @return result
*/
function updateNameSection($course, $nameSection , $idSection){
global $DB;
$id = null;
$sql = "update mdl_course_sections set name = ? where course = ? and section = ?";
$result = $DB->execute($sql, array($nameSection , $course, $idSection));
return $result;
}
</code></pre>
<p>So if anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.</p>
<p>Thanks in advance.</p>
| <p>You need to update the sections number on the table <strong>mdl_course_format_options</strong></p>
<p>Try this:</p>
<pre><code>$sql = "update mdl_course_format_options set value = ? where courseid = ? and name ='numsections'";
$result = $DB->execute($sql, array($numSections , $course));
</code></pre>
|
Angular.js dependencies order for third party libraries <p>First of all all third-party libraries should be wrapped in angular module so it can be added as a dependency to other angular modules.</p>
<p>for example</p>
<pre><code>angular.module('lodash', [])
.factory('_', function($window) { return $window._;});
</code></pre>
<p>and inject it into other module like:</p>
<pre><code>angular.module('myApp', ['lodash']);
</code></pre>
<p>The question is, where should third-party libraries be located in dependency list at start or at end?</p>
<pre><code>angular.module('myApp').controller(function($scope, _){});
</code></pre>
<p>VS</p>
<pre><code>angular.module('myApp').controller(function(_, $scope){});
</code></pre>
<p>Both cases works, but what is your opinion on that?</p>
<p>Thank you in advance</p>
| <p>The order doesnt really matter in this case. Angularjs will automatically handle the dependencies between the dependencies. </p>
|
How to open contacts and show the picked contacts in a list? <p>I am trying to make a button to opens up my contacts and let me choose contacts I want to pick. Then, list the names and(maybe) their mobile numbers on a list. So far, I'm stuck on opening the contacts from my phone. Hope you can help me. Thanks! Here's my code:</p>
<pre><code>public class RecipientsFragment extends Fragment {
public Button button;
static final int PICK_CONTACT=1;
public RecipientsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipients, container, false);
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
return inflater.inflate(R.layout.fragment_recipients, container, false);
}
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
String cNumber = null;
Uri contactData = data.getData();
Cursor c = getActivity().managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("number is:"+cNumber+" Name :"+name);
}
}
break;
}
}
}
</code></pre>
| <p>// You need below permission to read contacts</p>
<pre><code><uses-permission android:name="android.permission.READ_CONTACTS"/>
</code></pre>
<p>// Declare this at Global variable</p>
<pre><code> static final int PICK_CONTACT=1;
</code></pre>
<p>// put this code in Click event </p>
<pre><code> Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
</code></pre>
<p>// put this code outSide the OnCreate() </p>
<pre><code> @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
String cNumber=null;
Uri contactData = data.getData();
Cursor c = getActivity().managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("number is:"+cNumber+" Name :"+name);
Toast.makeText(getActivity(), "number is:"+cNumber+" Name :"+name, Toast.LENGTH_LONG).show();
}
}
break;
}
}
</code></pre>
|
VelocityAutoConfiguration is deprecated in Spring Boot 1.4.* <p>I upgraded Spring Boot dependency in my project and I realized that some classes, such as VelocityAutoConfiguration, are deprecated.</p>
<p>Do you know how can change this in Spring Boot 1.4.1?</p>
<pre><code>@SpringBootApplication
@EnableAsync
@EnableScheduling
@EnableAutoConfiguration(exclude = VelocityAutoConfiguration.class)
public class Api {
@Value("${token.default}")
private String defaultToken;
@Value("${spring.server.secret.key}")
private String secretKey;
public static void main(String[] args) throws Throwable {
new SpringApplication(Api.class).run(args);
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
AuthenticationFilter f = new AuthenticationFilter();
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(f);
registrationBean.addInitParameter("defaultToken", defaultToken);
registrationBean.addInitParameter("secretKey", secretKey);
ArrayList<String> match = new ArrayList<>();
registrationBean.setUrlPatterns(match);
return registrationBean;
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
</code></pre>
<p>When I remove the line with VelocityAutoConfiguration.class I face with the problem below.</p>
<pre><code>Caused by: java.lang.ClassNotFoundException: autovalue.shaded.org.apache.commons.logging.LogFactory
</code></pre>
<p>Can anyone help me?</p>
| <p><code>VelocityAutoConfiguration</code> is deprecated but still working. You cannot remove the line because without the line Spring Boot tries to configure Velocity.</p>
<p>You have to wait to version 1.5 if you want remove the line</p>
|
MDX : calculated measure gives different result with "where" and "from select" <p>I have a problem with 2 MDX statements, the first one gives the correct result, but the second one is different as expected.</p>
<p>As the MDX is build dynamically I'd rather prefer to use the second one.</p>
<pre><code>create calculated member [Sejours Ambulatoire] as sum([Ambu].[Ambu].[Ambu].[Ambulatoire], NbSejours)
create calculated member [Taux Ambulatoire] as IIF( [Ambu].[Ambu].current is [Ambu].[Ambu].[Non Ambulatoire], 0, divN([Sejours Ambulatoire], [Measures].[NbSejours] , 0) ), format_string='percent'
</code></pre>
<p>1st code :</p>
<pre><code>select [Measures].[Taux Ambulatoire] on 0
from [Cube]
where {[Ambu].[Ambu].[Non Ambulatoire]} * {[Etablissement].[Lieu établissement].[All-M].&[CHU de Brest]} * { [Periode].[Periode].[All-M].&[2014] }
</code></pre>
<p>-- Result 0,00% Correct</p>
<p>2nd Code :</p>
<pre><code>SELECT
{ [Measures].[Taux Ambulatoire] } ON 0
FROM ( SELECT
{ [Periode].[Periode].[All-M].&[2014] } ON 0,
{ [Etablissement].[Lieu établissement].[All-M].&[CHU de Brest] } ON 1,
{ [Ambu].[Ambu].[Non Ambulatoire] } ON 2
FROM [Cube])
</code></pre>
<p>-- Result 120,86% INCORRECT</p>
<p>Can someone explain the difference ?</p>
| <p>Don'g forget that in icCube you've an MDX debugger that will help you understand how the different parts of MDX statements are solved.</p>
<p>The question is how this expression is solved :</p>
<pre><code>[Ambu].[Ambu].current
</code></pre>
<p>Current is <strong>not</strong> taking the values from the subselect filter definition. It takes values from the other sources: where clause, axis, and tuples defined in a calculated member. </p>
<p>Two possible solutions</p>
<p>1) Put the filter in a where clause instead of in a filter, so <em>current</em> is going to return the tuple as defined in the where clause.</p>
<p>2) To get IIF working you can use <a href="http://www.iccube.com/support/documentation/mdx/GetFilterInfo.php" rel="nofollow">GetFilterInfo</a> function that returns the content of the subselect and the where clause</p>
<pre><code>isIn( GetFilterInfo([Ambu].[Ambu]) , [Ambu].[Ambu].[Non Ambulatoire] )
</code></pre>
<p>Nonetheless I'd check my statement carefully.</p>
|
swift 3 json serialisation <p>I'm trying to serialize a JSON using Swift 3, and coming up short..
This is the JSON (summarised):</p>
<pre><code>{
"values": [
{
"a": {
"b": "1",
"c": {
"d": 0.0
}
},
"wantThisOne": "2016-10-07T08:47:00Z"
},
{
"a": {
"b": "1",
"c": {
"d": 0.0
}
},
"notThisOne": "2016-10-07T09:05:00Z"
}
]
}
</code></pre>
<p>Where I want the date from 'wantThisOne', but not sure how exactly to get it...
This is as far as I get but nothing i try in the if let block seems to work for me... anyone dealt with something like this? I've had a look through stack overflow etc... but super stuck.</p>
<pre><code> NSURLConnection.sendAsynchronousRequest(request1 as URLRequest, queue: queue, completionHandler:{ (response: URLResponse?, data: Data?, error: Error?) -> Void in
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error.localizedDescription)
}
})
</code></pre>
| <p>First of all in Swift use generic type <code>Dictionary</code> like <code>[String:Any]</code> instead of <code>NSDictionary</code> and after you get dictionary get the array from the <code>value</code> key and iterate through the Array and get the <code>wantThisOne</code> from every object.</p>
<pre><code>if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] {
if let valueArray = jsonResult["values"] as? [[String:Any]] {
for item in valueArray {
print("Date - \(item["wantThisOne"])")
}
}
}
</code></pre>
|
Logging in a console application which hosts a NancyFx web service <p><strong>What I am doing</strong><br>
I am writing a Nancy self hosting application (runs in a console window)</p>
<p><strong>My problem</strong><br>
I cannot get log4net to log anything to my console window. (Specifically - I cannot get this to work when hosting a NancyFx service, I have no problem using Log4Net in other console applications.)</p>
<p><strong>What I have researched</strong><br>
I have looked at the following pages (in addition to searching StackOverflow):<br>
<a href="http://www.philhack.com/wire-up-log4net-to-nancy/" rel="nofollow">http://www.philhack.com/wire-up-log4net-to-nancy/</a>
<a href="https://lookonmyworks.co.uk/2012/03/14/logging-unhandled-exceptions-with-nancy/" rel="nofollow">https://lookonmyworks.co.uk/2012/03/14/logging-unhandled-exceptions-with-nancy/</a></p>
<p><strong>My log4net Configuration</strong> </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level: %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="Console"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
</code></pre>
<p><strong>Example of my usage of Log4Net</strong> </p>
<pre><code> public class MyNancyModule : NancyModule
{
private static ILog Logger = LogManager.LogFactory.GetLogger(typeof(MyNancyModule));
public MyNancyModule()
{
Logger.Debug("This is a test");
}
}
</code></pre>
<p><strong>My problem (again)</strong><br>
I cannot get log4net to log anything to my console window using the above configuration. I understand from the blog posts above that Nancy does something to configure the error handling pipelines which interferes with log4Net, but I don't quite understand what it is doing or how. </p>
<p>How can I get log4Net working in a self hosted Nancy service in order to log to the console window (I am not particularly interested in logging to the in-built diagnostics page)? </p>
<p>I haven't tried adding the log manager to the IOC container as in all my other applications, I usually have a static log manager per class which gives me class specific logging - the example in the blog post will log everything as having originated from the bootstrapper class. </p>
<p><strong>Edit</strong>
I forgot to mention that I am using ServiceStack.Logging.Log4Net for the logManager. It also doesn't appear to work in my example if I do:</p>
<pre><code>private static ILog Logger = LogManager.GetLogger(typeof(ApiReverseProxyModule));
</code></pre>
| <p>i use log4net like:</p>
<p>First you must define once the XmlConfigurator:</p>
<pre><code>XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
</code></pre>
<p>and the you can use it in the Classes:</p>
<pre><code>var log = LogManager.GetLogger("ClassName");
log.Debug("What you want...");
</code></pre>
|
Prestashop custom field in groups in admin <p>I have edit AdminGroupsController.php and add one field to renderForm function, like :</p>
<pre><code>array(
'type' => 'text',
'label' => $this->l('Myfield'),
'name' => 'my_field',
</code></pre>
<p>and name is same as database column. But I don't get how or where it does the edit and/or add action so I can add the field to be saved to the database. It will post the field now but it does not save it.</p>
<p>Another issue is, I have in override/controllers/admin/AdminGroupsController.php :</p>
<pre><code>class AdminGroupsController extends AdminGroupsControllerCore
{
public function renderForm()
{
</code></pre>
<p>but it does not work, even I delete cache_index file from cache.
I had to do the edits to the controllers/admin/AdminGroupsController.php ...</p>
| <p>I found out that I had to copy classes/Group.php to override/classes/Group.php and modify it: </p>
<pre><code>class Group extends GroupCore
{
</code></pre>
<p>Seems to be the model for this.</p>
<p>and to add fiel(d) to the model I wanted to update, and it seems it will fetch that also when I try to edit the group.</p>
<p>Also, I still don't know why overriding AdminGroupController DOES NOT work, but overriding this class (model) works...</p>
|
Deploying ASP.Net application to two Windows servers <p>I've got this <em>Asp.Net MVC</em> App I would like to deploy to my two servers running <em>Windows Server 2012</em>. Actually I've got <strong><em>two servers</em></strong> on which I would like the application to run. Only one server is used at some point in time and the second is just a copy of the first. Both servers must be in the exactly <strong>same state</strong> at any time so that when one of them is broken, I could <strong>redirect users</strong> to the second without them noticing any change.</p>
<p><strong>Question:</strong>
How to sync the application on both servers to avoid having different states from one server to the other?</p>
| <p>Check this ARR setup configuration in IIS
<a href="https://www.iis.net/downloads/microsoft/application-request-routing" rel="nofollow">https://www.iis.net/downloads/microsoft/application-request-routing</a></p>
|
SQL select and count same table <p>I'm making a newsletter tool with a table that stores e-mail address's user and email id opened, to calculate total and unique opened for every sent e-mail. </p>
<p>I'd like to show a detailed page with a distinct about e-mail address's user and counting times that the user opened the e-mail.</p>
<p>Example of db table:</p>
<pre><code>email_id | user_id | user
----------------------------
1 | 1 | alpha@domain.com
1 | 1 | alpha@domain.com
1 | 1 | alpha@domain.com
1 | 2 | beta@domain.com
1 | 3 | gamma@test.org
1 | 4 | mars@planet.net
1 | 4 | mars@planet.net
</code></pre>
<p>Web result:</p>
<pre><code>â User â Times â
â¬ââââââââââââââââââââ¬ââââââââ£
â alpha@domain.com â 3 â
â beta@domain.com â 1 â
â gamma@test.org â 1 â
â mars@planet.net â 2 â
</code></pre>
<p>I tried the following query but it works only for the first row, then it truncates the rest:</p>
<pre><code>SELECT DISTINCT user, count(DISTINCT user) as counttotal
FROM newsletter_log
where email_id = 1
</code></pre>
| <p>Simply do a <code>GROUP BY</code>. Use <code>COUNT(*)</code> to count.</p>
<pre><code>select user, count(*) as counttotal
FROM newsletter_log
where email_id = 1
group by user
</code></pre>
|
How to overcome this item padding in navigation drawer? <p>I check out all the question and also google a lot I just want to remove this padding between each item in navigation view. Help me to sort out this problem thanks in advance.</p>
<p>This is the code of my main_drawer</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single" android:id="@+id/home1"
>
<item
android:id="@+id/home"
android:title="Home"
/>
</group>
<group android:checkableBehavior="single" android:id="@+id/aboutus1">
<item
android:id="@+id/nav_camera"
android:title="AboutUs" />
</group>
<group android:checkableBehavior="single" android:id="@+id/Services1">
<item
android:id="@+id/nav_gallery"
android:title="Services" />
</group>
<group android:checkableBehavior="single" android:id="@+id/consultation1">
<item
android:id="@+id/nav_slideshow"
android:title="Consultation" />
</group>
<group android:checkableBehavior="single" android:id="@+id/gallery1">
<item
android:id="@+id/nav_manage"
android:title="Gallery" />
</group>
<group android:checkableBehavior="single" android:id="@+id/appoinment1">
<item
android:id="@+id/nav_manage1"
android:title="Appoinment" />
</group>
<group android:checkableBehavior="single" android:id="@+id/Contact_Us1">
<item
android:id="@+id/Contact_Us"
android:title="Contact Us" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_menu_share"
android:title="Share" />
<item
android:id="@+id/nav_send"
android:icon="@drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
</code></pre>
<p>My image is ...<a href="http://i.stack.imgur.com/YAf24.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/YAf24.jpg" alt="Want to remove the padding showing in blue mark "></a></p>
| <p>According to sourcecode of NaviagtionView found <a href="https://github.com/android/platform_frameworks_support/blob/master/design/src/android/support/design/widget/NavigationView.java" rel="nofollow">here</a>, it led me to NavigationMenuPresenter (found <a href="https://github.com/android/platform_frameworks_support/blob/master/design/src/android/support/design/internal/NavigationMenuPresenter.java" rel="nofollow">here</a>) which says, every normal type in menu list inflates <code>R.layout.design_navigation_item</code>. So if You preview it (<a href="https://github.com/dandar3/android-support-design/blob/master/res/layout/design_navigation_item.xml" rel="nofollow">here</a>) You will notice what preference it uses.</p>
<pre><code><android.support.design.internal.NavigationMenuItemView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/listPreferredItemHeightSmall"
android:paddingLeft="?attr/listPreferredItemPaddingLeft"
android:paddingRight="?attr/listPreferredItemPaddingRight"
android:foreground="?attr/selectableItemBackground"
android:focusable="true"/>
</code></pre>
<p>So, the final step is to override style for one of that attribute, i.e. <code>layout_height</code> which references to <code>"?attr/listPreferredItemHeightSmall" (default 48dp)</code>.</p>
<p>Open please Your styles.xml and override it by i.e using custom value:</p>
<pre><code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- HERE-->
<item name="listPreferredItemHeightSmall">18dp</item>
</style>
</code></pre>
<hr>
<p><strong>Original:</strong></p>
<p><a href="http://i.stack.imgur.com/zgJ3A.png" rel="nofollow"><img src="http://i.stack.imgur.com/zgJ3A.png" alt="enter image description here"></a></p>
<p><strong>Custom:</strong></p>
<p><a href="http://i.stack.imgur.com/9RKH8.png" rel="nofollow"><img src="http://i.stack.imgur.com/9RKH8.png" alt="enter image description here"></a></p>
|
How to use a static UITableView inside a UIViewController? <p>I know that it is not possible to add a static <code>UITableView</code> inside an <code>UIViewController</code> (or at least I could not find any way to do it). Trying to do a workaround (as pointed <a href="http://stackoverflow.com/questions/22364230/static-table-view-outside-uitableviewcontroller#answer-25193002">here</a>), I am following these steps:</p>
<ul>
<li>I have created an <code>UIViewController</code> on my <code>Main.storyboard</code>.</li>
<li>I have drag an <code>UIContainerView</code> inside my <code>UIViewController</code>.</li>
<li>I have deleted the <code>UIViewController</code> embedded by default on my <code>UIContainerView</code>.</li>
<li>I have created an <code>UITableViewController</code> and drag it to the <code>UIContainerView</code>.</li>
<li>I have added a label with the text "Hello" into my <code>UITableViewCell</code>.</li>
</ul>
<p>Here is the structure of this part on my <code>Main.storyboard</code>:</p>
<p><a href="http://i.stack.imgur.com/PxVmv.png" rel="nofollow"><img src="http://i.stack.imgur.com/PxVmv.png" alt="enter image description here"></a></p>
<p>And here is the result that I am getting:</p>
<p><a href="http://i.stack.imgur.com/Lnlxk.png" rel="nofollow"><img src="http://i.stack.imgur.com/Lnlxk.png" alt="enter image description here"></a></p>
<p>I can only get an empty <code>UITableView</code> without any information inside of it. </p>
<p>Am I missing something? Am I doing it in the wrong way?</p>
<p><strong>P.S:</strong> I am using <code>Xcode8</code> and <code>Swift3</code>.</p>
<p>Thanks in advance!</p>
| <p>You are using a <code>UITableView</code> with <strong>Prototype Cells</strong> which is visible because in the grey area it's written "Prototype Content". </p>
<p>Change to <strong>Static Cells</strong> in the Table View inspector (on the right of the window) after selecting the <strong>TableView</strong> in <strong>Interface Builder</strong>.</p>
<p><a href="http://i.stack.imgur.com/IxmNK.png" rel="nofollow"><img src="http://i.stack.imgur.com/IxmNK.png" alt="TableView inspector"></a>
<a href="http://i.stack.imgur.com/NgDzo.png" rel="nofollow"><img src="http://i.stack.imgur.com/NgDzo.png" alt="Change to Static Cells"></a></p>
|
How can i get my program to return the password strength <p>I'm struggling with my password rater program. How can i make sure that when i insert a password, my program returns the password strength. When i run this program it says that password_strength is stored at .....) is the return that i call at the end of my program wrong?</p>
<pre><code>print ("Welcome to this password rater program")
print ("Your password needs to have a minimum of 6 characters with a maximum of 20 characters.")
print ("Your password can contain lowercase and uppercase characters, numbers and special characters")
print("")
password = input("Please insert your password: ")
def check_len(password):
l = len(password)
if 6 < l < 20:
x = check_char(password, l)
else:
x = 0
return x
def check_char(password, l):
for i in range(l):
ascii = ord(password[i])
num = 0
upper = 0
symbols = 0
lower = 0
space = 0
if 96 < ascii < 123:
lower = 15
elif 47 < ascii < 58:
num = 25
elif 64 < ascii < 91:
upper = 25
elif ascii == 32:
space = 30
else:
symbols = 25
total = ((lower + num + upper + space + symbols) * len(password))
return total
def password_strength(total):
if total >= 1000:
print("Your chosen password is Very strong")
elif 700 < total < 999:
print("Your chosen password is strong")
elif 500 < total < 699:
print("your chosen password is medium")
elif total <= 500:
print("Your chosen password is weak")
return total
strength = check_len(password)
print(password_strength(strength))
</code></pre>
| <p>Well first of all, you tell python to print the function, not the evaluation of the function. This is why you get that message.</p>
<p>Also, you never call any of the functions you wrote. To get a working program
after the declaration of all definitions is the following:</p>
<p>Call the check_len definition:</p>
<pre><code>strength = check_len(password)
</code></pre>
<p>This definition doesn't return any value though. You could change it to:</p>
<pre><code>def check_len(password):
l = len(password)
if 6 < l < 16:
x = check_char(password, l)
else:
x = 0
return x
</code></pre>
<p>To have it return the score/strength.</p>
<p>Finally you should process the score using your 'password_strength' definition:</p>
<pre><code>password_strength(strength)
</code></pre>
<p>In this line there is no need to print, because the printing statements are in the definition itself. If you want to print the final score as well though, you could make it into the following line:</p>
<pre><code> print(password_strength(strength))
</code></pre>
<p>One more debug thingy: your check_char definition doesn't take any arguments.
You could solve this by changing it into:</p>
<pre><code>def check_char(password, l):
</code></pre>
<p>Final code:
print ("Welcome to this password rater program")
print ("Your password needs to have a minimum of 6 characters with a maximum of 16 characters.")
print ("Your password can contain lowercase and uppercase characters, numbers and special characters")
print ("")</p>
<pre><code>password = raw_input("Please insert your password: ")
def check_len(password):
l = len(password)
if 6 < l < 16:
x = check_char(password, l)
else:
x = 0
return x
def check_char(password, l):
for i in range(l):
ascii = ord(password[i])
num = 0
upper = 0
symbols = 0
lower = 0
space = 0
if 96 < ascii < 123:
lower = 15
elif 47 < ascii < 58:
num = 25
elif 64 < ascii < 91:
upper = 25
elif ascii == 32:
space = 30
else:
symbols = 25
total = ((lower + num + upper + space + symbols) * len(password))
return total
def password_strength(total):
if total >= 1000:
print("Your chosen password is Very strong")
elif 700 < total < 999:
print("Your chosen password is strong")
elif 500 < total < 699:
print("your chosen password is medium")
elif total <= 500:
print("Your chosen password is weak")
return total
strength = check_len(password)
print(password_strength(strength)) `
</code></pre>
|
I want to store excel in database having data in 3 sheets <p>I want to store excel file in SQL Server database having 3 sheets.
So what will be better option form following.</p>
<p>1st Option Creating 3 table for each sheet and saving data.</p>
<p>2nd Appending columns to single table and append sheetnumber as prefix to columns</p>
<p>3rd convert all column data in one string (comma saperated) and store in single column</p>
<p>Which will be better option form above with respect to flexibility of data storage and access, space require for storing etc.</p>
<p>If any other option is there please tell me</p>
<p>Sheet3 data will be redundant for all rows. means the data in 1st row of sheet3 and last row of sheet 3 will be same in most cases</p>
<p>Sheet1 Sheet2 and Sheet3 data will have logical connection (not excel formula) </p>
<p>Thanks in advance</p>
| <p>To maintain the most flexibility, maintainability and least chance for headaches in the future do yourself a favor and create separate tables for each sheet. </p>
|
I want to stroed data of client side slider in temporary using javascript <ol>
<li><p>I have using one slider from client side that slider containing 4
question n question having 4 option of the answer. </p></li>
<li><p>user have select any one from them n go to next question.</p></li>
<li><p>i want to that user selected answer in temporarily stored in some where using javascript.</p></li>
<li><p>Please help me how to create the javascript for that.end
sorry for my english language.</p></li>
</ol>
<hr>
<p><a href="http://i.stack.imgur.com/qYNE7.png" rel="nofollow">enter image description here</a><a href="http://i.stack.imgur.com/4I1lJ.png" rel="nofollow">enter image description here</a></p>
<p><strong>code:</strong></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> <div class='home' style="background-color: #e4ceb4 !important">
<section class='start-invest'>
<div class='wrapper'>
<div class='unslider' data-unslider='true' id='unslider' style='display:none;'>
<ul class='nolist'>
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>1/4</span>
</div>
</div>
<!-- 1 -->
<div class='hide' data-slide-no='1'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>1</span>/4
</div>
<div class='age-income'>
I am
<input autocomplete='off' autofocus class='age' id='age' maxlength='2' placeholder='' tabindex='1' type='text'>
years old &amp;
<br class='br'>
earn
<br class='break'>a
Gross annual income
<br class='br'>of
<i class='fa fa-inr'></i>
<input class='income' id='income' maxlength='13' placeholder='' tabindex='2' type='text'>
</div>
<div class='cta-next'>
<button class='btn' id='next-btn' tabindex='3'>
Next
</button>
</div>
</li>
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>2/4</span>
</div>
</div>
<!-- 2 -->
<div class='hide' data-slide-no='2'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>2</span>/4
</div>
<div class='age-income'>
How long do you intend
<br class='br'>to
remain invested?
</div>
<div class='btn-set' id="Opt1">
<button id="Opt5" name="button" type="submit" class="wh-btn optn-btn risk-by-time-btns" data-risk-factor="10.5" value="1 to 3 yrs">1 to 3 yrs</button>
<button id="Opt2" name="button" type="submit" class="wh-btn optn-btn risk-by-time-btns" data-risk-factor="24.5" value="3 to 5 yrs">3 to 5 yrs</button>
<button id="Opt3" name="button" type="submit" class="wh-btn optn-btn risk-by-time-btns" data-risk-factor="28" value="5 to 7 yrs">5 to 7 yrs</button>
<button id="Opt4" name="button" type="submit" class="wh-btn optn-btn risk-by-time-btns" data-risk-factor="31.5" value="Greater than 7 yrs">Greater than 7 yrs</button>
</div>
</li>
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>3/4</span>
</div>
</div>
<!-- 3 -->
<div class='hide' data-slide-no='3'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>3</span>/4
</div>
<div class='age-income'>
What are you looking at from your
<br class='br'>investment?
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn optn-btn goal-btns" data-risk-factor="10.5">
Safety
<br class='br'>
<span class='tip'>I prioritise safety of my principal at the top and expect to achieve returns that equal inflation</span>
</button><button name="button" type="submit" class="wh-btn optn-btn lg goal-btns" data-risk-factor="17.5">
Safety +
<br class='br-lg'>
Moderate Growth
<br class='br'>
<span class='tip'>While I would like to protect my principal, I will be happy with returns that beat inflation</span>
</button><button name="button" type="submit" class="wh-btn optn-btn goal-btns" data-risk-factor="26.25">
Growth
<br class='br'>
<span class='tip'>I seek to grow my capital in line with the stock market performance over a longer period of time while being able to accept short term volatilities</span>
</button><button name="button" type="submit" class="wh-btn optn-btn goal-btns lg" data-risk-factor="31.5">
Aggressive
<br class='br-lg'>
Growth
<br class='br'>
<span class='tip'>I would like to take the stock market returns and beat them hands down with my portfolio performance! I will digest the volatility that accompanies my style</span>
</button>
</div>
</li>
<li id='risk-buttons'>
<div class='slide-counter'>
<div class='inner-d'>
<span>4/4</span>
</div>
</div>
<!-- 4 -->
<div class='hide' data-slide-no='4'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>4</span>/4
</div>
<div class='age-income'>
How do you rate yourself
<br class='br'>
on Risk Tolerance?
<sup>*</sup>
</div>
<!-- For Mobile -->
<div class='risk-sm'>
* Risk tolerance is an important component in investing. An individual should have a realistic understanding of
<br class='br-lg'>
his or her ability and willingness to stomach large swings in the value of his or her investments.
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn sure risk-willingness-btns" data-risk-factor="3">
Very Low
<span class='tip'>I cannot tolerate any loss</span>
</button><button name="button" type="submit" class="wh-btn sure risk-willingness-btns" data-risk-factor="6">
Low
<span class='tip'>I can tolerate up to 5% loss in a short term dip</span>
</button><button name="button" type="submit" class="wh-btn sure risk-willingness-btns" data-risk-factor="9">
Medium
<span class='tip'>I can tolerate up to a 10% loss in a short term dip</span>
</button><button name="button" type="submit" class="wh-btn sure risk-willingness-btns" data-risk-factor="11.25">
High
<span class='tip'>I can tolerate up to a 25% loss in a short term dip</span>
</button><button name="button" type="submit" class="wh-btn sure risk-willingness-btns" id="very_high_tolerance" data-risk-factor="13.5">
Very High
<span class='tip'>I can tolerate greater than 25% loss in a short term dip</span>
</button><button name="button" type="submit" class="wh-btn unsure risk-willingness-btns" data-risk-factor="0">
Unsure
<span class='tip'></span>
</button>
</div>
<div class='cta hide' id='okay-cta'>
<small>Still unsure? Answer a few more questions for us!</small>
<br>
<button class='btn' id='okay-btn'>OKAY</button>
</div>
<div class='cta hide' id='compute-cta'>
<button class='btncompute btn compute' id="compute" onclick=" Progressbar()">COMPUTE</button><div>
</div>
</div>
<!-- For Desktop -->
<div class='risk-lg'>
* Risk tolerance is an important component in investing. An individual should have a realistic understanding of
<br class='br-lg'>
his or her ability and willingness to stomach large swings in the value of his or her investments.
</div>
</li>
<!-- 4.1 -->
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>
4.1 /
<br>4.4</br>
</span>
</div>
</div>
<div class='hide' data-slide-no='5'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>4</span>/4
</div>
<div class='age-income'>
By how much would your investments need
<br class='break'>
to go down to cause you discomfort?
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn optn-btn investment-fall-threshold-btns" data-risk-factor="0.75">
Any fall
</button><button name="button" type="submit" class="wh-btn optn-btn investment-fall-threshold-btns" data-risk-factor="1.5">
By 10%
</button><button name="button" type="submit" class="wh-btn optn-btn investment-fall-threshold-btns" data-risk-factor="2.25">
By 25%
</button><button name="button" type="submit" class="wh-btn optn-btn investment-fall-threshold-btns" data-risk-factor="3.375">
By more than 25%
</button>
</div>
</li>
<!-- 4.2 -->
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>
4.2 /
<br>4.4</br>
</span>
</div>
</div>
<div class='hide' data-slide-no='6'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>4</span>/4
</div>
<div class='age-income'>
While making investments, what do you care for most?
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn optn-btn lg investment-care-btns" data-risk-factor="0.75">
Minimizing Losses
</button><button name="button" type="submit" class="wh-btn optn-btn lg investment-care-btns" data-risk-factor="1.875">
Both Equally
</button><button name="button" type="submit" class="wh-btn optn-btn lg investment-care-btns" data-risk-factor="3.375">
Maximising Gains
</button>
</div>
</li>
<!-- 4.3 -->
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>
4.3 /
<br>4.4</br>
</span>
</div>
</div>
<div class='hide' data-slide-no='7'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>4</span>/4
</div>
<div class='age-income'>
While deciding between two jobs,
<br class='break'>
which will you go for?
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn optn-btn lg job-choice-btns" data-risk-factor="0.75">
The one with high job security
<br class='break'>
and low pay increase
</br>
</button><button name="button" type="submit" class="wh-btn optn-btn lg job-choice-btns" data-risk-factor="1.875">
Can't say as it depends on
<br class='break'>
other factors as well
</br>
</button><button name="button" type="submit" class="wh-btn optn-btn lg job-choice-btns" data-risk-factor="3.375">
The one with less job security
<br class='break'>
but high pay increase
</br>
</button>
</div>
</li>
<!-- 4.4t -->
<li>
<div class='slide-counter'>
<div class='inner-d'>
<span>
4.4 /
<br>4.4</br>
</span>
</div>
</div>
<div class='hide' data-slide-no='8'></div>
<div class='start-heading'>Start your Investment Plan</div>
<!-- For Mobile -->
<div class='slider-nav'>
<span>4</span>/4
</div>
<div class='age-income'>
How do you rate your willingness to take investment
<br class='break'>
risks relative to the general population?
</div>
<div class='btn-set'>
<button name="button" type="submit" class="wh-btn relative-risk-willingness-btns" data-risk-factor="0.75">
Very Low
<br class='break risk-rel-pop'>
Risk-taker
</br>
</button><button name="button" type="submit" class="wh-btn relative-risk-willingness-btns" data-risk-factor="1.5">
Low
<br class='break risk-rel-pop'>
Risk-taker
</br>
</button><button name="button" type="submit" class="wh-btn relative-risk-willingness-btns" data-risk-factor="2.25">
Medium
<br class='break risk-rel-pop'>
Risk-taker
</br>
</button><button name="button" type="submit" class="wh-btn relative-risk-willingness-btns" data-risk-factor="2.8125">
High
<br class='break risk-rel-pop'>
Risk-taker
</br>
</button><button name="button" type="submit" class="wh-btn relative-risk-willingness-btns" data-risk-factor="3.375">
Very High
<br class='break risk-rel-pop'>
Risk-taker
</br>
</button>
</div>
<div class='cta'>
<button class='btn compute hide btncompute' onclick=" Progressbar()" id="compute">COMPUTE</button>
</div>
</li>
</ul>
<a class="unslider-arrow next tooltip" href="#">
<span class='error-message'>
ZAPP!
<br>
Please pick an
<br>
option before we
<br>
move ahead.
</span>
<span class='error-message-input'></span>
</a><a class="unslider-arrow prev" href="#"></a>
</div>
</div>
</section>
<div class='hide' id='progress'>
<div class='wrapper of-hidden'>
<div class='orange-text'></div>
<div class='white-text'></div>
<div class="safari chart" data-percent="100" style="align-content: center ;margin-left: auto; margin-right: auto; width: 6em">
<img class="tag" src="~/Image/spinner.gif" style="align-content: center ;margin-left: auto; margin-right: auto; width: 6em" />
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>You can use localstorage to store data on client-side</p>
|
touchesMoved seen by all view controllers in Swift? <p>I have a ViewController that defines touchesMoved() to increment a counter as a user drags a finger over the screen:</p>
<pre><code>override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
numMoved += 1
print("Moved: \(numMoved)")
}
</code></pre>
<p>When the user goes to another view controller which doesn't have touchesMoved() defined, I expect that nothing would happen. (The new view controller is defined to be of class OtherViewController, which inherits directly from UIViewController and so does not get the touchesMoved() override I had defined for the first view controller.)</p>
<p>However, after tapping a button that brings me to the other view controller, I still see the printed messages, meaning touchesMoved() is still being invoked even though I am no longer on the original view controller that is tracking the drag. </p>
<p>Am I missing some simple thing that would ensure that the override to touchesMoved() only affects the ViewController it is defined within?</p>
<p>Thanks for any insights.</p>
| <p>Instead of defining <code>touchesMoved</code> in a view controller, define it in a <em>view</em>. The main view of the view controller will do. (You will need to subclass UIView and make the main view of the view controller an instance of this subclass.)</p>
<p>It will have the same effect, but now you are not in the view controller hierarchy and you won't get messages from the other view controller's views.</p>
<p>Another alternative: pull a UITouch out of the <code>touches:</code> and look at its <code>view</code>. If this isn't your view, ignore this call.</p>
|
Bash JQ getting multiple values Issue in JSON file <p>I'm trying to parse a JSON file for getting multiple values. I know how to parse the specific values ( "A"/"B"/"C") in the array <code>(.info.file.hashes[])</code>. </p>
<p>For Example : When issuing the following command over the file <code>b.json</code></p>
<pre><code>#jq -r '.info.file.hashes[] | select(.name == ("A","B","C")).value' b.json
Result :
f34d5f2d4577ed6d9ceec516c1f5a744
66031dad95dfe6ad10b35f06c4342faa
9df25fa4e379837e42aaf6d05d92012018d4b659
#b.json
{
"Finish": 1475668827,
"Start": 1475668826,
"info": {
"file": {
"Score": 4,
"file_subtype": "None",
"file_type": "Image",
"hashes": [
{
"name": "A",
"value": "f34d5f2d4577ed6d9ceec516c1f5a744"
},
{
"name": "B",
"value": "66031dad95dfe6ad10b35f06c4342faa"
},
{
"name": "C",
"value": "9df25fa4e379837e42aaf6d05d92012018d4b659"
},
{
"name": "D",
"value": "4a51cc531082d216a3cf292f4c39869b462bf6aa"
},
{
"name": "E",
"value": "e445f412f92b25f3343d5f7adc3c94bdc950601521d5b91e7ce77c21a18259c9"
}
],
"size": 500
}
}
}
</code></pre>
<p>Now , How can i get multiple values with "Finish", "Start" along with the hash values ? I have tried issuing the command.</p>
<pre><code> #jq -r '.info.file.hashes[] | select(.name == ("A","B","C")).value','.Finish','.Start' b.json
</code></pre>
<p>and Im getting the result as </p>
<pre><code>Result:
f34d5f2d4577ed6d9ceec516c1f5a744
null
66031dad95dfe6ad10b35f06c4342faa
null
9df25fa4e379837e42aaf6d05d92012018d4b659
null
null
null
Expected Result :
f34d5f2d4577ed6d9ceec516c1f5a744
66031dad95dfe6ad10b35f06c4342faa
9df25fa4e379837e42aaf6d05d92012018d4b659
1475668827
1475668826
</code></pre>
| <p>Literally just downloaded and read the manual </p>
<p>Try </p>
<pre><code>jq '(.info.file.hashes[] |select(.name == ("A","B","C")).value), .Finish, .Start' b.json
"f34d5f2d4577ed6d9ceec516c1f5a744"
"66031dad95dfe6ad10b35f06c4342faa"
"9df25fa4e379837e42aaf6d05d92012018d4b659"
1475668827
1475668826
</code></pre>
<p>Note the brackets used for grouping the pipe separately from the Finish and Start values.</p>
|
Typescript type assignation <p>I'm curently learning Typescript and I'm having an issue ...</p>
<p><strong>Type assignation for a function</strong></p>
<p>Here are 2 simple sample of code, which are compiling in a different way and I don't get the reason.</p>
<p><strong>1 Sample</strong></p>
<pre><code>testP(): Promise<number> {
return new Promise<string>((resolve, reject) => {
resolve("string");
});
}
</code></pre>
<p>This code returning in error during compilation as I'm not returning a number, that's fine.</p>
<p><strong>2 Sample</strong></p>
<pre><code>testP(): Promise<number> {
return new Promise<any>((resolve, reject) => {
resolve("string");
});
}
</code></pre>
<p>This code is compiling without any bug and I don't know why ...</p>
<p>WHat is my mistake ?
Thank you in advance !</p>
<p>Edit:</p>
<p>Here is what I'm actually trying to do</p>
<pre><code>export interface Animal {
name: string,
weight: number,
age: number
}
getDogs(): Promise<Dog[]> {
return this.http.get('/dogs')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
</code></pre>
<p>But like that, even if my "response" is not an array of "dogs", it doesn't trigger any error;</p>
<p>What am I missing ?</p>
| <p>The compiler cannot infer the return type of the promise from a call to <code>resolve</code>.</p>
<p>This code:</p>
<pre><code>return new Promise((resolve, reject) => {
</code></pre>
<p>... is a shorthand for:</p>
<pre><code>return new Promise<any>((resolve, reject) => {
</code></pre>
<p>And then the type <code>any</code> is a way to disable type checking. Your second code compiles but it is wrong.</p>
<p>If you don't want to repeat yourself, you can do this:</p>
<pre><code>let testP = function () {
return new Promise<string>((resolve, reject) => {
resolve("string");
});
}
</code></pre>
<p>Here, the return type of the function is inferred to <code>Promise<string></code>.</p>
<hr>
<p>EDIT #1 (To answer to your answer): <code>Promise<any></code> is compatible with <code>Promise<number></code>, and <code>"string"</code> is also compatible with <code>any</code>. But <code>Promise<string></code> is not compatible with <code>Promise<number></code>. In fact, <code>any</code> allows you to do wrong code. When you use it, it's up to you to know what you are doing.</p>
<hr>
<p>EDIT #2:</p>
<p>About this code:</p>
<pre><code>export interface Dog {
name: string,
weight: number,
age: number
}
function getDogs(): Promise<Dog[]> {
return this.http.get('/dogs')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
</code></pre>
<p>The TypeScript compiler checks types <em>statically</em>. It can't check the type of a string value returned by the server, because, at run time, on the browser, there is just compiled code without types metadata at all.</p>
<p>TypeScript is like JSDoc. It helps to describe parts of your program. It can't help to check data that your program receives dynamically.</p>
|
Ruby hashes group by multiple value <p>I have multiple hashes who looks like this: </p>
<pre><code>[{"name" => "name1", "folder" => "folder1", id => 1 },
{"name" => "name1", "folder" => "folder1", id => 2 },
{"name" => "name1", "folder" => "folder2", id => 3},
{"name" => "name2", "folder" => "folder1", id => 4}]
</code></pre>
<p>And my goal is to have something who looks like this:</p>
<pre><code> {"name1" =>
[{"folder1" =>
[{"name" => "name1", "folder" => "folder1", id => 1 },
{"name" => "name1", "folder" => "folder1", id => 2 }] }
{"folder2" =>
[{"name" => "name1", "folder" => "folder2", id => 3}] }]
{"name2" =>
[{"folder 1" =>
[{"name" => "name2", "folder" => "folder1", id => 4}] }] }
</code></pre>
<p>I didn't find a proper solution who give exactly this kind or a similar result for now.</p>
<p>Edit: i tried that and many others but never found the way of having two level's deep hashes <code>a.group_by{|line| line["name"]}.each_value {|v| v.map{|line| line["folder"]}}</code></p>
| <p>This seems to <a href="http://ideone.com/tUK9Ar" rel="nofollow">do what you want</a>:</p>
<pre><code>transformed_hash = initial_hash
.group_by { |x| x['name'] }
.map { |k, v| [k, v.group_by{ |x| x['folder'] }] }
.to_h
</code></pre>
|
Empty return in non-void function, is undefined behaviour? <p>After reading answers about the topic of <em>control reaches end of non-void functions</em> I didn't see any answer adressing specifically the the case of exiting a non-void function with an empty <code>return</code> statement:</p>
<pre><code>int return_integer() { return; } // empty return in non-void function
</code></pre>
<p>What I've found so far in the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf">C standard</a> is:</p>
<blockquote>
<h2>6.8.6.4 The return statement</h2>
<h3>Constraints</h3>
<ol>
<li>A <code>return</code> statement with an expression shall not appear in a function whose return type is <code>void</code>. A <code>return</code> statement without an expression shall only appear in a function whose return type is <code>void</code>.</li>
</ol>
</blockquote>
<p>The standard quote states what <strong>should</strong> we do with our <code>return</code> statements for <code>void</code> and non-<code>void</code> functions, what happens when we ignore the constraint is mentioned in other part of the document:</p>
<blockquote>
<h2>6.9.1 Function definitions</h2>
<ol start="12">
<li>If the <code>}</code> that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.</li>
</ol>
</blockquote>
<p>Previous standard quote states that UB happens if we use the returned value from a function which ends after reaching the closing curly braces (<code>}</code>), so we have UB in the code below:</p>
<pre><code>int UB(int x) { if (x) return x; }
printf("%d", UB(1)); // Correct
printf("%d", UB(0)); // Undefined behavior
</code></pre>
<p>In the <code>UB(1)</code> call the function returns <code>1</code> through the <code>return x;</code> instruction under the <code>if (x)</code>; in the <code>UB(0)</code> call the <code>if (x)</code> condition is not passed so function ends reaching <code>}</code>, to use the return value in this case is UB (but isn't in <code>UB(1)</code>). But, what happens in this case?</p>
<pre><code>int UB(int x) { if (x) return; } // empty return statement
printf("%d", UB(1)); // Undefined behavior?
printf("%d", UB(0)); // Undefined behavior
</code></pre>
<p>In the code above, the call <code>UB(1)</code> does not meet the <code>§6.9.1/12</code> requirements to lead to UB because the function ends <strong>without reaching <code>}</code></strong> and also does not return any value.</p>
<p>In which part of the C standard is this situation described?</p>
| <pre><code>int UB(int x) { if (x) return; }
</code></pre>
<p>This is not even undefined behavior, it is a <em>constraint violation</em>. The cited text </p>
<blockquote>
<p>A return statement without an expression shall only appear in a
function whose return type is void</p>
</blockquote>
<p>from 6.8.6.4 is normative, meaning the compiler is not allowed to let it slip without giving a diagnostic message. If it compiles without giving a diagnostic, the compiler is not a conforming implementation (doesn't follow the language standard).</p>
<p>In plain English this means: that code should not even compile. </p>
<p>Now if the compiler does produce a binary executable even if the code had constraint violations, all bets are off. It is no longer a C program, but some non-standard one, with no guaranteed behavior by any language standard.</p>
|
Charts not rendering ASP.NET <p>Please help. I am trying to put charts on a aspx page but they don't show when attempting to view in browser. It just shows blank where the charts should be. Here is the aspx code. Thank you.</p>
<pre><code><h2>Top 5 Most Expensive Products</h2>
<br />
<asp:Chart ID="Chart1" runat="server" DataSourceID="SqlDataSource1">
<Series>
<asp:Series Name="Series1" ChartArea="ChartArea1"></asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1"></asp:ChartArea>
</ChartAreas>
</asp:Chart>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT TOP 5 [price], [productName] FROM [products] ORDER BY [price] DESC"></asp:SqlDataSource>
<br />
<h2>Total Number of Customers Per State</h2>
<br />
<asp:Chart ID="Chart2" runat="server">
<Series>
<asp:Series Name="Series1"></asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1"></asp:ChartArea>
</ChartAreas>
</asp:Chart>
<br />
</code></pre>
| <p>You are missing the mapping between the <strong>Data</strong> coming from you <strong>Database</strong> and the <code>Series</code> in the <code>Charts</code>.</p>
<p>For that you need to use <code>XValueMember</code> and <code>YValueMember</code> to complete the mapping.</p>
<p>Try something like this:</p>
<pre><code><Series>
<asp:Series Name="Series1" ChartArea="ChartArea1" XValueMember="price" YValueMember="productName"></asp:Series>
</Series>
</code></pre>
|
Angular2 : Login Page to restrict access to entire app <p>I'm struggling to find a solution to my problem.
In my Angular2 app I would like to redirect all my "routes" to a login page when no user is authenticated. I'm aware about the routes, guards etc...</p>
<p>But in the <a href="https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard" rel="nofollow">official "Routing & Navigation" documentation</a>, the login form to access the "Admin" component is loaded in the router-outlet.</p>
<p>In my case, I would like that my App is not reachable when not logged in.</p>
<p>Any idea how to do this ?</p>
<p>Thanks a lot</p>
| <p>Found the solution by myself reading the <a href="https://angular.io/docs/ts/latest/guide/router.html" rel="nofollow">official Angular2 documentation</a> and using <em>Child Routes</em> & <em>CanActivate Guard</em></p>
<p>I pushed on Sample on <a href="https://github.com/An0d/angular-login-sample" rel="nofollow">my GitHub</a> </p>
|
looping over product to compute a serie in python <p>I'm just gonna compute the result of below serie in python:</p>
<p>The formula</p>
<p><a href="http://i.stack.imgur.com/vxNE0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/vxNE0.gif" alt="enter image description here"></a></p>
<p>So, here is my function to compute:</p>
<pre><code> def compute(limit):
pi = 1
for i in range(1,limit):
pi = pi * ((4*(i**2))//(4*(i**2)-1))
print(2*pi)
compute(10000) /*returns 2*/
</code></pre>
<p>I know it is a silly question. But could you address the problem with this snippet?</p>
| <p>As others have already mentioned, <code>//</code> is integer division. No matter whether you're dividing floats or integers, the result will always be an integer. Pi is not an integer, so you should use float division: <code>/</code> and tell Python explicitly that you really want a float by converting one of the numbers to float<sup>*</sup>. For example, you could do <code>4</code> -> <code>4.</code> (notice the dot).</p>
<p>You could do the same thing in a more clear way using <a href="https://docs.python.org/3/library/functools.html" rel="nofollow"><code>functools</code></a> and <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a> modules and a generator expression. </p>
<pre><code>import functools
import operator
def compute(limit):
return 2 * functools.reduce(operator.mul, ((4.*(i**2)/(4*(i**2)-1) for i in range(1, limit + 1))
</code></pre>
<p><sub>* Python 3 does float division with <code>4/(something)</code> even without this, but Python 2.7 will need <code>from __future__ import division</code> to divide as freely as Python 3, otherwise the division will result in an integer in any way.</sub></p>
|
Python: Matplotlib open interactive figures <p>since I like the interactive figures of matlab (*.fig). I wrote a small program for saving interactive figures in Python. I use pickle to dump a matplotlib.pyplot figure in a name.pyfig file:</p>
<pre><code> output = open('name.pyfig', 'wb')
pickle.dump(plt.gcf(), output)
output.close()
</code></pre>
<p>To open the figure I use:</p>
<pre><code> f = open('name.pyfig','rb')
pickle.load(f)
f.close()
</code></pre>
<p>Now I'd like to implement the following: I want to open the figure by double clicking on the name.pyfig file in the windows file explorer.</p>
<p>Since name.pyfig only contains the data of the figure, I wrote a python script openfig.py to open the figure by using </p>
<pre><code> python openfig.py name.pyfig
</code></pre>
<p>in CMD which is working quite well. To be able to run the openfig.py by double-clicking on the pyfig file I associate the pyfig extension with a bat file (open with - choose default program) calling the code from above which is also working, as long as the bat file is in the same folder! For some reason, it is not possible to select the bat file as default program for the pyfig file if it is located somewhere else!</p>
<p>Any solution?
Ge</p>
<p>System:
Python Version 2.7.9
Win 7 Enterprise</p>
| <p>You need to give the full absolute path if you want to put the bat file somewhere else.</p>
<pre><code>f = open('C:\full\path\to\folder\name.pyfig','rb')
</code></pre>
|
Custom error pages in IIS <p>I have the following set-up in my web.config</p>
<pre><code><customErrors mode="RemoteOnly" defaultRedirect="/ServerError" redirectMode="ResponseRewrite"/>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="400" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="400" path="/error/Error400" responseMode="ExecuteURL" />
<error statusCode="404" path="/error/Error404" responseMode="ExecuteURL" />
<error statusCode="500" path="/error/Error500" responseMode="ExecuteURL" />
</httpErrors>
</code></pre>
<p>With the above configuration, our website is able to catch 404s, and display the nice 404 page served from /error/error404 with the 404 Header.</p>
<p>Now i have the following scenario: <br/>
1. User navigates to /action/id <br/>
2. Id is not found, i would like to return a 404, but serve a custom 404, different from the generic one served from /error/error404. i.e. serve a different custom page;</p>
<p>In my controller i have the following:</p>
<pre><code>Response.StatusCode=(int)HttpStatusCode.NotFound;
Response.TrySkipIisCustomErrors = true;
return View("SomeView", model);
</code></pre>
<p>Is this something that can be achieved ? <br/></p>
<p>PS: using IIS 8</p>
<p><strong>LE</strong> In case anyone is interested in the solution i implemented, i have done the following: <br>
1. In my <code>action</code>, i set a session variable <code>Session["InvalidId"]=something</code><br>
2. In my <code>ErrorController</code> i have the following:</p>
<pre><code>var invalidId = Session["InvalidId"];
if(invalidId != null)
{
return View("SomeView", model);
}
</code></pre>
<p>This helped me serve a different 404 page to my generic one.</p>
<p>Thanks for the help !</p>
| <p>Yes, this can be easily achieved and you do not really need other pages. You need to have some session variables for custom messages and use them to determine whether you need to display some messages. If so, then display them in your view.</p>
<p>Algorithm:</p>
<ol>
<li>Your custom page detects an error</li>
<li>Some error messages are generated</li>
<li>Your custom page redirects to the error page</li>
<li>The error page checks for error messages to be displayed</li>
<li>If there are such error messages, then they are displayed and the error message queue is cleared</li>
</ol>
|
Double Lost Of Precision <p>I'm a little bit confused because I lose precision all the time.</p>
<p>Maybe I'm operating with the wrong type. I have a String like "100.00". But when I do </p>
<blockquote>
<p>Double.parseDouble("100.00") it is being cut off to 100. Need help. Thanks in advance.</p>
</blockquote>
| <p>You probably printed your number with <code>System.out.println(d)</code>. It will internally call <code>Double.toString(double)</code>, whose specification states</p>
<blockquote>
<p>How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. </p>
</blockquote>
<p>This is because the <code>double</code> number has no notion of "decimal precision". It is a <em>binary</em> number with fixed <em>binary</em> precision (number of binary digits after the binary point).</p>
|
Return empty fields in view if relationship not available? <p>I am trying to retrieve a view with a employee and personal detail data that are held on different tables. It works fine when the relationship is set. </p>
<p>However when employee model does not yet have a PersonalDetail row in db i get Trying to get property of non-object for the personal detail data. How do i write my controller so that it ignores null fields and returns empty fields to my blade? Code:</p>
<p>Employee Model</p>
<p><code>public function PersonalDetail()
{
return $this->hasOne('App\PersonalDetail');
}
</code></p>
<p>PersonalDetail model</p>
<pre><code> public function Employee()
{
return $this->belongsTo('App\Employee');
}
</code></pre>
<p>And my controller </p>
<pre><code> public function show($employee )
{
$employee = Employee::find($employee);
$personaldetails = $employee->PersonalDetail;
return view('employees.show')->withEmployee($employee)->withPersonalDetail($personaldetails);
}
</code></pre>
<p>example blade item</p>
<pre><code>{{ $employee->personaldetail->address }}
</code></pre>
| <p>You have to just check is is <code>null</code> or not:</p>
<pre><code>{{ $employee->personaldetail ? $employee->personaldetail->address : '' }}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>If you want to change it level above the view then you can add a method in the <code>Employee</code> model like this:</p>
<pre><code>public function getPersonalDetailAddress()
{
return $this->personaldetail ? $this->personaldetail->address : '';
}
</code></pre>
<p>and then in the view:</p>
<pre><code>{{ $employee->getPersonalDetailAddress() }}
</code></pre>
|
jq select attribute if any array element satisfies a condition <p>With the help of <strong>jq</strong> i would like to select all addresses of nodes that have at least one <strong>required=true</strong> in their attribute list. The result list should have unique items.</p>
<p>Here is my Json:</p>
<pre><code>{
"nodes": [
{
"address":"127.0.0.1",
"attributes": [
{
"id":"abc",
"required":true
},
{
"id":"def",
"required":true
},
{
"id":"ghi",
"required":false
}
]
},
{
"address":"127.0.0.2",
"attributes": [
{
"id":"abc",
"required":false
},
{
"id":"def",
"required":false
}
]
}
]
}
</code></pre>
<p>I first tried with:</p>
<pre><code>jq '.nodes[] | select(.attributes[].required == true) | .address'
</code></pre>
<p>This produces:</p>
<pre><code>"127.0.0.1"
"127.0.0.1"
</code></pre>
<p>So it gets the address for every <strong>required=true</strong> field it finds in the attributes section. How to make the result list unique? There is also a unique keyword in jq, but I couldn't figure out how this could help me.</p>
| <p>Using <code>unique</code> is safe but it does require sorting, which may not be necessary. In your particular case, for example, the repetition is an artifact of the jq query. Consider using <code>any</code> instead (or as well), as it more precisely captures the intention ("at least one"), as well as having "short-circuit" semantics (i.e., it stops searching once the condition is true):</p>
<pre><code>$ jq '.nodes[]
| select( any(.attributes[]; .required == true))
| .address' input.json
</code></pre>
<p>Output:</p>
<pre><code>"127.0.0.1"
</code></pre>
<p>You can always add <code>unique</code> if necessary.</p>
|
How to store and retrieve passwords without being seen in the code using spock table <p>I am looking for some good approaches on storing passwords within the framework (groovy+geb+spock+selenium). Currently I am using encrypt and decrypt methods using Crypto.Cipher. However I would like to know if others have any good approaches to do it. Such as any other algorithms/techniques/tools?</p>
<p>It looks something like below:</p>
<pre><code>def "test" (){
given:
when
Login(username,password)
then
where:
username | password
"jass" | "testpass123"
//"jass" | decryptPassword("some encrypted value ")
// instead of the actual password we are calling a
// function "decryptPassword" which takes encrypted value and
// returns the actual key to the calling function.
}
</code></pre>
| <p>You can encrypt the password and store in the spock table. Write a separate method in other class for decrypt. Use the encrypted data. Call the decrypt method in password field instead of plain test. </p>
<p>More secure decrypt method should be converted as jar file and use it. So its difficult to find the decrypt algorithm.</p>
|
I am trying to run the code inside the onMenuItemClick() without pressing the menu button <p>This is the code for android activity I want to run, if at all possible without creating a new activity. Need to get rid of the Listener function. I tried to make a new java class but it gave me error on putExtra functions. Also how can I deal with the instance of newConnection inside the Listener constructor.</p>
<pre><code>public class NewConnection extends Activity {
private Bundle result = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
private class Listener implements OnMenuItemClickListener {
//used for starting activities
private NewConnection newConnection = null;
public Listener(NewConnection newConnection)
{
this.newConnection = newConnection;
}
</code></pre>
<p>Trying to run the code below without clicking:</p>
<pre><code> @Override
public boolean **onMenuItemClick**(MenuItem item) {
{
// this will only connect need to package up and sent back
Intent dataBundle = new Intent();
String server = ("tsp//:server address");
String port = ("1823");
//put data into a bundle to be passed back to ClientConnections
dataBundle.putExtra(ActivityConstants.server, server);
dataBundle.putExtra(ActivityConstants.port, port);
...
...
//add result bundle to the data being returned to ClientConnections
dataBundle.putExtras(result);
setResult(RESULT_OK, dataBundle);
newConnection.finish();
}
return false;
}
</code></pre>
<p>This is the code used to call the activity:</p>
<pre><code> createConnection = new Intent();
createConnection.setClassName(
clientConnections.getApplicationContext(),
"org.eclipse.paho.android.service.sample.NewConnection");
clientConnections.startActivityForResult(createConnection,
ActivityConstants.connect);
</code></pre>
| <p>This is a basic constructor within a listener paradigm. It's a core idea within computer science that code should be reusable, and to facilitate this code needs to generally be self contained. This is often done within Java with a listener. It's usually an abstract class or an interface that has a few set functions. The main class that uses the listener is assigned this object or objects, and when it reaches a relevant point will trigger the listener to notify your code of an event.</p>
<p>This allows people to write code that is fully contained and still provide event hooks whereby other user who employ that code can get feedback such as when a menu item is clicked or a new connection is made, and have this dealt with by the person using this code, but without the author of the original class knowing anything about your code. It allows things like menus and connection managers and buttons that have no connection to the code that they trigger, by design. So that any number of these can be made and used.</p>
|
Change global variable to value in entry field <p>How can I change a global variable to a value inputted by a user in an entry field?</p>
<pre><code>card_no = 0
def cardget():
global card_no
card_no = e1.get()
print(card_no)
def menu():
global card_no
root = Tk()
e1 = Entry(root).pack()
Label(root, text= "Enter card number").pack(anchor= NW)
Button(root, text= "Confirm card", command=cardget).pack(anchor= NW)
menu()
</code></pre>
| <p>Don't use global variables. Tkinter apps work much better with OOP.</p>
<pre><code>import tkinter as tk
class App:
def __init__(self, parent):
self.e1 = tk.Entry(parent)
self.e1.pack()
self.l = tk.Label(root, text="Enter card number")
self.l.pack(anchor=tk.NW)
self.b = tk.Button(root, text="Confirm card", command=self.cardget)
self.b.pack(anchor=tk.NW)
self.card_no = 0
def cardget(self):
self.card_no = int(self.e1.get()) # add validation if you want
print(self.card_no)
root = tk.Tk()
app = App(root)
root.mainloop()
</code></pre>
|
SDL_PollEvent causes screen to wake up after xset dpms force off <p>I have a program that turns the screen on and off with <code>xset dpms force on/off</code> and also calls <code>SDL_PollEvent(&e)</code> in a loop. After turning the display off with <code>xset</code>, any call to <code>SDL_PollEvent</code> causes the screen to wake up, even without any input. I can comment out the <code>SDL_PollEvent</code> call and it doesn't happen. Is there something I need to do with an event or something to prevent the screen from turning on? Updated with minimal code to reproduce the problem:</p>
<pre><code>#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <atomic>
#include <iostream>
#include <thread>
using namespace std;
atomic<bool> SCREEN_ON(true);
atomic<bool> RUNNING(true);
atomic<bool> SERVER_CONNECTED(false);
std::string exec(const char *cmd) {
char buffer[128];
std::string result = "";
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe)
throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL)
result += buffer;
}
return result;
}
double get_time() {
static const Uint64 freq = SDL_GetPerformanceFrequency();
static const Uint64 begin_time = SDL_GetPerformanceCounter();
Uint64 current = SDL_GetPerformanceCounter();
Uint64 elapsed = current - begin_time;
return (double)elapsed / (double)freq;
}
void handle_input() {
SDL_Event e;
while (SDL_PollEvent(&e)){}
}
void monitor_thread() {
while (RUNNING) {
double time = get_time();
if (time < 15)
SERVER_CONNECTED = false;
else if (time < 35)
SERVER_CONNECTED = true;
else
SERVER_CONNECTED = false;
cout << "server status: " << SERVER_CONNECTED << endl;
cout << "screen_on status: " << SCREEN_ON << endl;
handle_input();
SDL_Delay(1000);
if (SCREEN_ON && (!SERVER_CONNECTED)) {
cout << "TURNING SCREEN OFF\n";
SCREEN_ON = false;
exec("sleep 1 && xset -display :0.0 dpms force off");
}
if ((!SCREEN_ON) && SERVER_CONNECTED) {
cout << "TURNING SCREEN ON\n";
SCREEN_ON = true;
exec("sleep 1 && xset -display :0.0 dpms force on");
}
}
}
int main(int argc, char *argv[]) {
Uint32 initflags = SDL_INIT_TIMER | SDL_INIT_VIDEO;
SDL_Init(initflags);
Uint32 window_flags =
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_GRABBED;
SDL_Window *window =
SDL_CreateWindow("title", 25, 25, 800, 600, window_flags);
SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_EnableScreenSaver();
SDL_GLContext gl_context = SDL_GL_CreateContext(window);
glewInit();
thread update_thread(monitor_thread);
glClearColor(1, 1, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
while (RUNNING) {
if (!SCREEN_ON) {
cout << "zzz...\n";
SDL_Delay(2000);
continue;
}
glClear(GL_COLOR_BUFFER_BIT);
SDL_Delay(16);
SDL_GL_SwapWindow(window);
}
return 0;
}
</code></pre>
<p><s>The screen will turn itself back on very shortly after <code>exec("sleep 1 && xset -display :0.0 dpms force off");</code>, before the next call to turn it back on.</s></p>
<p>Nevermind, SDL_PollEvent can only be called in the main thread.</p>
| <p>Call <a href="https://wiki.libsdl.org/SDL_EnableScreenSaver" rel="nofollow"><code>SDL_EnableScreenSaver()</code></a>.</p>
<p><a href="https://wiki.libsdl.org/FAQUsingSDL#Why_does_SDL_disable_my_screensaver_by_default.3F" rel="nofollow">More info</a>:</p>
<blockquote>
<p><strong>Why does SDL disable my screensaver by default?</strong></p>
<p>Many applications using SDL are games or screensavers or media players
where the user is either watching something for an extended period of
time or using joystick input which generally does not prevent the
screensaver from kicking on.</p>
<p>You can disable this behavior by setting the environment variable:
<code>SDL_VIDEO_ALLOW_SCREENSAVER=1</code> This can be set globally for the user or
on a per-application basis in code.</p>
<p>In SDL 2.0.2 this can also be changed by setting the hint
<code>SDL_HINT_VIDEO_ALLOW_SCREENSAVER</code>.</p>
<p>Additionally, SDL 2.0 provides the function <code>SDL_EnableScreenSaver()</code>.</p>
</blockquote>
|
Spring REST Controller returns JSON with empty data <p>I have a simple Spring Boot web application. I'm trying to receive some data from server. The Controller returns a collection, but the browser receives empty JSON - the number of curly brackets is equals to the number of objects from server, but its content is empty.</p>
<pre><code>@RestController
public class EmployeeController {
@Autowired
private EmployeeManagerImpl employeeManagerImpl;
@RequestMapping(path="/employees", method = RequestMethod.GET)
public Iterable<Employee> getAllEmployees() {
Iterable<Employee> employeesIterable = employeeManagerImpl.getAllEmployees();
return employeesIterable;
}
}
</code></pre>
<p>The method fires and a browser shows:</p>
<p><a href="http://i.stack.imgur.com/yYQxo.png" rel="nofollow"><img src="http://i.stack.imgur.com/yYQxo.png" alt="enter image description here"></a></p>
<p>Nothing more in the console. Any ideas?</p>
<p>EDIT:
Employee.java</p>
<pre><code>@Entity
public class Employee implements Serializable{
private static final long serialVersionUID = -1723798766434132067L;
@Id
@Getter @Setter
@GeneratedValue
private Long id;
@Getter @Setter
@Column(name = "first_name")
private String firstName;
@Getter @Setter
@Column(name = "last_name")
private String lastName;
@Getter @Setter
private BigDecimal salary;
public Employee(){
}
}
</code></pre>
| <p>I think you should use Lombok as class level instead of field level.</p>
<pre><code>@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Employee implements Serializable {}
</code></pre>
<p>This may solve your problem.</p>
|
most suited search algorithm? <p>I'm now facing a problem and I'm not sure what the right solution is. I'll try to explain it, and I hope someone has some good solutions for me:</p>
<p>I have two big data arrays. One that I'm browsing, with something between 50^3 and 150^3 data samples (usually between 50 and 100, rare worst case scenario 150).
For every sample, I want to make a query on another structure that is around the same size (so huge number of total combinations, I can't explore them all).</p>
<p>The query can't be predicted exactly but usually, it is something like :
structure has fields A B C D E F G (EDIT : in total, it's something like 10 to 20 int fields).
query is something like :
10 < A < 20 and B > 100 and D > 200.
Yes, it's really close to SQL.</p>
<p>I thought to put this in a database, but actually it would be a standalone database, and I can work in RAM to make it even faster (speed is an essential criteria).</p>
<p>I thought to try something using GPGPU but it seems it's a terrible idea and despite search can be parallel, it does't seem to be a good idea, searching an unpredictable number of results isn't a good application (if someone can tell me if my understanding has been right it would help me confirm that I should forgive this solution).
EDIT : the nubmer of results is unpredictable because of the query nature, but the it is quite low, since the purpose is to find a low number of well suited combinations</p>
<p>Then since I could use a DB, why not make a RAM B-Tree? it seems close to the solution, but is it? If it is, how should I build my indexes? Can I really do multidimensional indexes, since multidimensional search will always exist? probably UB-Tree or R-tree could do the job (but in my second data sample, I could have some duplicates, so doesn't it make the R-TREE non applicable?).
The thing is, I'm not sure I understand properly all those right now, so if one of you knows trees (and gpgpu, and even solutions I didn't think to), perhaps you could let me know which solution I should explore, learn, and implement?</p>
| <ul>
<li><p>GPGPU is not a suitable choice due to the fact that you are limited by their capacity and since you are not telling us the data size of these samples I am assuming that a titan x tier card will not suffice. If you could go really wild, TESLA or FirePro, then it is actually worth it since you mentioned that speed really matters. But I am going to speculate that these things are out of your budget, and considering that you have to learn CUDA or OpenCL to make something that will generally be a pain to port here and there, my take is "No".</p></li>
<li><p>You mentioned that you have an unpredictable number of results and this is a bad thing. You should develop a formula that will "somewhat" calculate the amount of space which will be needed otherwise it will be disappointing to have your program work on something for quite some time only to get a capacity error/crash. On the other hand, if the RAM capacity is not sufficient, you could work "database style" fetching data from storage when needed(and this is quite bothersome to implement due to scheduling implementations etc).</p></li>
<li><p>If you do have the time to go bespoke, here is a helpfull link. Remember, you are going to stumble a lot, but when you make it you will have learnt a tone of stuff:</p>
<pre><code>https://www.quora.com/What-are-some-fast-similarity-search-algorithms-and-data-structures-for-high-dimensional-vectors
</code></pre></li>
<li><p>In my opinion, an in memory database is the easiest and at the same time most reliable thing to do without compromising on speed. Which one to implement is on you. I think MemSQL is a good one.</p></li>
</ul>
|
Passport create multi session in my database <p>Iâm confronted to a weird situation using an API made with sailsJS.</p>
<p>So when I use postman to login, passport create one session in DB and everything works fine.</p>
<p>But when I use my app made with Angular2 and do the same request to my API, passport generate many sessions in my DB â¦</p>
<p>Here is my Code :
<strong>Login - SailsJS</strong>
<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> login: (req, res) => {
passport.authenticate('local', (err, user, info) => {
if ((err) || (!user)) {
return res.send({
message: info.message,
user: user
});
}
req.logIn(user, function(err) {
if (err) res.send(err);
return res.send({
message: info.message,
user: user
});
});
})(req, res);
},</code></pre>
</div>
</div>
</p>
<p><strong>PassPort Conf - SailsJS</strong></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>function findById(id, fn) {
User.findOne(id).then(function (user) {
if (!user) return fn("User Not Found", null) ;
return fn(null, user);
}).catch(function(err) {
console.log("err",err) ;
return fn(err, null);
});
}
passport.serializeUser( (user, done) => {
done(null, user.id);
});
passport.deserializeUser( (id, done) => {
findById(id, function (err, user) {
if (err)
user = null;
return done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
User.findOne({email: email}, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {message: 'Incorrect email.'});
}
bcrypt.compare(password, user.password, (err, res) => {
if (!res)
return done(null, false, {
message: 'Invalid Password'
});
let returnUser = {
id: user.id,
email: user.email
};
return done(null, returnUser, {
message: 'Logged In Successfully'
});
});
});
}</code></pre>
</div>
</div>
</p>
<p><strong>Calling the api - Angular2</strong></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>private _headers = new Headers();
private _options = new RequestOptions({
headers: this._headers,
withCredentials: true
});
login(email, password): Observable < any > {
return this._http
.post(this._url + 'login', {
email: email,
password: password
}, this._options)
.map(
(res: any) => {
let user = JSON.parse(res._body).user;
if (user) {
this.isLogged = true;
localStorage.setItem('User', JSON.stringify(user));
return true;
} else {
return false;
}
}
)
}</code></pre>
</div>
</div>
</p>
| <p>I finally add the "saveUninitialized" to false in my express-session configuration. </p>
<p>This parameter set to true forces a session that is "uninitialized" to be saved to the store. <a href="https://github.com/expressjs/session" rel="nofollow">Documentation</a></p>
<p>So now, as long as req.session is not updated by passport, the session is not stored.</p>
|
I'm trying to run an Angular Material example dialog, but seeing a blank page <p>I want to run this demo:</p>
<p><a href="https://material.angularjs.org/latest/demo/dialog" rel="nofollow">https://material.angularjs.org/latest/demo/dialog</a></p>
<p>But there is blank page when I run this in the browser</p>
<pre><code><html lang="en" >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<style>
.dialogdemoBasicUsage #popupContainer {
position: relative; }
.dialogdemoBasicUsage .footer {
width: 100%;
text-align: center;
margin-left: 20px; }
.dialogdemoBasicUsage .footer, .dialogdemoBasicUsage .footer > code {
font-size: 0.8em;
margin-top: 50px; }
.dialogdemoBasicUsage button {
width: 200px; }
.dialogdemoBasicUsage div#status {
color: #c60008; }
.dialogdemoBasicUsage .dialog-demo-prerendered md-checkbox {
margin-bottom: 0; }
</style>
<!--
Your HTML content here
-->
<!-- Angular Material requires Angular.js Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-resource.min.js"></script>
<!-- Your application bootstrap -->
<script type="text/javascript">
/**
* You must include the dependency on 'ngMaterial'
*/
angular.module('dialogDemo1', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) {
$scope.status = ' ';
$scope.customFullscreen = false;
$scope.showAlert = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
// Modal dialogs should fully cover application
// to prevent interaction outside of dialog
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('This is an alert title')
.textContent('You can specify some description text in here.')
.ariaLabel('Alert Dialog Demo')
.ok('Got it!')
.targetEvent(ev)
);
};
$scope.showConfirm = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Would you like to delete your debt?')
.textContent('All of the banks have agreed to forgive you your debts.')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
$mdDialog.show(confirm).then(function() {
$scope.status = 'You decided to get rid of your debt.';
}, function() {
$scope.status = 'You decided to keep your debt.';
});
};
$scope.showPrompt = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.prompt()
.title('What would you name your dog?')
.textContent('Bowser is a common name.')
.placeholder('Dog name')
.ariaLabel('Dog name')
.initialValue('Buddy')
.targetEvent(ev)
.ok('Okay!')
.cancel('I\'m a cat person');
$mdDialog.show(confirm).then(function(result) {
$scope.status = 'You decided to name your dog ' + result + '.';
}, function() {
$scope.status = 'You didn\'t name your dog.';
});
};
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'dialog1.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.showTabDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'tabDialog.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.showPrerenderedDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
contentElement: '#myDialog',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
};
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
});
</script>
</head>
<body>
<div ng-controller="AppCtrl" class="md-padding" id="popupContainer" ng-cloak>
<p class="inset">
Open a dialog over the app's content. Press escape or click outside to close the dialog and
send focus back to the triggering button.
</p>
<div class="dialog-demo-content" layout="row" layout-wrap layout-margin layout-align="center">
<md-button class="md-primary md-raised" ng-click="showAlert($event)" >
Alert Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showConfirm($event)" >
Confirm Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showPrompt($event)" >
Prompt Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showAdvanced($event)">
Custom Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showTabDialog($event)" >
Tab Dialog
</md-button>
<md-button class="md-primary md-raised" ng-if="listPrerenderedButton" ng-click="showPrerenderedDialog($event)">
Pre-Rendered Dialog
</md-button>
</div>
<p class="footer">Note: The <b>Confirm</b> dialog does not use <code>$mdDialog.clickOutsideToClose(true)</code>.</p>
<div ng-if="status" id="status">
<b layout="row" layout-align="center center" class="md-padding">
{{status}}
</b>
</div>
<div class="dialog-demo-prerendered">
<md-checkbox ng-model="listPrerenderedButton">Show Pre-Rendered Dialog</md-checkbox>
<p class="md-caption">Sometimes you may not want to compile the dialogs template on each opening.</p>
<md-checkbox ng-model="customFullscreen" aria-label="Fullscreen custom dialog">Use full screen mode for custom dialog</md-checkbox>
<p class="md-caption">Allows the dialog to consume all available space on small devices</p>
</div>
<div style="visibility: hidden">
<div class="md-dialog-container" id="myDialog">
<md-dialog layout-padding>
<h2>Pre-Rendered Dialog</h2>
<p>
This is a pre-rendered dialog, which means that <code>$mdDialog</code> doesn't compile its
template on each opening.
<br/><br/>
The Dialog Element is a static element in the DOM, which is just visually hidden.<br/>
Once the dialog opens, we just fetch the element from the DOM into our dialog and upon close
we restore the element back into its old DOM position.
</p>
</md-dialog>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>Does anyone know what the problem is?</p>
| <p>Below is the working code. Two changes I've made are </p>
<blockquote>
<p>Included the <code>ng-app</code> tag on body to bootstrap</p>
<p>Included the angular material cdn</p>
</blockquote>
<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><html lang="en" >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<style>
.dialogdemoBasicUsage #popupContainer {
position: relative; }
.dialogdemoBasicUsage .footer {
width: 100%;
text-align: center;
margin-left: 20px; }
.dialogdemoBasicUsage .footer, .dialogdemoBasicUsage .footer > code {
font-size: 0.8em;
margin-top: 50px; }
.dialogdemoBasicUsage button {
width: 200px; }
.dialogdemoBasicUsage div#status {
color: #c60008; }
.dialogdemoBasicUsage .dialog-demo-prerendered md-checkbox {
margin-bottom: 0; }
</style>
<!--
Your HTML content here
-->
<!-- Angular Material requires Angular.js Libraries -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-resource.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.1.1/angular-material.js"></script>
<!-- Your application bootstrap -->
</head>
<body ng-app="dialogDemo">
<div ng-controller="AppCtrl" class="md-padding" id="popupContainer" ng-cloak>
<p class="inset">
Open a dialog over the app's content. Press escape or click outside to close the dialog and
send focus back to the triggering button.
</p>
<div class="dialog-demo-content" layout="row" layout-wrap layout-margin layout-align="center">
<md-button class="md-primary md-raised" ng-click="showAlert($event)" >
Alert Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showConfirm($event)" >
Confirm Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showPrompt($event)" >
Prompt Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showAdvanced($event)">
Custom Dialog
</md-button>
<md-button class="md-primary md-raised" ng-click="showTabDialog($event)" >
Tab Dialog
</md-button>
<md-button class="md-primary md-raised" ng-if="listPrerenderedButton" ng-click="showPrerenderedDialog($event)">
Pre-Rendered Dialog
</md-button>
</div>
<p class="footer">Note: The <b>Confirm</b> dialog does not use <code>$mdDialog.clickOutsideToClose(true)</code>.</p>
<div ng-if="status" id="status">
<b layout="row" layout-align="center center" class="md-padding">
{{status}}
</b>
</div>
<div class="dialog-demo-prerendered">
<md-checkbox ng-model="listPrerenderedButton">Show Pre-Rendered Dialog</md-checkbox>
<p class="md-caption">Sometimes you may not want to compile the dialogs template on each opening.</p>
<md-checkbox ng-model="customFullscreen" aria-label="Fullscreen custom dialog">Use full screen mode for custom dialog</md-checkbox>
<p class="md-caption">Allows the dialog to consume all available space on small devices</p>
</div>
<div style="visibility: hidden">
<div class="md-dialog-container" id="myDialog">
<md-dialog layout-padding>
<h2>Pre-Rendered Dialog</h2>
<p>
This is a pre-rendered dialog, which means that <code>$mdDialog</code> doesn't compile its
template on each opening.
<br/><br/>
The Dialog Element is a static element in the DOM, which is just visually hidden.<br/>
Once the dialog opens, we just fetch the element from the DOM into our dialog and upon close
we restore the element back into its old DOM position.
</p>
</md-dialog>
</div>
</div>
</div>
</body>
<script type="text/javascript">
/**
* You must include the dependency on 'ngMaterial'
*/
angular.module('dialogDemo', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) {
$scope.status = ' ';
$scope.customFullscreen = false;
$scope.showAlert = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
// Modal dialogs should fully cover application
// to prevent interaction outside of dialog
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('This is an alert title')
.textContent('You can specify some description text in here.')
.ariaLabel('Alert Dialog Demo')
.ok('Got it!')
.targetEvent(ev)
);
};
$scope.showConfirm = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.title('Would you like to delete your debt?')
.textContent('All of the banks have agreed to forgive you your debts.')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please do it!')
.cancel('Sounds like a scam');
$mdDialog.show(confirm).then(function() {
$scope.status = 'You decided to get rid of your debt.';
}, function() {
$scope.status = 'You decided to keep your debt.';
});
};
$scope.showPrompt = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.prompt()
.title('What would you name your dog?')
.textContent('Bowser is a common name.')
.placeholder('Dog name')
.ariaLabel('Dog name')
.initialValue('Buddy')
.targetEvent(ev)
.ok('Okay!')
.cancel('I\'m a cat person');
$mdDialog.show(confirm).then(function(result) {
$scope.status = 'You decided to name your dog ' + result + '.';
}, function() {
$scope.status = 'You didn\'t name your dog.';
});
};
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'dialog1.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.showTabDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'tabDialog.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.showPrerenderedDialog = function(ev) {
$mdDialog.show({
controller: DialogController,
contentElement: '#myDialog',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
});
};
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
});
</script>
</html></code></pre>
</div>
</div>
</p>
|
Node.js killed due to out of memory <p>I'm running <code>Node.js</code> on a server with only <code>512MB</code> of <code>RAM</code>. The problem is when I run a script, it will be killed due to out of memory. </p>
<p>By default the <code>Node.js</code> memory limit is <code>512MB</code>. So I think using <code>--max-old-space-size</code> is useless. </p>
<p>Follows the content of <code>/var/log/syslog</code>:</p>
<pre><code>Oct 7 09:24:42 ubuntu-user kernel: [72604.230204] Out of memory: Kill process 6422 (node) score 774 or sacrifice child
Oct 7 09:24:42 ubuntu-user kernel: [72604.230351] Killed process 6422 (node) total-vm:1575132kB, anon-rss:396268kB, file-rss:0kB
</code></pre>
<p>Is there a way to get rid of out of memory without upgrading the memory? (like using persistent storage as additional RAM)</p>
<p>Update:
It's a scraper which uses node module request and cheerio. When it runs, it will open hundreds or thousands of webpage (but not in parallel)</p>
| <p>If you're giving Node access to every last megabyte of the available 512, and it's still not enough, then there's 2 ways forward:</p>
<ol>
<li><p>Reduce the memory requirements of your program. This may or may not be possible. If you want help with this, you should post another question detailing your functionality and memory usage.</p></li>
<li><p>Get more memory for your server. <code>512mb</code> is not much, especially if you're running other services (such as databases or message queues) which require in-memory storage.</p></li>
</ol>
<p>There is the 3rd possibility of using <code>swap</code> space (disk storage that acts as a memory backup), but this will have a strong impact on performance. If you still want it, Google how to set this up for your operating system, there's a lot of articles on the topic. This is OS configuration, not Node's.</p>
|
Small Javascript Program, Change one image for another bug <p>I am learning Javascript, I am writing this program below, you click the picture of an orange, and then it changes into a picture of an apple, but it's not working yet, can anyone help explain what errors are in my program? </p>
<p>Thanks</p>
<p>Here is the code below: </p>
<pre><code><!DOCTYPE HTML>
<html>
<body>
<p Below is an image, click it to see what happens!</p>
<img id="changeimage" onclick="newFunction"() src="orange.jpg" alt="orange" />
<script>
function newFunction ()
{"document.getElementById('changeimage') .src='apple.jpg'"
}
</script>
</body>
</html>
</code></pre>
| <blockquote>
<pre><code>onclick="newFunction"()
</code></pre>
</blockquote>
<p>The attribute value must be entirely inside the <code>"</code> characters. Use <a href="https://validator.w3.org/nu/" rel="nofollow">a validator</a>.</p>
<blockquote>
<pre><code>"document.getElementById('changeimage') .src='apple.jpg'"
</code></pre>
</blockquote>
<p>Your statement must not be inside a string literal. Remove the <code>"</code> characters.</p>
|
If number comparison too slow <p>I have a buffer and I need to make sure I don't exceed certain size. If I do, I want to append the buffer to a file and empty it.</p>
<p>My code:</p>
<pre><code>import sys
MAX_BUFFER_SIZE = 4 * (1024 ** 3)
class MyBuffer(object):
b = ""
def append(self, s):
if sys.getsizeof(self.b) > MAX_BUFFER_SIZE:
#...print to file... empty buffer
self.b = ""
else:
self.b += s
buffer = MyBuffer()
for s in some_text:
buffer.append(s)
</code></pre>
<p>However, this comparison (<code>sys.getsizeof(self.buffer) > MAX_BUFFER_SIZE</code>) is way too slow (ie. without comparison, the whole execution takes less than 1 second, with comparison it takes like 5 minutes).</p>
<p>At the moment I can fit the whole <code>some_string</code> to memory and so buffer actually never gets bigger than <code>MAX_BUFFER_SIZE</code>, but I must make sure my code work for huge files (several TBs in size) too.</p>
<p>Edit:</p>
<p>This code runs in under 1 second:</p>
<pre><code>import sys
buffer = ""
for s in some_text:
buffer += s
#print out to file
</code></pre>
<p>The problem is that the buffer might become too big.</p>
<p>Similarly, this code also runs under 1 second:</p>
<pre><code>import sys
MAX_BUFFER_SIZE = 4 * (1024 ** 3)
class MyBuffer(object):
b = ""
def append(self, s):
print sys.getsizeof(self.b)
buffer = MyBuffer()
for s in some_text:
buffer.append(s)
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>Sorry, the slow part is actually appending to the buffer, not the comparison itself as I thought... When I was testing the code, I commented out the whole <code>if / else</code> statement instead of just the first part.</p>
<p>Hence, is there an efficient way to keep a buffer?</p>
| <p>Undeleting and editing my answer based on edits to the question.</p>
<p>It's incorrect to assume that the comparision is slow. In fact the comparision is fast. Really, really fast. </p>
<p>Why don't you avoid re inventing the wheel by using buffered IO?</p>
<blockquote>
<p>The optional buffering argument specifies the fileâs desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]</p>
</blockquote>
<p><a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">https://docs.python.org/2/library/functions.html#open</a></p>
|
.htaccess Redirect with Cloudflare location <p>I'm really struggling to place redirects into my .htaccess file based on the cloud flare country code. I'm either getting "too many redirect errors" or 500 internal errors using examples from across this site.</p>
<p>I currently have this:</p>
<pre><code>Options +FollowSymLinks
RewriteEngine on
SetEnvIf CF-IPCountry "(.*)$" Country=$1
RewriteCond %{ENV:Country} GB
RewriteRule ^(.*)$ http://example.com/$1 [R,L]
</code></pre>
<p>So I need the default domain to be <a href="http://example.com" rel="nofollow">http://example.com</a></p>
<p>but if a country code of GB comes from cloudflare for example, I need it to redirect to:</p>
<p><a href="http://example.com/gb" rel="nofollow">http://example.com/gb</a></p>
<p>With my limited knowledge of .htaccess is this possible?</p>
| <p>Try with:</p>
<pre><code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP:CF-IPCountry} ^GB$
RewriteCond %{REQUEST_URI} !(?:gif|png|jpg|jpeg|css)$ [NC]
RewriteRule !^gb/ /gb%{REQUEST_URI} [NC,NE,R,L]
</code></pre>
<p>Redirect <code>http://example.com/test</code> to <code>http://example.com/gb/test</code> when the request comes from a user with <code>CF-IPCountry=GB</code> which is not already using a link with <code>/gb/</code></p>
|
How to design a auto generated mail in HTML format using javamail <p>i want to try to generate mail in HTML Table format using CSS in java project</p>
<pre><code> email.append("<html><head><style type='text/css'> .out {border-width:1px,border-color: black}</style></head>");
email.append();
</code></pre>
| <p>Hey simply use template api for email, i prefered Velocity Template</p>
<p>follow steps,
1 create html file of your mail content
2 use Velocity api methods to retrive & replace dynamic content
3 convert in to string and send mail using javamail</p>
<p>click link to learn more <br>
<a href="http://www.javaworld.com/article/2075966/core-java/start-up-the-velocity-template-engine.html" rel="nofollow">http://www.javaworld.com/article/2075966/core-java/start-up-the-velocity-template-engine.html</a></p>
|
Elasticsearch 2.4 nodes does not form cluster with ConnectTransportException <p>I am already running ELK stack with Elasticsearch(ES) 1.7 with docker container with 3 nodes, each running one ES container, running behind <code>nginx</code> server. Now I am trying to upgrade ES to 2.4.0. Root user is not allowed in ES 2.4.0 so I am using <code>-Des.root.insecure.allow=true</code> option.</p>
<pre><code>#Pulling SLES12 thin base image
FROM private-registry-1
#Author
MAINTAINER xyz
# Pre-requisite - Adding repositories
RUN zypper ar private-registry-2
RUN zypper --no-gpg-checks -n refresh
#Install required packages and dependencies
RUN zypper -n in net-tools-1.60-764.185 wget-1.14-7.1 python-2.7.9-14.1 python-base-2.7.9-14.1 tar-1.27.1-7.1
#Downloading elasticsearch executable
ENV ES_VERSION=2.4.0
ENV ES_CLUSTER_NAME=ccs-elasticsearch
ENV ES_DIR="//opt//log-management//elasticsearch"
ENV ES_DATA_PATH="//data"
ENV ES_LOGS_PATH="//var//log"
ENV ES_CONFIG_PATH="${ES_DIR}//config"
ENV ES_REST_PORT=9200
ENV ES_INTERNAL_COM_PORT=9300
WORKDIR /opt/log-management
RUN wget private-registry-3/elasticsearch/elasticsearch/${ES_VERSION}.tar/elasticsearch-${ES_VERSION}.tar.gz --no-check-certificate
RUN tar -xzvf ${ES_DIR}-${ES_VERSION}.tar.gz \
&& rm ${ES_DIR}-${ES_VERSION}.tar.gz \
&& mv ${ES_DIR}-${ES_VERSION} ${ES_DIR} \
&& cp ${ES_DIR}/config/elasticsearch.yml ${ES_CONFIG_PATH}/elasticsearch-default.yml
#Exposing elasticsearch server container port to the HOST
EXPOSE ${ES_REST_PORT} ${ES_INTERNAL_COM_PORT}
#Removing binary files which are not needed
RUN zypper -n rm wget
# Removing zypper repos
RUN zypper rr caspiancs_common
COPY query-crs-es.sh ${ES_DIR}/bin/query-crs-es.sh
RUN chmod +x ${ES_DIR}/bin/query-crs-es.sh
COPY query-crs-wrapper.py ${ES_DIR}/bin/query-crs-wrapper.py
RUN chmod +x ${ES_DIR}/bin/query-crs-wrapper.py
ENV CRS_PARSER_PYTHON_SCRIPT="${ES_DIR}//bin//query-crs-wrapper.py"
#Copy elastic search bootstrap script
COPY elasticsearch-bootstrap-and-run.sh ${ES_DIR}/
RUN chmod +x ${ES_DIR}/elasticsearch-bootstrap-and-run.sh
COPY config-es-cluster ${ES_DIR}/bin/config-es-cluster
RUN chmod +x ${ES_DIR}/bin/config-es-cluster
COPY elasticsearch-config-script ${ES_DIR}/bin/elasticsearch-config-script
RUN chmod +x ${ES_DIR}/bin/elasticsearch-config-script
#Running elasticsearch executable
WORKDIR ${ES_DIR}
ENTRYPOINT ${ES_DIR}/elasticsearch-bootstrap-and-run.sh
</code></pre>
<p>Configuration file will be modified by <code>elasticsearch-config</code> and <code>config-es-cluster</code>, mentioned in Dockerfile, as follows:</p>
<pre><code>#Bootstrap script to configure elasticsearch.yml file
echo "cluster.name: ${ES_CLUSTER_NAME}" > ${ES_CONFIG_PATH}/elasticsearch.yml
echo "path.data: ${ES_DATA_PATH}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "path.logs: ${ES_LOGS_PATH}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#Performance optimization settings
echo "index.number_of_replicas: 1" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "index.number_of_shards: 3" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "discovery.zen.ping.multicast.enabled: false" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "bootstrap.mlockall: true" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "indices.memory.index_buffer_size: 50%" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#Search thread pool
echo "threadpool.search.type: fixed" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "threadpool.search.size: 20" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "threadpool.search.queue_size: 100000" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#Index thread pool
echo "threadpool.index.type: fixed" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "threadpool.index.size: 60" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "threadpool.index.queue_size: 200000" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#publish host as container host address
#echo "network.publish_host: ${CONTAINER_HOST_ADDRESS}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "network.bind_host: ${CONTAINER_HOST_ADDRESS}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "network.publish_host: ${CONTAINER_PRIVATE_IP}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "network.bind_host: ${CONTAINER_PRIVATE_IP}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "network.host: ${CONTAINER_HOST_ADDRESS}" >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "network.host: 0.0.0.0" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "htpp.port: 9200" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#echo "transport.tcp.port: 9300-9400" >> ${ES_CONFIG_PATH}/elasticsearch.yml
#configure elasticsearch.yml for clustering
echo 'discovery.zen.ping.unicast.hosts: [ELASTICSEARCH_IPS] ' >> ${ES_CONFIG_PATH}/elasticsearch.yml
echo "discovery.zen.minimum_master_nodes: 1" >> ${ES_CONFIG_PATH}/elasticsearch.yml
</code></pre>
<p><code>ELASTICSEARCH_IPS</code> is array of IPs of other nodes, which is obtained by all nodes running a script called <code>query-crs-es.sh</code>. Eventually Array will have IPs of other two nodes of cluster. Please note they will be node's IP, not container private IPs.</p>
<p>When ever I try to run the container I use <code>ansible</code>. During start up, all nodes get up but failed to form cluster. I consistently get these error</p>
<p>Node1:</p>
<pre><code>[2016-10-07 09:45:23,313][WARN ][bootstrap ] running as ROOT user. this is a bad idea!
[2016-10-07 09:45:23,474][INFO ][node ] [Dragon Lord] version[2.4.0], pid[1], build[ce9f0c7/2016-08-29T09:14:17Z]
[2016-10-07 09:45:23,474][INFO ][node ] [Dragon Lord] initializing ...
[2016-10-07 09:45:23,970][INFO ][plugins ] [Dragon Lord] modules [reindex, lang-expression, lang-groovy], plugins [], sites []
[2016-10-07 09:45:23,994][INFO ][env ] [Dragon Lord] using [1] data paths, mounts [[/data (/dev/mapper/platform-data)]], net usable_space [2.5tb], net total_space [2.5tb], spins? [possibly], types [xfs]
[2016-10-07 09:45:23,994][INFO ][env ] [Dragon Lord] heap size [989.8mb], compressed ordinary object pointers [true]
[2016-10-07 09:45:24,028][WARN ][threadpool ] [Dragon Lord] requested thread pool size [60] for [index] is too large; setting to maximum [32] instead
[2016-10-07 09:45:25,540][INFO ][node ] [Dragon Lord] initialized
[2016-10-07 09:45:25,540][INFO ][node ] [Dragon Lord] starting ...
[2016-10-07 09:45:25,687][INFO ][transport ] [Dragon Lord] publish_address {172.17.0.15:9300}, bound_addresses {[::]:9300}
[2016-10-07 09:45:25,693][INFO ][discovery ] [Dragon Lord] ccs-elasticsearch/5wNwWJRFRS-2dRY5AGqqGQ
[2016-10-07 09:45:28,721][INFO ][cluster.service ] [Dragon Lord] new_master {Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}, reason: zen-disco-join(elected_as_master, [0] joins received)
[2016-10-07 09:45:28,765][INFO ][http ] [Dragon Lord] publish_address {172.17.0.15:9200}, bound_addresses {[::]:9200}
[2016-10-07 09:45:28,765][INFO ][node ] [Dragon Lord] started
[2016-10-07 09:45:28,856][INFO ][gateway ] [Dragon Lord] recovered [20] indices into cluster_state
</code></pre>
<p>Node2:</p>
<pre><code>[2016-10-07 09:45:58,561][WARN ][bootstrap ] running as ROOT user. this is a bad idea!
[2016-10-07 09:45:58,729][INFO ][node ] [Defensor] version[2.4.0], pid[1], build[ce9f0c7/2016-08-29T09:14:17Z]
[2016-10-07 09:45:58,729][INFO ][node ] [Defensor] initializing ...
[2016-10-07 09:45:59,215][INFO ][plugins ] [Defensor] modules [reindex, lang-expression, lang-groovy], plugins [], sites []
[2016-10-07 09:45:59,237][INFO ][env ] [Defensor] using [1] data paths, mounts [[/data (/dev/mapper/platform-data)]], net usable_space [2.5tb], net total_space [2.5tb], spins? [possibly], types [xfs]
[2016-10-07 09:45:59,237][INFO ][env ] [Defensor] heap size [989.8mb], compressed ordinary object pointers [true]
[2016-10-07 09:45:59,266][WARN ][threadpool ] [Defensor] requested thread pool size [60] for [index] is too large; setting to maximum [32] instead
[2016-10-07 09:46:00,733][INFO ][node ] [Defensor] initialized
[2016-10-07 09:46:00,733][INFO ][node ] [Defensor] starting ...
[2016-10-07 09:46:00,833][INFO ][transport ] [Defensor] publish_address {172.17.0.16:9300}, bound_addresses {[::]:9300}
[2016-10-07 09:46:00,837][INFO ][discovery ] [Defensor] ccs-elasticsearch/RXALMe9NQVmbCz5gg1CwHA
[2016-10-07 09:46:03,876][WARN ][discovery.zen ] [Defensor] failed to connect to master [{Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}], retrying...
ConnectTransportException[[Dragon Lord][172.17.0.15:9300] connect_timeout[30s]]; nested: ConnectException[Connection refused: /172.17.0.15:9300];
at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:1002)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:937)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:911)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:260)
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:444)
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:396)
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4400(ZenDiscovery.java:96)
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1296)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: /172.17.0.15:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at org.jboss.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152)
at org.jboss.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105)
at org.jboss.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
... 3 more
[2016-10-07 09:46:06,899][WARN ][discovery.zen ] [Defensor] failed to connect to master [{Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}], retrying...
ConnectTransportException[[Dragon Lord][172.17.0.15:9300] connect_timeout[30s]]; nested: ConnectException[Connection refused: /172.17.0.15:9300];
at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:1002)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:937)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:911)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:260)
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:444)
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:396)
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4400(ZenDiscovery.java:96)
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1296)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: /172.17.0.15:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at org.jboss.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152)
at org.jboss.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105)
at org.jboss.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
... 3 more
[2016-10-07 09:46:09,917][WARN ][discovery.zen ] [Defensor] failed to connect to master [{Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}], retrying...
ConnectTransportException[[Dragon Lord][172.17.0.15:9300] connect_timeout[30s]]; nested: ConnectException[Connection refused: /172.17.0.15:9300];
</code></pre>
<p>Node3:</p>
<pre><code>[2016-10-07 09:45:58,624][WARN ][bootstrap ] running as ROOT user. this is a bad idea!
[2016-10-07 09:45:58,806][INFO ][node ] [Scarlet Beetle] version[2.4.0], pid[1], build[ce9f0c7/2016-08-29T09:14:17Z]
[2016-10-07 09:45:58,806][INFO ][node ] [Scarlet Beetle] initializing ...
[2016-10-07 09:45:59,341][INFO ][plugins ] [Scarlet Beetle] modules [reindex, lang-expression, lang-groovy], plugins [], sites []
[2016-10-07 09:45:59,363][INFO ][env ] [Scarlet Beetle] using [1] data paths, mounts [[/data (/dev/mapper/platform-data)]], net usable_space [2.5tb], net total_space [2.5tb], spins? [possibly], types [xfs]
[2016-10-07 09:45:59,363][INFO ][env ] [Scarlet Beetle] heap size [989.8mb], compressed ordinary object pointers [true]
[2016-10-07 09:45:59,390][WARN ][threadpool ] [Scarlet Beetle] requested thread pool size [60] for [index] is too large; setting to maximum [32] instead
[2016-10-07 09:46:00,795][INFO ][node ] [Scarlet Beetle] initialized
[2016-10-07 09:46:00,795][INFO ][node ] [Scarlet Beetle] starting ...
[2016-10-07 09:46:00,927][INFO ][transport ] [Scarlet Beetle] publish_address {172.17.0.16:9300}, bound_addresses {[::]:9300}
[2016-10-07 09:46:00,931][INFO ][discovery ] [Scarlet Beetle] ccs-elasticsearch/SFWrVwKRSUu--4KiZK4Kfg
[2016-10-07 09:46:03,965][WARN ][discovery.zen ] [Scarlet Beetle] failed to connect to master [{Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}], retrying...
ConnectTransportException[[Dragon Lord][172.17.0.15:9300] connect_timeout[30s]]; nested: ConnectException[Connection refused: /172.17.0.15:9300];
at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:1002)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:937)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:911)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:260)
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:444)
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:396)
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4400(ZenDiscovery.java:96)
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1296)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: /172.17.0.15:9300
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at org.jboss.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152)
at org.jboss.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105)
at org.jboss.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42)
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
... 3 more
[2016-10-07 09:46:06,990][WARN ][discovery.zen ] [Scarlet Beetle] failed to connect to master [{Dragon Lord}{5wNwWJRFRS-2dRY5AGqqGQ}{172.17.0.15}{172.17.0.15:9300}], retrying...
ConnectTransportException[[Dragon Lord][172.17.0.15:9300] connect_timeout[30s]]; nested: ConnectException[Connection refused: /172.17.0.15:9300];
at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:1002)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:937)
at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:911)
at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:260)
at org.elasticsearch.discovery.zen.ZenDiscovery.joinElectedMaster(ZenDiscovery.java:444)
at org.elasticsearch.discovery.zen.ZenDiscovery.innerJoinCluster(ZenDiscovery.java:396)
at org.elasticsearch.discovery.zen.ZenDiscovery.access$4400(ZenDiscovery.java:96)
at org.elasticsearch.discovery.zen.ZenDiscovery$JoinThreadControl$1.run(ZenDiscovery.java:1296)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>As you can see from logs, Node 2 and 3 are aware of master, Node1, but unable to connect. I have tried most of the configurations about <code>network.host</code> which you can see commented in configuration code and neither of them work.
Any leads will be appreciated.</p>
<p>This is the state of ports:</p>
<pre><code> netstat -nlp | grep 9200
tcp 0 0 10.240.135.140:9200 0.0.0.0:* LISTEN 188116/docker-proxy
tcp 0 0 10.240.137.112:9200 0.0.0.0:* LISTEN 187240/haproxy
netstat -nlp | grep 9300
tcp 0 0 :::9300 :::* LISTEN 188085/docker-proxy
</code></pre>
| <p>I was able to form cluster with following settings</p>
<p><code>network.publish_host=CONTAINER_HOST_ADDRESS</code> i.e. address of node where the
container is running. </p>
<pre><code>network.bind_host=0.0.0.0
transport.publish_port=9300
transport.publish_host=CONTAINER_HOST_ADDRESS
</code></pre>
<p><code>tranport.publish_host</code> is important when your are running ES behind proxy/ load balancer such nginx or haproxy.</p>
|
Connection to IP is refused when trying to connect from android application <p>I am trying to connect my android app with server which is running in same PC,ip is 192.168.1.129,and tomcat port is 8081,getting below issue,Can any one help me to resolve this?</p>
<pre><code>10-07 15:51:45.672 29710-5937/com.net.app W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.129:8081 refused
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:188)
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:379)
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:580)
10-07 15:51:45.673 29710-5937/com.net.app W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:503)
10-07 15:51:45.674 29710-5937/com.net.app W/System.err: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:481)
10-07 15:51:45.679 29710-5937/com.net.app W/System.err: at com.chronicwatch.app.utils.WebRequest.post(WebRequest.java:72)
10-07 15:51:45.679 29710-5937/com.net.app W/System.err: at com.chronicwatch.app.utils.WebRequest.loadDataFromNetwork(WebRequest.java:54)
10-07 15:51:45.679 29710-5937/com.net.app W/System.err: at com.octo.android.robospice.request.CachedSpiceRequest.loadDataFromNetwork(CachedSpiceRequest.java:48)
10-07 15:51:45.680 29710-5937/com.net.app W/System.err: at com.octo.android.robospice.request.DefaultRequestRunner.processRequest(DefaultRequestRunner.java:150)
10-07 15:51:45.680 29710-5937/com.net.app W/System.err: at com.octo.android.robospice.request.DefaultRequestRunner$1.run(DefaultRequestRunner.java:217)
10-07 15:51:45.680 29710-5937/com.net.app W/System.err: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
10-07 15:51:45.680 29710-5937/com.net.app W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-07 15:51:45.681 29710-5937/com.net.app W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-07 15:51:45.681 29710-5937/com.net.app W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-07 15:51:45.681 29710-5937/com.net.app W/System.err: at java.lang.Thread.run(Thread.java:818)
10-07 15:51:45.681 29710-5937/com.net.app W/System.err: Caused by: java.net.ConnectException: failed to connect to /192.168.1.129 (port 8081) after 15000ms: isConnected failed: EHOSTUNREACH (No route to host)
10-07 15:51:45.682 29710-5937/com.net.app W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
10-07 15:51:45.682 29710-5937/com.net.app W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at java.net.Socket.connect(Socket.java:882)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
10-07 15:51:45.683 29710-5937/com.net.app W/System.err: at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
10-07 15:51:45.685 29710-5937/com.net.app W/System.err: ... 16 more
10-07 15:51:45.685 29710-5937/com.net.app W/System.err: Caused by: android.system.ErrnoException: isConnected failed: EHOSTUNREACH (No route to host)
10-07 15:51:45.686 29710-5937/com.net.app W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
10-07 15:51:45.686 29710-5937/com.net.app W/System.err: ... 23 more
</code></pre>
| <p>There can be two problems. First the firewall can prevent access. Switch it off for a test. Second: Maybe Tomcat is bound to localhost/127.0.0.1 only. Have a check in its settings. </p>
|
How to match json response in 2 requests? <p>I have a json response in 1 request like this:</p>
<blockquote>
<p>{"total":1,"page":1,"records":2,"rows":[{"id":1034,"item_type_val":"Business
Requirement","field_name":"Assigned To","invalid_value":"Jmeter
System","dep_value":"","dep_field":""},{"id":1033,"item_type_val":"Risk","field_name":"Category","invalid_value":"Energy","dep_value":"Logged
User","dep_field":"Assigned To"}]}</p>
</blockquote>
<p>and in 2nd request like this:</p>
<blockquote>
<p>{"total":1,"page":1,"records":2,"rows":[{"id":1100,"item_type_val":"Business
Requirement","field_name":"Assigned To","invalid_value":"Jmeter
System","dep_value":"","dep_field":""},{"id":1111,"item_type_val":"Risk","field_name":"Category","invalid_value":"Energy","dep_value":"Logged
User","dep_field":"Assigned To"}]}</p>
</blockquote>
<p>Both are same but different id's. I need to verify the 1st json response from 2nd json response and compare both that both are same or not. here both are same but having different id's which should be acceptable. how can i do this by regex so i can ignore the id's and match whole content?</p>
| <p>Not sure if you can do it with a single regex but other way out is you can create a map of it and then compare everything except 'id' </p>
|
how to listen android serial port data in my BroadcastReceiver <p>I made an application with serial port comminication systems. But i need this. When serial data received, application triggers and opens the screen.</p>
<p>I already use USB_DEVICE_ATTACHED but i need something like that action "USB_DATA_RECEIVED". Is it possible? </p>
<p>XXX is a action that i need.</p>
<pre><code><receiver
android:name=".receivers.SerialDataReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.XXX" />
</intent-filter>
</receiver>
</code></pre>
| <p>There is no default action for this. </p>
<p>In your custom receiver, get the port and use this.</p>
<ul>
<li>I use <a href="https://github.com/mik3y/usb-serial-for-android" rel="nofollow">mik3y</a> and/ or <a href="https://github.com/felHR85/UsbSerial" rel="nofollow">felHR85</a> solution for serial port</li>
</ul>
<p>This is how it likes;</p>
<pre><code>public class CustomBroadcastReceiver extends BroadcastReceiver {
public static final String BROADCAST = "arda.kaplan.android.action.broadcast";
@Override
public void onReceive(final Context context, Intent intent) {
findDevices(context);
}
private void findDevices(final Context context) {
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
final List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
final List<UsbSerialPort> result = new ArrayList<>();
for (final UsbSerialDriver driver : drivers) {
final List<UsbSerialPort> ports = driver.getPorts();
result.addAll(ports);
}
if (result.size() > 0) {
UsbSerialPort usbSerialPort = result.get(0);
UsbSerialDriver driver = usbSerialPort.getDriver();
UsbDevice device = driver.getDevice();
UsbDeviceConnection usbConnection = usbManager.openDevice(usbSerialPort.getDriver().getDevice());
final UsbSerialDevice usbSerialDevice = UsbSerialDevice.createUsbSerialDevice(device, usbConnection);
usbSerialDevice.open();
usbSerialDevice.setBaudRate(9600);
usbSerialDevice.setDataBits(UsbSerialInterface.DATA_BITS_8);
usbSerialDevice.setStopBits(UsbSerialInterface.STOP_BITS_1);
usbSerialDevice.setParity(UsbSerialInterface.PARITY_NONE);
usbSerialDevice.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
usbSerialDevice.read(new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(final byte[] data) {
Intent startAppIntent = new Intent(context, ComingFromBroadcastReceiverActivity.class);
startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startAppIntent.putExtra(ComingFromBroadcastReceiverActivity.KEY, new String(data));
context.startActivity(startAppIntent);
}
});
}
}
</code></pre>
<p>}</p>
<p>And this code for registering custom receiver</p>
<pre><code>Intent intent = new Intent(CustomBroadcastReceiver.BROADCAST);
Bundle extras = new Bundle();
sendBroadcast(intent);
</code></pre>
<p>And this is manifest part</p>
<pre><code><receiver android:name=".receivers.CustomBroadcastReceiver">
<intent-filter>
<action android:name="arda.kaplan.android.action.broadcast" />
</intent-filter>
</receiver>
</code></pre>
|
Getting slightly different input in each data fetch operation <p>I am following the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/models/image/cifar10" rel="nofollow">cifar10 tutorial</a> and fetch my data using <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10_input.py#L197" rel="nofollow">inputs()</a> function called by <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10.py#L163" rel="nofollow">cifar10.inputs</a>. My code is as follows:</p>
<pre><code>import tensorflow as tf
import cifar10
# Get images and labels
images, labels = cifar10.inputs(eval_data='test')
# Start running operations on the Graph.
sess = tf.Session()
sess.run(tf.initialize_all_variables())
# Start the queue runners.
tf.train.start_queue_runners(sess=sess)
img, lab = sess.run([images, labels])
print(lab)
</code></pre>
<p>To test this, I run the code with batch size 10 and print the <strong>labels</strong> of the first batch. I expect the same output each time I execute this code, because <strong>shuffle=False</strong> in the <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10_input.py#L197" rel="nofollow">inputs()</a> function. However, I observe slightly different labels in each execution, for example outputs from three consecutive executions are:</p>
<pre><code>run-1: [0 1 2 2 1 1 1 9 8 8]
run-2: [1 2 2 0 1 1 1 9 8 8]
run-3: [0 2 2 1 1 1 1 9 8 8]
</code></pre>
<p>I would like to know: </p>
<ol>
<li>Why I am getting different labels although shuffle is off? and </li>
<li>What should I do to obtain the same labels at each execution?</li>
</ol>
| <p>The queue runners you are starting there are multiple threads loading data from disk and adding it to the queue. <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10_input.py#L117" rel="nofollow">There are 16 of them by default</a>. </p>
<p>The queue itself is thread-safe, but there is nothing enforcing order.</p>
<p>So even though you're not using the shuffling queue, the race-condition between the threads to fetch and insert the items randomizes the order slightly.</p>
<p>The easiest way to make it completely repeatable is to only use 1 thread to fetch items. This will probably be slow.</p>
|
Polymer: Passing array to property via markup <p>I have created an element which has an array property 'icon-buttons'. I can pass the array using javascript but when I pass it in the markup itself, it does not work.</p>
<p>Property:</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>iconButtons: {
type: Array,//tried Object as well
value: function() { return []; }
}</code></pre>
</div>
</div>
</p>
<p>Usage:</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><my-card heading="Demo 2" icon-buttons='[
{"name" : "edit", "icon" : "icons:create", "click" : "toggleMode();", "disabled" : false},
{"name" : "close", "icon" : "icons:clear", "click" : "alert(''close'');", "disabled" : false},
{"name" : "maximize", "icon" : "icons:fullscreen", "click" : "alert(''maximize'');", "disabled" : false},
{"name" : "more", "icon" : "icons:more-vert", "click" : "alert(''more'');", "disabled" : true}
]'>
<div class="card-content">
<list mode="edit"></list>
</div>
<div class="card-actions">
<paper-button>Hello</paper-button>
<paper-button>Bye</paper-button>
</div>
</my-card></code></pre>
</div>
</div>
</p>
<p>I have passed a JSON object similarly for another element. But this one with Array does not work.
What is wrong in this?</p>
| <p>a1626 is right, use <code>\"</code> instead of <code>''</code> in your alerts</p>
<pre><code>... "click": "alert(\"close\");", ...
</code></pre>
|
ASP.NET Dropdownlist into jquery variabel <p>I have 2 code,</p>
<p>This is the First:</p>
<pre><code> $("#Button1")
.click(function () {
var index;
var select = $("#DropDownList1");
var select = document.getElementById("DropDownList1");
var myindex = ["zero", "one", "two", "three"];
for (index = 0; index < myindex.length; index++) {
select.appendChild(new Option(myindex[index]));
}
});
</code></pre>
<p>This is the Second:</p>
<pre><code> $("#Button1")
.click(function () {
var index;
var select = document.getElementById("DropDownList1");
var myindex = ["zero", "one", "two", "three"];
for (index = 0; index < myindex.length; index++) {
select.appendChild(new Option(myindex[index]));
}
});
</code></pre>
<p>Why the first code doesn't work? </p>
<pre><code> var select = $("#DropDownList1");
</code></pre>
<p>I have to change it to</p>
<pre><code> var select = document.getElementById("DropDownList1");
</code></pre>
<p>I want to turn $("#DropDownList1") to a variabel.</p>
| <p><code>appendChild</code> is not a jquery function. </p>
<p>Assuming your first code has a paste-typo with the extra <code>document.getElementById</code>, you can use <code>select.get(0).appendChild()</code> to convert a jquery object to a DOM element.</p>
<pre><code> var index;
var select = $("#DropDownList1");
var myindex = ["zero", "one", "two", "three"];
for (index = 0; index < myindex.length; index++) {
select.get(0).appendChild(new Option(myindex[index]));
}
</code></pre>
<p>or you could continue with jquery, eg:</p>
<pre><code> for (index = 0; index < myindex.length; index++) {
select.append("<option>" + myindex[index] + "</option>");
}
</code></pre>
|
Targeting placeholder text using sass <p>So I designed a flat signup form for a website to learn front-end developing. I used Mailchimp for the form, and this all seems to work. Now I have styled up everything how it supposed to be, however I cannot get this placeholder text to have a normal opacity. To me, it seems its opacity is lower than '1', or it does not show up completely 'white'.</p>
<p>I have tried a couple of things, but nothing works; "Opacity 1" and trying to select the placeholder with the vendor fixes mentioned in other posts. I also tried to come up with a mixin to target the vendor fixes (mentioned as a solution in previous posts), but nothing happened.</p>
<p>Thanks! </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>.newsletter-container {
display: flex;
height: 200px;
background-color: #f4f4f4;
align-items: center;
justify-content: center;
}
.newsletter-container .newsletter-form {
max-width: 700px;
width: 100%;
}
.newsletter-container .newsletter-form .form-display {
background: #f4f4f4;
display: flex;
}
.newsletter-container .newsletter-form .form-display .mc-field-group {
flex: 2;
}
.newsletter-container .newsletter-form .form-display input {
background: #1d1c1c;
border: 0;
padding: 0;
color: white;
height: 50px;
width: 100%;
font-family: "Open Sans";
font-size: 12px;
}
.newsletter-container .newsletter-form .form-display input[type="submit"] {
flex: 1;
border-left: 5px solid #f4f4f4;
text-transform: uppercase;
}
.newsletter-container .newsletter-form .form-display input[type="text"] {
padding-left: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newsletter-container">
<div class="newsletter-form">
<div id="mc_embed_signup">
<form action="//facebook.us14.list-manage.com/subscribe/post?u=868cbba0c64a29c8fb08f6aef&amp;id=eda72469b9" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<div id="mc_embed_signup_scroll">
<div class="form-display">
<div class="mc-field-group">
<label for="mce-FNAME"></label>
<input type="text" value="" name="FNAME" class="" id="mce-FNAME" placeholder="Full Name">
</div>
<div class="mc-field-group">
<label for="mce-EMAIL"></label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Adress">
</div>
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_868cbba0c64a29c8fb08f6aef_eda72469b9" tabindex="-1" value=""></div>
</div>
</form>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>All are correct, except you need to specifically change the color of the input placeholder for different browsers, try:</p>
<p>WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element</p>
<pre><code>::-webkit-input-placeholder {
color: white;
}
</code></pre>
<p>Mozilla Firefox 4 to 18 are using a pseudo-class: <code>:-moz-placeholder</code></p>
<p>Mozilla Firefox 19+ are using a pseudo-element: <code>::-moz-placeholder</code> (double colon)</p>
<p>Internet Explorer 10 and 11 are using a pseudo-class: <code>:-ms-input-placeholder</code>.</p>
<p>Browsers <=IE9 & <=Opera12, does not support CSS selectors for placeholders (<em>no surprise there!</em>)</p>
<pre><code>//affects all input placeholders across webkit browsers
::-webkit-input-placeholder {
color: white;
}
//affects all input placeholders across webkit browsers
//no change in any of your other styles
.newsletter-container {
display: flex;
height: 200px;
background-color: #f4f4f4;
align-items: center;
justify-content: center;
}
//no change in any of your other styles
</code></pre>
<p>Hope this helped..</p>
<p><strong>Update:</strong></p>
<p>This helped the OP.</p>
<blockquote>
<p>Also check if the <code>::-webkit-input-placeholder</code> is getting overridden by any other files like <code>normalize.scss</code> etc.</p>
</blockquote>
|
How to return to home activity on single backpressed <p>I want to return to home activity on single backpressed and on double backpressed exit from app but it not working properly i had added code below kindly help me.</p>
<pre><code> if (doubleBackToExitPressedOnce)
{
replaceFragment(new HomeActivity());
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit.", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
</code></pre>
<p>kindly help me. </p>
| <p>just add this in your Handler run method</p>
<pre><code> @Override
public void run() {
replaceFragment(new HomeActivity());
ActivityName.super.onBackPressed();
doubleBackToExitPressedOnce = false;
}
</code></pre>
<p><strong>OR</strong>
make else method like this</p>
<pre><code>else{
replaceFragment(new HomeActivity());
super.onBackPressed();
}
</code></pre>
|
ng-repeat fails due to duplicates <p>I'm trying to <a href="http://stackoverflow.com/questions/16824853/way-to-ng-repeat-defined-number-of-times-instead-of-repeating-over-array#16824944">ng-repeat something a defined number of times</a>:</p>
<p>Here's the (reduced) HTML:</p>
<pre><code><div class="row" ng-repeat="r in getNumber(size) track by $rowIndex">
<span class="slot" data-y-coord="{{$rowIndex}}"></span>
</div>
</code></pre>
<p>And here's the JS:</p>
<pre><code>$scope.size = 48;
$scope.getNumber = (number) => {
var arr = [];
for(var i=0; i<number; i++) {
arr.push(i);
}
return arr;
};
</code></pre>
<p>I get the error</p>
<pre><code>Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: r in getNumber(size) track by $rowIndex, Duplicate key: undefined, Duplicate value: 1
</code></pre>
<p>which I think is weird because I am using 'track by'.</p>
| <p>try this,change <code>$rowIndex</code> to <code>$index</code></p>
<pre><code><div class="row" ng-repeat="r in getNumber(size) track by $index">
<span class="slot" data-y-coord="{{$index}}"></span>
</div>
</code></pre>
<p>AngularJS does not allow duplicates in a ng-repeat directive. <a href="https://docs.angularjs.org/error/ngRepeat/dupes" rel="nofollow">link</a></p>
|
Python function returning string which is function name, need to execute the returned statement <p>1) Function 1 encodes the string</p>
<p>def Encode(String):<br>
..<br>
..code block<br>
..<br>
return String</p>
<p>2) Function 2 return the string, which actually forms function call of Function 1</p>
<p>def FunctionReturningEncodeFuntionCall(String):<br>
..<br>
..code block<br>
..<br>
return EncodeFunctionString<br></p>
<p>3) In Function 3 parse the string and pass to Function 2 to form Function 1 call and execute the Function 1 and store its returned value</p>
<p>def LastFuntionToAssignValue(String):<br>
..<br>
..code block<br>
..<br>
a = exec FunctionReturningMyFuntionCall("abcd") <br>
print a</p>
<p>Thanks in advance</p>
| <p>Consider using the <a href="https://docs.python.org/2.0/ref/exec.html" rel="nofollow">exec statement</a></p>
|
Mindset behind recursive functions <p>I'm trying to learn recursive functions, but I can't seem to wrap my head around the idea of recursion. I've watched videos on recursions and saw tutorials, but I cant think of the recursion needed when I try to solve them myself. However, I can solve those pretty quickly using loops and iterations.</p>
<p>For example, I saw a question about finding the number of digits in a number, and the answer was:</p>
<pre><code>def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
</code></pre>
<p>I know that the <code>if</code> is a point where the recursion will stop, but I don't understand how or why the <code>else</code> part works even after looking at the answer. </p>
<p>What should my thought process be like when using recursive functions?</p>
| <p>Recursion is very useful if the problem at hand is recursive as well. One such problem is traversing a tree-like datastructure. Any computer program that is being compiled results in such a structure called the syntax tree. The compiler goes through the tree and generates code for the branches it finds. I know this in itself doesn't help you to comprehend recursion, but it's just to make clear that recursion is a very practical concept. Only the examples given are mostly rather artificial, since the 'real' examples need too much prior knowledge.</p>
<p>As for your example, some prints should make clear what's going on:</p>
<pre><code>def digit(n):
print ('Entering "digit" with n == {}'.format (n))
if n < 10:
print ('In the "if" now')
return 1
else:
print ('In the "else" now')
return 1 + digit(n/10)
print (digit (10000))
</code></pre>
<p>Following modified code makes it even more clear, try to follow execution step by step:</p>
<pre><code>def digit(n):
print ('\nCalling "digit" with n == {}'.format (n))
if n < 10:
print ('In the "if" now for n == {}'.format (n))
result = 1
print ('Exiting "digit" from the "if" with n == {}, result now is {}'.format (n, result))
return result
else:
print ('In the "else" now for n == {}'.format (n))
result = 1 + digit(n/10)
print ('Exiting "digit" with n == {}, result now is {}'.format (n, result))
return result
print ('Nr of digits is: {}'.format (digit (10000)))
</code></pre>
<p>It prints:</p>
<pre><code>D:\aaa>call C:\Python35\python.exe so.py
Calling "digit" with n == 10000
In the "else" now for n == 10000
Calling "digit" with n == 1000.0
In the "else" now for n == 1000.0
Calling "digit" with n == 100.0
In the "else" now for n == 100.0
Calling "digit" with n == 10.0
In the "else" now for n == 10.0
Calling "digit" with n == 1.0
In the "if" now for n == 1.0
Exiting "digit" from the "if" with n == 1.0, result now is 1
Exiting "digit" with n == 10.0, result now is 2
Exiting "digit" with n == 100.0, result now is 3
Exiting "digit" with n == 1000.0, result now is 4
Exiting "digit" with n == 10000, result now is 5
Nr of digits is: 5
</code></pre>
<p>What also helps is the following: With each call of the function, a new chunk of local data is piled upon something in memory called the stack. In this case that chunk of data is just parameter n which is stored as a local variable. And with each exit of a call (so at one of the returns), this chunk of data is taken off the stack and thrown away. In neat terms: each function call has its own stack frame.</p>
<p>Take some pieces of paper, and for each call (see output), write n on it and put it on a stack. Then for each exit throw away the top paper. While this is no magic bullet it may help your imagination.</p>
<p>Bottom line: it may take you considerable time before a "click" is made in your brain. But it's really worth while. Don't be amazed if it takes a week or longer. That's normal, although not all programmers will admit it. Try to follow program execution step by step, using the output in my answer and a pile of paper notes. After a while: click... Don't stare the problem for longer than a quarter if you get dizzy, try again next day (from experience...).</p>
<p>Note to Python specialists: The 'stack' model in Python is only conceptually, while in e.g. C++ it is real. But it's a good model for the behavior of recursion.</p>
|
Concatenate/append bitcoin address to image_tag source Rails <p>I have a hash that contains a bitcoin address.
The hash looks like this:</p>
<pre><code>{"status"=>"success", "data"=>{"user_id"=>2, "address"=>"2NE9LK7LGKr9dStvxpF64ucKyoywnfcLd1W", "label"=>"slesle91", "available_balance"=>"0.00000000", "pending_received_balance"=>"0.00000000"}}
</code></pre>
<p>I can display the bitcoin address via:</p>
<pre><code><%= @address["data"]["address"] %>
</code></pre>
<p>How can I add this to an image_tag to get a url like this that create a qr code:</p>
<pre><code><%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl="2NE9LK7LGKr9dStvxpF64ucKyoywnfcLd1W" %>
</code></pre>
<p>So I am looking for a solution to do something similar to:</p>
<pre><code>%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl="<%= @address["data"]["address"] %>" %>
</code></pre>
<p>Any comment or assistance will be greatly appreciated.</p>
| <p>I managed to resolve this in the following manner:</p>
<pre><code><%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=#{@balance["data"]["address"]}" %>
</code></pre>
|
sitecore reporting DB - performance <p>we are on 8.0, Update 4.</p>
<p>Our Azure MS-SQL reporting database is showing massives performance spiking every day between 5am and 8am. We have 2 CD servers, and one CM server, the CM servers' app pool gets recycled daily at 5am, so i guess the spike is related to that. </p>
<p>This screenshot shows the query that is causing the issue, and you will notice the massive number of times that it gets run, circa 40k times over 4 hours. Does anyone know what the query is doing and how we might mitigate this? </p>
<p><a href="http://i.stack.imgur.com/KTmVv.png" rel="nofollow"><img src="http://i.stack.imgur.com/KTmVv.png" alt="enter image description here"></a></p>
| <p>This is a known issue published on the Sitecore KB <a href="https://kb.sitecore.net/articles/028657" rel="nofollow">https://kb.sitecore.net/articles/028657</a>. </p>
<p>Your case is #2. <strong>Disable the periodic index rebuild</strong></p>
<p>Basically, the problem occurs because of the scheduled suggested_tests_index rebuild.</p>
<p>Sitecore suggests removing the <strong>/sitecore/system/Tasks/Schedules/Content Testing/Rebuild Suggested Tests Index</strong> item from the master database.
This item is responsible for periodic index rebuilds.</p>
<p>However, there are some implications. Check the article. </p>
|
I want to edit data without editing the email only edit another input field <p>basic email check is clear but if any user wants to update the data with same email Id then that message should not display.... </p>
<pre><code>if(isset($_GET['edited']))
{
$sql="SELECT * FROM user WHERE Id=".$_REQUEST['id']." ";
//echo "SELECT * FROM user WHERE Id=".$_REQUEST['id']."";
$query=mysqli_query($connect,$sql);
$user=mysqli_fetch_array($query);
$Id=$user['Id'];
$name=$user['name'];
$email=$user['email'];
$gender=$user['gender'];
$purpose=$user['purpose'];
$MobileNumber=$user['MobileNumber'];
$Status=$user['Status'];
}
</code></pre>
| <p>Looking at the code you have provided and not really understanding what you are trying to do, have a look at this and see if it helps.</p>
<pre><code>$query = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0)
{
echo 'Email is already exists!';
$sql="UPDATE user SET name='$name',email='$email',gender='$gender',purpose='$purpoââse',MobileNumber='$MââobileNumber', Status='$Status' WHERE Id = ".$_REQUEST['txtid'];
}
else
{
if($_POST['txtid']=="0")
{
$sql = "INSERT INTO user(name,email,gender,purpose,MobileNumber) values ('$name','ââ$email','$gender','$ââpurpose','$MobileNumââber')";
}
}
$query=mysqli_query($connect,$sql);
</code></pre>
<p>This is untested and I am not sure if you have provided all the code so you may need to edit it a bit before use.</p>
<p>The basic though is that the check for the existing email is completed, if that shows that there is an row containing that email address then you update the row with the new information. The the email address is not in the database then insert it.</p>
|
hide and show component with angularjs <p>I am creating a web app in c# but i am using angularjs for fetching data from sql-server and there is one issue for me</p>
<p>as i am using angular for fetching the data I want to use angular for showing and hiding the required component</p>
<p>like there is a dropdownlist</p>
<pre><code><select>
<option>Guest</option>
<option>Google</option>
<option>User</option>
</select>
</code></pre>
<p>and i have 3 textboxes</p>
<pre><code><input type="text" visible="false" name="Guest">
<input type="text" visible="false" name="Google">
<input type="text" visible="false" name="User">
</code></pre>
<p>If a user select Guest from dropdownlist</p>
<p><code><input type="text" visible="false" name="Guest"></code>
this textbox should be visible</p>
<p>If a user select Google from dropdownlist</p>
<p><code><input type="text" visible="false" name="Google"></code>
this textbox should be visible</p>
<p>If a user select User from dropdownlist</p>
<p><code><input type="text" visible="false" name="User"></code>
this textbox should be visible</p>
<p>now I want to know how to hide or show these component in angularJS</p>
| <p>If you are really interested to do it in angular way the set <code>ng-model</code> and <code>ng-show</code> first for all text controls.</p>
<pre><code><select ng-model="ddSelect" ng-change="getOptions()">
<option>Guest</option>
<option>Google</option>
<option>User</option>
</select>
<input type="text" visible="false" name="Guest" ng-model="txtGuest" ng-show="isGuestVisible">
<input type="text" visible="false" name="Google" ng-model="txtGoogle" ng-show="isGoogleVisible">
<input type="text" visible="false" name="User" ng-model="txtUser" ng-show="isUserVisible">
</code></pre>
<p>Now in controller get hold of <code>getOptions</code></p>
<pre><code>$scope.isGuestVisible = false;
$scope.isGoogleVisible = false;
$scope.isUserVisible = false;
$scope.getOptions = function(){
if($scope.ddSelect === "Guest"){
$scope.isGuestVisible = true;
$scope.isGoogleVisible = false;
$scope.isUserVisible = false;
}
}
//Likewise check other options and set ng-show.
</code></pre>
<p>Note: This solution is given based on your exact case study .It could be made more dynamic thus reducing if.</p>
|
Window.Activate() not working properly <p>Sometime, <code>Window.Activate()</code> not working in other system.</p>
<pre><code>var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(y => y.IsActive) ?? Application.Current.Windows.OfType<Window>().FirstOrDefault();
if (window != null)
window.Activate();
</code></pre>
<p>I want a solution which should not fail in any system and also want to know the main cause of this.</p>
| <p>It can fail if you call it from non-UI thread. In that case you should to wrap call into dispatcher.</p>
<pre><code>Application.Current.Dispatcher.Invoke(() =>
{
///.... UI stuff
});
</code></pre>
|
R - Time Spent in Interval <p>I have a data frame of start and end dates/times, like so:</p>
<pre><code>start_date <- c("20/09/2016 01:20" , "22/09/2016 01:20", "28/09/2016 22:16", "16/09/2016 21:01")
end_date <- c("20/09/2016 06:20" , "24/09/2016 22:40", "29/09/2016 03:20", "16/09/2016 23:01")
df <- data.frame(start_date, end_date)
</code></pre>
<p>And some time intervals:</p>
<pre><code>interval_start <- "21:00"
interval_end <- "02:00"
</code></pre>
<p>I would like to create a new column in df which calculates the total number of minutes each instance spent within the interval period. For example, row 1 spent 40 minutes in the interval period.</p>
<p>Does anyone know how this could be achieved? Thanks.</p>
| <p>Package <code>lubridate</code> helps doing the job. The main problem to tackle is long time periods, where the interval occurs several times (I solved it with the inner <code>for</code> loop) and the key function is <code>intersect</code>, which gives the simple answer to the problem "Intersection of two intervals". Summing up all the intersections gives the solution per row.</p>
<pre><code>library(lubridate)
start_date <- c("20/09/2016 01:20" , "22/09/2016 01:20", "28/09/2016 22:16", "16/09/2016 21:01")
end_date <- c("20/09/2016 06:20" , "24/09/2016 22:40", "29/09/2016 03:20", "16/09/2016 23:01")
start_date <- dmy_hm(start_date)
end_date <- dmy_hm(end_date)
df <- data.frame(start_date, end_date)
time_spent <- c()
# loop through each row
for (i in 1:nrow(df)){
row <- df[i,]
out <- 0
period <- interval(row$start_date, row$end_date)
#1. Set as many intervals for this time periods as there are days
for(day in seq(day(row$start_date) - 1, day(row$end_date), 1)){
myInterval <- interval(dmy_hm(paste(day,
month(row$start_date),
year(row$start_date),
"21:00")),
dmy_hm(paste(day+1,
month(row$start_date),
year(row$start_date),
"02:00")))
# calculate intersection
timedifference <- intersect(period, myInterval)
if(!is.na(timedifference)){
out <- out + as.numeric(timedifference)/60
}
}
time_spent <- c(time_spent, out)
}
df$time_spent <- time_spent
</code></pre>
<p>The solution is</p>
<pre><code>> df$time_spent
[1] 40 740 224 120
</code></pre>
|
Yii2 admin pretty urls not working in nginx <p>I have deployed yii2 in nginx server and working fine..I can access the admin section by /admin url but no other urls under /admin is not working. I have enabled pretty urls in the application, what could be the nginx config I need to change </p>
| <p>Can you add your nginx conf ? </p>
<p>I also faced same issue, do you use this conf ?</p>
<pre><code>server {
charset utf-8;
client_max_body_size 128M;
listen 80; ## listen for ipv4
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
server_name mysite.local;
root /path/to/basic/web;
index index.php;
access_log /path/to/basic/log/access.log;
error_log /path/to/basic/log/error.log;
location / {
# Redirect everything that isn't a real file to index.php
try_files $uri $uri/ /index.php$is_args$args;
}
# uncomment to avoid processing of calls to non-existing static files by Yii
#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
# try_files $uri =404;
#}
#error_page 404 /404.html;
# deny accessing php files for the /assets directory
location ~ ^/assets/.*\.php$ {
deny all;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
try_files $uri =404;
}
location ~* /\. {
deny all;
}
</code></pre>
<p>}</p>
<p><a href="http://www.yiiframework.com/doc-2.0/guide-start-installation.html" rel="nofollow">more at here</a></p>
|
Swift Extension For Generic type compiler error <p>I have created extension of Cache class for NSData generic type (<a href="https://github.com/aschuch/AwesomeCache" rel="nofollow">https://github.com/aschuch/AwesomeCache</a>)</p>
<p>First method works fine, but <em>setIntegerValue</em> show compiler error:
"Cannot invoke 'setObject' with an argument list of type '(NSData, forKey: String, expires: CacheExpiry)'" at line: <em>self.setObject(data, forKey: forKey, expires: expires)</em></p>
<pre><code>extension Cache where T: NSData {
func integerForKey(key: String) -> Int? {
if let data = self.objectForKey(key), string = String(data: data, encoding: NSUTF8StringEncoding), intValue = Int(string) {
return intValue
}
return nil
}
func setIntegerValue(integerValue: Int, forKey: String, expires: CacheExpiry = .Never) {
let stringValue = String(integerValue)
if let data = stringValue.dataUsingEncoding(NSUTF8StringEncoding) {
self.setObject(data, forKey: forKey, expires: expires)
}
}
}
</code></pre>
<p>I have created test without extension which works perfectly: </p>
<pre><code>let cache = try! Cache<NSData>(name: "MyCache")
let string = "foo"
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
cache.setObject(data, forKey: "bar")
}
</code></pre>
<p>So, I don't understand what was happen? Could anybody tell me - what was wrong?</p>
| <p>The problem is that <code>data</code> is an NSData, but <code>setObject</code> takes a T as its first parameter. Not an NSData.</p>
<p>It's true that you have defined this extension for <code>T:NSData</code> but that doesn't matter to Swift.</p>
|
Missing artifact error when adding a Maven dependency <p>I am not familiar with maven but I need to add a <a href="https://github.com/kwhat/jnativehook" rel="nofollow">jnativehook</a> dependency in a Java/Jersey project. I tried to add this dependency in my pom.xml </p>
<pre><code><dependency>
<groupId>com.1stleg</groupId>
<artifactId>system-hook</artifactId>
<version>2.0.3</version>
</dependency>
</code></pre>
<p>But I get an error on Eclipse </p>
<blockquote>
<p>Missing artifact com.1stleg:system-hook:jar:2.0.3</p>
</blockquote>
| <p>According <a href="http://mvnrepository.com/artifact/com.1stleg" rel="nofollow">this</a>, it should be:</p>
<pre><code><dependency>
<groupId>com.1stleg</groupId>
<artifactId>jnativehook</artifactId>
<version>2.0.3</version>
</dependency>
</code></pre>
<p>instead of</p>
<pre><code><dependency>
<groupId>com.1stleg</groupId>
<artifactId>system-hook</artifactId>
<version>2.0.3</version>
</dependency>
</code></pre>
<p>Hope it helps!</p>
|
Using Entity Framework to retrieve distinct values from SQL Server in json for angularjs <p>I am having an issue where I'm trying to retrieve distinct values using Entity Framework and returning it in JSON format to use in an angularJS dropdown list. When trying to retrieve distinct values I get the following error: </p>
<p>Cannot implicitly convert type 'System.Collection.Generic.List to 'System.Collection.Generic.List'</p>
<p>Here is the code that causes an issue:</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-html lang-html prettyprint-override"><code> List<TABLE_NAME> objContext = new List<TABLE_NAME>();
using (MyEntity dc = new MyEntity())
{
objContext = dc.TABLE_NAME.Where(a => a.COLUMN_NAME != null).Select(m >= m.COLUMN_NAME).Distinct().ToList();
}
return new JsonResult { Data = objContext, JsonRequestBehavior = JsonRequestBehavior.AllowGet };</code></pre>
</div>
</div>
</p>
<p>However this code runs without error but I don't get a list of distinct values:</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> List<TABLE_NAME> objContext = new List<TABLE_NAME>();
using (MyEntity dc = new MyEntity())
{
objContext = dc.TABLE_NAME.OrderBy(a >= a.COLUMN_NAME).ToList();
}
return new JsonResult { Data = objContext, JsonRequestBehavior = JsonRequestBehavior.AllowGet };</code></pre>
</div>
</div>
</p>
<p>Thanks,</p>
<p>S</p>
| <p>U r specifying in select statement u only need a field data but u r trying to assign it into
List</p>
<pre><code>List<String> objContext = dc.TABLE_NAME.Where(a >= a.COLUMN_NAME != null).Select(m >= m.COLUMN_NAME).Distinct().ToList();
</code></pre>
<p>in this case </p>
<pre><code> objContext = dc.TABLE_NAME.OrderBy(a >= a.COLUMN_NAME).ToList();
</code></pre>
<p>This will not throw error because it return TABLE_NAME object so u can assign it to <code>List<TABLE_NAME></code></p>
|
How to save JSpinner values in variables as a permanent unchangeable value? <p>I have a JSpinner Number Model as in the following Picture:</p>
<p><a href="http://i.stack.imgur.com/mOutw.png" rel="nofollow"><img src="http://i.stack.imgur.com/mOutw.png" alt="JSpinner"></a></p>
<p>I saved the value shown in the Width for example in a Double variable as</p>
<pre><code>public void stateChanged(ChangeEvent arg0) {
doublewidth =(Double) spinnerwidth.getModel().getValue();
}
</code></pre>
<p>Now the value of JSpinner Width saved to doublewidth = 60, but if i change Width again to 300 as an example now doublewidth = 300 but I dont want that to happen. </p>
<p>I want doublewidth to save the value of 60 no matter what happens to JSpinner. </p>
<p>Can you help me please? </p>
| <p>When you initialize doubleWidth set it to</p>
<pre><code>doubleWidth = -1
</code></pre>
<p>then inside your stateChanged method only adjust it if it is still equal to -1.</p>
<pre><code>if (doubleWith == -1){
doublewidth =(Double) spinnerwidthto.getModel().getValue();
}
</code></pre>
|
how to set when downloading from playstore that app should install in sdcard or internal memory in android? <p>Requirement: When I install app from the playstore,after clicking on install button I want to show a dialog whether app should be installed in SD card or internal memory. How can I achieve this. Can someone help me out </p>
| <p>Check <a href="https://developer.android.com/guide/topics/manifest/manifest-element.html" rel="nofollow">manifest</a>'s <code>android:installLocation</code>.</p>
<p>Dynamically changing the <code>android:installLocation</code> is not possible.</p>
|
How to multithread using serial connection vb.net <p>I have a serial connection to a remote machine and i'm developing a windows form using vb.net in order to gather some infos.</p>
<p>So as u can see in the code below i'm waiting until i receive the full string ( length 4, # as separator ) to change some textboxes text.</p>
<pre><code>Dim ReceivedTextSeries As String = vbNullString
Private Sub ReceivedText(ByVal [text] As String)
If TextBoxConsola.InvokeRequired Then
Dim x As New SetTextCallBlack(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
ReceivedTextSeries &= [text]
JustTesting()
Else
TextBoxConsolaReceived.Text &= [text]
ReceivedTextSeries &= [text]
JustTesting()
End If
End Sub
</code></pre>
<hr>
<pre><code>Sub JustTesting()
Dim Series() As String = ReceivedTextSeries.Split("#")
If Series.Length = 4 Then
TextBox1.Text = Series(0)
TextBox2.Text = Series(2)
End If
End Sub
</code></pre>
<p>But i'm getting an error saying that multithreading isn't allowed..
<code>The operation between threads is not valid: Control 'TextBox1' accessed from a thread other than the thread where it was created.</code></p>
<p>How can i manage this now? I've tried to add event handlers to avoid this but without success..</p>
| <p>So you could create a quick sub that invokes your textboxes. You're already doing that in your previous method. This makes it reusable.</p>
<pre><code>Private Sub UpdateTextBox(Text As String, TextBox As TextBox)
If TextBox.InvokeRequired Then
TextBox.Invoke(DirectCast(Sub() UpdateTextBox(Text, TextBox), Action))
Exit Sub
End If
TextBox.Text = Text
End Sub
</code></pre>
<p>Then all your calls to write to a textbox can be called with </p>
<pre><code>UpdateTextBox("My Text", TextBox1)
</code></pre>
<p>So with your code you could do</p>
<pre><code>Sub JustTesting()
Dim Series() As String = ReceivedTextSeries.Split("#")
If Series.Length = 4 Then
UpdateTextBox(Series(0), TextBox1)
UpdateTextBox(Series(2), TextBox2)
End If
End Sub
</code></pre>
|
how to keep the key background color changed...? <p>I have custom keyboard with red buttons when I press on the for example number 1 the color changed to blue when I pull my finger from the screen goes back to be red , I want to stay blue anyone knows how to do it here's my color changing (pressing) xml</p>
<pre><code> <selector xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:state_pressed="true"
android:drawable="@drawable/pressed" />
<item
android:state_checkable="true"
android:state_pressed="true"
android:drawable="@drawable/download" />
<item android:drawable="@drawable/red"/>
</selector>
</code></pre>
<p>check this:</p>
<pre><code>public class BasicOnKeyboardActionListener implements KeyboardView.OnKeyboardActionListener {
private Activity mTargetActivity;
public BasicOnKeyboardActionListener(Activity targetActivity) {
mTargetActivity = targetActivity;
}
@Override
public void swipeUp() {
// TODO Auto-generated method stub
}
@Override
public void swipeRight() {
// TODO Auto-generated method stub
}
@Override
public void swipeLeft() {
// TODO Auto-generated method stub
}
@Override
public void swipeDown() {
// TODO Auto-generated method stub
}
@Override
public void onText(CharSequence text) {
// TODO Auto-generated method stub
}
@Override
public void onRelease(int primaryCode) {
}
// TODO Auto-generated method stub
@Override
public void onPress(int primaryCode) {
}
// TODO Auto-generated method stub
@Override
public void onKey(int primaryCode, int[] keyCodes)
{
long eventTime = System.currentTimeMillis();
KeyEvent event = new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, primaryCode, 0, 0 ,0 , 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE);
mTargetActivity.dispatchKeyEvent(event);
}
</code></pre>
| <blockquote>
<pre><code>Add this methods to the `keyboardListner`
</code></pre>
</blockquote>
<pre><code> public class SimpleIME extends InputMethodService
implements OnKeyboardActionListener{
private KeyboardView kv;
private Keyboard keyboard;
private boolean caps = false;
@Override
public void onKey(int primaryCode, int[] keyCodes) {
}
@Override
public void onPress(int primaryCode) {
}
@Override
public void onRelease(int primaryCode) {
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeDown() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeUp() {
}
}
</code></pre>
<p>and change the <code>onpressed</code> and <code>OnReleased</code> color</p>
<p>for more details follow the link... <a href="https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615" rel="nofollow">click here</a></p>
|
Error when trying to sort dictionaies stored inside array inside NSUserDefaults <p>Im making a game which saves the final score together with an entered name and a date to be then displayed in an UITableView. I need to be able to sort the values so that the values are stored by the highest score to lowest score. Im trying to sort using an NSDescriptor. However when I try to sort it I get an error:</p>
<p>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'</p>
<p>My code is as follows:</p>
<pre><code>class LeaderboardVC: UITableViewController {
var finishedGame = 0
var gameScore:Int = 0
var defaults = UserDefaults.standard
var newUserArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "Name", ascending: false)
self.tableView.dataSource = self
self.tableView.delegate = self
newUserArray = defaults.object(forKey: "data") as! NSMutableArray
newUserArray.sort(using: [descriptor])
self.tableView.reloadData()
defaults.synchronize()
if finishedGame == 1{
saveNew()
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
self.navigationItem.hidesBackButton = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func saveNew() {
let enterNameAlert = UIAlertController(title: "Please Enter Your Name", message: "This will be used to place you in the leaderboards", preferredStyle: .alert)
enterNameAlert.addTextField { (textField:UITextField) -> Void in
textField.placeholder = "Name"
textField.autocapitalizationType = UITextAutocapitalizationType.words
textField.autocorrectionType = UITextAutocorrectionType.no
textField.clearsOnBeginEditing = true
textField.clearsOnInsertion = true
textField.clearButtonMode = UITextFieldViewMode.always
textField.keyboardType = UIKeyboardType.default
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (action:UIAlertAction) in
let currentTime = Date()
let timeFormatter = DateFormatter()
timeFormatter.locale = Locale.current
timeFormatter.dateFormat = "HH:mm dd/MM/yy"
let convertedTime = timeFormatter.string(from: currentTime)
let enteredName = enterNameAlert.textFields?.first?.text
let newUserData = self.defaults.object(forKey: "data") as! NSArray
let newUserArray = NSMutableArray(array: newUserData)
let newUserRecord = [
"Name" : enteredName!,
"Score" : String(self.gameScore),
"Date" : convertedTime
] as [String : String]
newUserArray.add(newUserRecord)
self.defaults.set(newUserArray, forKey: "data")
self.defaults.synchronize()
let sb = UIStoryboard(name: "Main", bundle: nil)
let leaderBoardVC = sb.instantiateViewController(withIdentifier: "leaderboard") as! LeaderboardVC
self.navigationController?.pushViewController(leaderBoardVC, animated: true)
}
enterNameAlert.addAction(cancelAction)
enterNameAlert.addAction(confirmAction)
self.present(enterNameAlert, animated: true, completion: nil)
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LeaderBoardCell
cell.dateLabel?.text = "Date: \(((newUserArray.object(at: indexPath.row) as! [String:Any])["Date"] as! String))"
cell.dateLabel.adjustsFontSizeToFitWidth = true
cell.scoreLabel?.text = "Score: \(((newUserArray.object(at: indexPath.row) as! [String:Any])["Score"] as! String))"
cell.scoreLabel.adjustsFontSizeToFitWidth = true
cell.nameLabel?.text = "Name: \(((newUserArray.object(at: indexPath.row) as! [String:Any])["Name"] as! String))"
cell.nameLabel.adjustsFontSizeToFitWidth = true
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newUserArray.count
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
</code></pre>
<p><strong>Key Points to understand my problem</strong></p>
<ol>
<li><p>There are 3 values saved in each dictionary: "Name", "Score" and "Date"; all 3 are saved as String</p></li>
<li><p>Each dictionary is stored inside an NSMutableArray named newUserArray. This array must be Mutable as it will have a dictionary added to it after every game is finished.</p></li>
<li><p>I have tried to use NSDescriptors however if there is a better way to do this Im open.</p></li>
<li><p>I must sort all the dictionaries by the "Score".</p></li>
</ol>
<p>Thanks</p>
| <p><code>NSUserDefaults</code> does not return mutable objects and a downcast won't change this, hence the exception that results from attempting to mutate an immutable object. </p>
<p>You need to create a mutable copy of the immutable array you get from <code>NSUserDefaults</code></p>
<pre><code>if let defaultsArray = defaults.objectForKey("data") as? NSArray {
newUserArray = defaultsArray.mutableCopy()
...
}
</code></pre>
|
MySQL - How to do a self join to return overlapping date ranges? <p>I have a table of historical position tenures held by members within an organisation (tbl_tenue).
Each position may only be held by one person at a time but one person may hold several positions sequentially or concurrently.
I want to check the integrity of this table by taking each position tenure record in turn and then comparing it with every other record in the table looking for (erronous) overlaps with other tenures of the same position.</p>
<p>I have written a working query (below) that returns details of overlaps when passed a test_tenure_id, position_id, and the start and end dates of a particular tenure (see below)
For each overlap. this query returns tenure_id, member_id, member_sn, date_started, date_ended and reason for the overlap. </p>
<p>Can anyone help me with the sql to now run this query against the same tbl_tenue table, each time passing it the data from one row in tbl_tenue so I can test each record for overlap with every other one (except itself of course) and return data from the record and all its overlaps?</p>
<p><em>(I realise that if I can do this then I should be able to avoid passing in the tenure_id to the WHERE clause by using the join and also avoid passing the dates as well using the join but I can't see how to do that at the moment, so any help with that would be good)</em></p>
<p>The query below uses the following tables, simplified for this question </p>
<pre><code>TABLE tbl_member
( member_id INT AUTO_INCREMENT, -- pk
member_sn` varchar(50) , --surname
<other stuff>
)
TABLE tbl_tenure
(tenure_id INT AUTO_INCREMENT, -- pk
member_id INT -- fk to tbl_member
position_id -- fk to table of position titles
date_started DATE
date_ended DATE -- will be NULL if still in post
)
-- test data for query
SET @the_test_tenure_start_date = '2016-05-13' ;
SET @the_test_tenure_end_date = '2016-10-05';
SET @the_test_position_id = 18;
SET @the_test_tenue_id = 122;
-- the query to return overlaps with data from a given tenure record
SELECT
tbl_tenure.tenure_id,
tbl_tenure.member_id,
tbl_member.member_sn,
tbl_tenure.date_started,
tbl_tenure.date_ended,
CASE
WHEN @the_test_tenure_end_date <= IFNULL(date_ended, CURDATE()) -- test end date <= existing end date
AND @the_test_tenure_start_date >= date_started -- test start date >= existing start date
THEN 'Test dates fall completely inside an existing tenure'
WHEN @the_test_tenure_end_date >= IFNULL(date_ended, CURDATE()) -- test end date >= existing end date
AND @the_test_tenure_start_date <= date_started -- test start date <= existing start date
THEN 'An existing tenure falls completely inside test dates'
WHEN @the_test_tenure_start_date >= date_started -- test start date >= existing start date
AND @the_test_tenure_start_date <= IFNULL(date_ended, CURDATE()) -- test start date <= existing end date
THEN 'Test start date overlaps with an existing tenure'
WHEN @the_test_tenure_end_date >= date_started -- test end date >= existing start date
AND @the_test_tenure_end_date <= IFNULL(date_ended, CURDATE()) -- test end date <= existing end date
THEN 'Test end date overlaps with an existing tenure'
END AS reason
FROM
tbl_tenure
INNER JOIN tbl_member
ON tbl_tenure.member_id = tbl_member.member_id
WHERE ( -- there is an overlap (see qry 2.2 http://salman-w.blogspot.co.uk/2012/06/sql-query-overlapping-date-ranges.html
@the_test_tenure_end_date >= date_started)
AND
IFNULL(date_ended, CURDATE()) >= @the_test_tenure_start_date
)
AND tbl_tenure.position_id = @the_test_position_id -- position to be tested
AND tbl_tenure.tenure_id <> @the_test_tenue_id -- don't look at the test tenure record
ORDER BY tbl_tenure.date_started ASC;
</code></pre>
<p>In order to clarify this question, the output I am looking for is something like this, note tenure_id 132 where a member is recorded as ovelapping with themself</p>
<pre><code>tenure_id | member_id | position_id | start_date | end_date | overlapping_member_id | overlapping_tenure_id | overlapping_start_date |overlapping_end_date | overlap_reason
123 | 2 | 6 | 2016-02-01 | 2016 02-01 | 7 | 456 | 2016-01-05 | 2016-01-10 |'Test start date overlaps with an existing tenure'
125 | 2 | 8 | 2016-02-01 | 2016 03-01 | 8 | 459 | 2016-01-0 | 2016-02-01 |'Test end date overlaps with an existing tenure'
129 | 4 | 7 | 2016-03-10 | 2016 04-01 | 6 | 501 | 2016-03-2 | 2016-03-25 |'An existing tenure falls completely inside test dates'
132 | 4 | 7 | 2016-01-01 | 2016 04-01 | 4 | 505 | 2016-03-01 | 2016-04-01 |'Test end date overlaps with an existing tenure'
135 | 9 | 3 | 2016-05-01 | 2016 07-01 | 9 | 520 | 2016-04-0 | 2016-08-01 |'Test dates fall completely inside an existing tenure'
</code></pre>
| <p>After spending the day on it and having a think while running on my treadmill I believe I have the answer. I'm posting it here for the benefit of others. I moved the join with tbl_member into a sub query, and for the sake of completeness include another subquery to get the actual title of the position from a third table, tbl_position, shown below. <em>(Can't see a way to replace the sub queries with joins but that doesn't matter.)</em> </p>
<pre><code>TABLE tbl_positions
(
position_id INT AUTO_INCREMENT, -- pk
position VARCHAR(100), -- title of position
<other stuff>
)
</code></pre>
<p>The code I came up with is below which appears to work correctly and shows all the overlaps with details of who is overlapped with whom, when and why.</p>
<p>The oly niggle is that if, for example, Fred is shown to overlap as President with Jim's existing record with the reason that Fred's tenure completely encloses Jim's tenure, then Jim's position as President is also shown to overlap with Fred's existing tenure record with the reason given that Fred's is completely enclosed by Jim's. ie I get both sides of the overlap. </p>
<p>If there is a quick way to get just a 'one way' overlap then by all means post a better answer.</p>
<p>My answer</p>
<pre><code>SELECT
base_tenure.position_id AS base_tenure_id,
base_tenure.member_id AS base_member_id,
(SELECT member_sn FROM tbl_member WHERE tbl_member.member_id = base_tenure.member_id) AS base_sn,
(SELECT tbl_positions.position FROM tbl_positions WHERE tbl_positions.position_id = base_tenure.position_id ) AS POSITION,
base_tenure.date_started AS base_date_started,
base_tenure.date_ended AS base_date_ended,
overlap_tenure.position_id AS overlap_tenure_id,
overlap_tenure.member_id AS overlap_member_id,
(SELECT member_sn FROM tbl_member WHERE tbl_member.member_id = overlap_tenure.member_id) AS overlap_sn,
overlap_tenure.date_started AS overlap_date_started,
overlap_tenure.date_ended AS overlap_date_ended,
CASE
WHEN base_tenure.date_ended <= IFNULL(overlap_tenure.date_ended, CURDATE())-- test end date <= existing end date
AND base_tenure.date_started >= overlap_tenure.date_started -- test start date >= existing start date
THEN 'tbl_member dates fall completely inside an existing tenue'
WHEN base_tenure.date_ended >= IFNULL(overlap_tenure.date_ended, CURDATE()) -- test end date >= existing end date
AND base_tenure.date_started <= overlap_tenure.date_started -- test start date <= existing start date
THEN 'An existing tenue falls completely inside tbl_member dates'
WHEN base_tenure.date_started >= overlap_tenure.date_started -- test start date >= existing start date
AND base_tenure.date_started <= IFNULL( overlap_tenure.date_ended , CURDATE()) -- test start date <= existing end date
THEN 'tbl_member start date overlaps with an existing tenue'
WHEN base_tenure.date_ended >= overlap_tenure.date_started -- test end date >= existing start date
AND base_tenure.date_ended <= IFNULL( overlap_tenure.date_ended , CURDATE())-- test end date <= existing end date
THEN 'tbl_member end date overlaps with an existing tenue'
END AS reason
FROM -- a self join on tbl_tenure
tbl_tenure AS base_tenure,
tbl_tenure AS overlap_tenure
WHERE (-- there is an overlap (see qry 2.2 http://salman-w.blogspot.co.uk/2012/06/sql-query-overlapping-date-ranges.html
base_tenure.date_ended >= overlap_tenure.date_started -- test end date >= existing start date
AND
IFNULL(overlap_tenure.date_ended, CURDATE()) >= base_tenure.date_started
)
AND
base_tenure.club_function_id = overlap_tenure.club_function_id -- positions are the same for both members
AND
base_tenure.position_id <> overlap_tenure.position_id -- don't compare the base record with itself as they are identical and will always overlap
ORDER BY
(SELECT member_sn FROM tbl_member WHERE tbl_member.member_id = base_tenure.member_id) ,
base_tenure.date_started ;
</code></pre>
|
Upload files to google drive using Google.Apis.Drive.v3 in asp.net MVC <p>I want to upload files to Google Drive using the Google.Apis.Drive.v3 in asp.net MVC. I want my visitor to upload the files to my google drive, I will set the credentials of my google drive in code. Can anyone help me to get this work?</p>
<p>I tried the quick start sample for upload but it asks for the credentials every time. Or it uses the cached credential.</p>
<p>How can I upload a file without knowing the user about the credential?</p>
| <p>According to this <a href="https://developers.google.com/drive/v3/web/quickstart/dotnet" rel="nofollow">documentation</a>, you need to get the access credentials to enable the Google Drive. If you want to programmatically access users data without any manual authorization on their part, then perform <a href="https://developers.google.com/drive/v3/web/about-auth#perform_google_apps_domain-wide_delegation_of_authority" rel="nofollow">Google Apps Domain-Wide Delegation of Authority</a>. To delegate authority this way, domain administrators can use service accounts with <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">OAuth 2.0</a>. You can also check on this <a href="https://github.com/google/google-api-dotnet-client" rel="nofollow">link</a> which might help.</p>
|
IdentityServer 3 and ASP.NET Identity: how to get user information <p>I'm using IdentityServer 3 with ASP.NET Identity as its user store. I have followed this <a href="https://mindfulsoftware.com.au/guidance/oauth2-walkthrough-using-identity-server-and-aspnet/creating-an-identity-server-using-aspnet-identity-and-entity-framework-storage" rel="nofollow">article</a> to set up IdentityServer and my client is an ASP MVC web application. I'm able to login from my client, but I don't understand how to get user information on the client side. On the server side Im using:</p>
<pre><code> var scopes = new Scope[]
{
StandardScopes.OpenId,
StandardScopes.Email,
new Scope
{
Name = "roles",
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
}
};
var clients = new Client[]
{
new Client
{
ClientId = "mvc-demo",
ClientName = "MVC Demo Client",
Flow = Flows.Implicit,
RedirectUris = new List<string>
{
"http://localhost:16652/"
},
AllowedScopes = new List<string>
{
"openid", "email", "roles"
}
}
};
var factory = new IdentityServerServiceFactory().Configure(connectionString);
factory.UseInMemoryClients(clients);
factory.UseInMemoryScopes(scopes);
</code></pre>
<p>And on the client side:</p>
<pre><code> app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
SignInAsAuthenticationType = "cookies",
Authority = "https://localhost:44305/",
ClientId = "mvc-demo",
RedirectUri = "http://localhost:16652/",
ResponseType = "id_token token",
Scope = "openid email roles",
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
var id = n.AuthenticationTicket.Identity;
var email = id.FindFirst(Constants.ClaimTypes.Email);
var roles = id.FindAll(Constants.ClaimTypes.Role);
// create new identity and set name and role claim type
var nid = new ClaimsIdentity(
id.AuthenticationType,
Constants.ClaimTypes.Email,
Constants.ClaimTypes.Role);
nid.AddClaim(email);
nid.AddClaims(roles);
// add some other app specific claim
//nid.AddClaim(new Claim("app_specific", "some data"));
n.AuthenticationTicket = new AuthenticationTicket(
nid,
n.AuthenticationTicket.Properties);
return Task.FromResult(0);
}
}
</code></pre>
<p>But I cant get the information about users email for example.</p>
| <p>I managed to send claims to my client application this way:</p>
<pre><code>var scopes = new Scope[]
{
StandardScopes.OpenId,
new Scope
{
Name = "roles",
Type = ScopeType.Identity,
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
},
new Scope
{
Name = "email",
Type = ScopeType.Identity,
Claims = new List<ScopeClaim>
{
new ScopeClaim(Constants.ClaimTypes.Email)
}
}
};
var clients = new Client[]
{
new Client
{
ClientId = "mvc-demo",
ClientName = "MVC Demo Client",
Flow = Flows.Implicit,
RedirectUris = new List<string>
{
"http://localhost:16652/"
},
AllowedScopes = new List<string>
{
"openid", "email", "roles"
}
}
};
</code></pre>
<p>And on the client side, I needed to turn off claims transformation, to fetch them correctly, like this(in OWIN startup class):</p>
<pre><code>AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
</code></pre>
|
How to specify folder for build definition in VSTS <p>I have a single repository, hosted in VSTS, that contains two projects - a frontend SPA and a backend API.</p>
<p>I want to create separate build definitions for each. </p>
<p>When I go to "Create new build definition", I have an option to select the Repository source (the Team Project in VSTS), but I can't see how to specify which folder to set for each project</p>
| <p>Multiple build definitions can have the same repository source. So, In your example, one build definition could build your frontend project and the other build definition can build your backend API project. Inside each build definition, you will create a task where you specify the required project to build. For .NET, this will probably point to the .csproj or .vbproj. For other solutions, you can just point to the folder or whatever is required for your build task.</p>
|
invalid column index error in java while fetching data from oracle 10g database. Cant figure out whats wrong <p>Code snippet:
On a button click, actionevent will be called</p>
<pre><code>public void actionPerformed(ActionEvent e)
{
Function f = new Function();
</code></pre>
<p>Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.</p>
<pre><code>ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
</code></pre>
<p>t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.</p>
<pre><code>rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
</code></pre>
<p>Here is the code snippet for nested class Function which is inside the main class:</p>
<pre><code>class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:@Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
</code></pre>
<p>Please help figure out the problem.</p>
| <p>Don't put the parameter placeholder <code>?</code> in single quotes.</p>
<p>This: </p>
<pre><code>ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
</code></pre>
<p>should be </p>
<pre><code>ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
</code></pre>
<p>The <code>?</code> is not recognized as a placeholder if you enclose it in single quotes. </p>
|
mootools equivalent of jQuery's .is() <p>Does Mootools have the equivalent of jQuery's .is()? Or if not, what's the best approach for this functionality in Mootools? I've searched for a while and can't seem to find the right solution. </p>
<p>Example of jQuery I'm trying to achieve in Mootools.</p>
<pre><code>if(a.is(':last-child')){
console.log('this should return true >', a.is(':last-child'));
}
</code></pre>
<p>Any help would be great, thanks!</p>
| <p>Well I don't know of a Mootools equivalent, but you can probably the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/matches" rel="nofollow">native</a> <code>matches()</code> function. <a href="https://davidwalsh.name/element-matches-selector" rel="nofollow">Other Link</a></p>
<pre><code>var bd = document.body;
console.log(bd.matches('body')) //true
console.log(bd.matches(':last-child')) //true
</code></pre>
|
Remove the sharing app from share intent chooser listing <p>I want to share the content from my application to other applications. I've used the below code for this</p>
<pre><code>Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, title);
intent.putExtra(Intent.EXTRA_TEXT, linkUrl);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
((Activity) mContext).startActivityForResult(
Intent.createChooser(intent, mContext.getString(R.string.share_via) + "â¦"), ConstantVariables.CONTENT_SHARING_CODE)
</code></pre>
<p>I've also defined the below intent filter in my application's manifest file. </p>
<pre><code><intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</code></pre>
<p>So, whenever I share any content from my application, an application chooser appears which lists all the apps which can receive this content. In this listing, my application is also getting listed but I don't want to list my application when I share any content from my app itself.</p>
<p>Can someone please help, how can I achieve this. </p>
<p>Thanks a lot in advanced.</p>
| <p>Look the below code.. taken from my previous <a href="http://stackoverflow.com/a/39527295/2299040">answer</a></p>
<pre><code> public static void shareExludingApp(Context ctx, String packageNameToExclude, android.net.Uri imagePath, String text) {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
File file = new File(imagePath.getPath());
List<ResolveInfo> resInfo = ctx.getPackageManager().queryIntentActivities(createShareIntent(text, file), 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = createShareIntent(text, file);
if (!info.activityInfo.packageName.equalsIgnoreCase(packageNameToExclude)) {
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0),
"Select app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
targetedShareIntents.toArray(new Parcelable[]{}));
ctx.startActivity(chooserIntent);
}
}
private static Intent createShareIntent(String text, File file) {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
if (text != null) {
share.putExtra(Intent.EXTRA_TEXT, text);
}
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
return share;
}
</code></pre>
|
issue storing data to Sqlite database <p>i need your help..i am getting incoming call mobile no. using broadcastreceiver and and want to save that no into my database..but when i do that it shows :- Attempt to invoke virtual method 'android.content.Context.getResources()' on a null object reference...please guys help me...thanx in advance...</p>
<p>ServiceReceiver.java</p>
<pre><code>public class ServiceReceiver extends BroadcastReceiver {
MyReceiver receiver = new MyReceiver();
@Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
System.out.println("incomingNumber :" + incomingNumber);
receiver.setData(incomingNumber, context);
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}}
</code></pre>
<p>DataBaseHelper.java</p>
<pre><code>public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "callinfo.db";
public static final String TABLE_NAME = "misscall";
public static final String COL_1 = "ID";
public static final String COL_2 = "MOBILE";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,MOBILE VARCHAR(20));");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXITS"+ TABLE_NAME );
onCreate(sqLiteDatabase);
}
public boolean insertData(String mobile) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,mobile);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}}
</code></pre>
<p>MyReceiver.java</p>
<pre><code>public class MyReceiver extends AppCompatActivity {
DataBaseHelper myDB;
public MyReceiver(){
}
public void setData(String incomingNumber, Context context){
myDB = new DataBaseHelper(context);//i think here i get that error
Toast.makeText(context, incomingNumber, Toast.LENGTH_LONG).show();
save(incomingNumber,context);
}
public void save(String number,Context context){
if(number!=null){
AddData(number);
}
}
public void AddData(String number) {
boolean isInserted = myDB.insertData(number);
if(isInserted == true)
Toast.makeText(MyReceiver.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MyReceiver.this,"Data not Inserted", Toast.LENGTH_LONG).show();
} }
</code></pre>
<p>error</p>
<pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:90)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:551)
at android.widget.Toast.<init>(Toast.java:122)
at android.widget.Toast.makeText(Toast.java:290)
at com.example.abhijeetsingh.recievecall.MyReceiver.setData(MyReceiver.java:51)
at com.example.abhijeetsingh.recievecall.ServiceReceiver$1.onCallStateChanged(ServiceReceiver.java:37)
at android.telephony.PhoneStateListener$2.handleMessage(PhoneStateListener.java:404)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
</code></pre>
| <p>Obviously, you have got an incorrect implementation of <code>AppCompatActivity</code> class. </p>
<p>this code has an incorrect point:
<code>Toast.makeText(MyReceiver.this, "Data Inserted", Toast.LENGTH_LONG).show();</code></p>
<p>I mean <code>Toast.makeText</code> needs a <code>context</code> variable which is correctly generated .</p>
<pre><code>public class MyReceiver {
DataBaseHelper myDB;
public MyReceiver(){
}
public void setData(String incomingNumber, Context context){
myDB = new DataBaseHelper(context);//i think here i get that error
Toast.makeText(context, incomingNumber, Toast.LENGTH_LONG).show();
save(incomingNumber,context);
}
public void save(String number,Context context){
if(number!=null){
AddData(number, context);
}
}
public void AddData(String number, Context context) {
boolean isInserted = myDB.insertData(number);
if(isInserted == true)
Toast.makeText(context, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Data not Inserted", Toast.LENGTH_LONG).show();
} }
</code></pre>
<p>To correctly use an <code>Activity</code> class you have to initialize in via <code>startActivity</code> method that directly launch a window.</p>
|
Django Rest: Correct data isn't sent to serializer with M2M model <p>I have a simple relational structure with projects containing several sequences with an intermediate meta model.</p>
<p>I can perform a GET request easily enough and it formats the data correctly. However, when I want to post the validated_data variable does not contain data formatted correctly, so I can't write a create/update method.</p>
<p>The data should look like:</p>
<pre><code>{'name': 'something',
'seqrecords': [{
'id': 5,
'sequence': 'ACGG...AAAA',
'name': 'Z78529',
'order': 1
},
{
'id': 6,
'sequence': 'CGTA...ACCC',
'name': 'Z78527',
'order': 2
},
}
</code></pre>
<p>But instead it looks like this:</p>
<pre><code>{'name': 'something',
'projectmeta_set': [
OrderedDict([('order', 1)]),
OrderedDict([('order', 2)]),
OrderedDict([('order', 3)])
]
}
</code></pre>
<p><strong>Serializers:</strong></p>
<pre><code>class ProjectMetaSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.ReadOnlyField(source='sequence.id')
name = serializers.ReadOnlyField(source='sequence.name')
class Meta:
model = ProjectMeta
fields = ['id', 'name', 'order']
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
seqrecords = ProjectMetaSerializer(source='projectmeta_set', many=True)
class Meta:
model = Project
fields = ['id', 'name', 'seqrecords']
ReadOnlyField = ['id']
def create(self, validated_data):
project = Project(name=validated_data['name'])
project.save()
# This is where it all fails
for seq in validated_data['seqrecords']:
sequence = SeqRecord.objects.filter(id=seq['id'])
meta = ProjectMeta(project=project,
sequence=sequence,
order=seq['order'])
meta.save()
return project
class SeqRecordSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = SeqRecord
fields = ['id', 'name', 'sequence']
read_only_fields = ['id']
</code></pre>
<p><strong>Models:</strong></p>
<pre><code>class SeqRecord(models.Model):
name = models.CharField(max_length=50)
sequence = models.TextField()
class Project(models.Model):
name = models.CharField(max_length=50)
sequences = models.ManyToManyField(SeqRecord,
through='primer_suggestion.ProjectMeta')
class ProjectMeta(models.Model):
project = models.ForeignKey(Project)
sequence = models.ForeignKey(SeqRecord)
order = models.PositiveIntegerField()
</code></pre>
<p><strong>View</strong></p>
<pre><code>class ProjectApiList(viewsets.ViewSetMixin, generics.ListCreateAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
</code></pre>
<p>Is there some way to change the validation of the data, so it returns the things I need or can I write the create and functions some other way?</p>
| <p>As you see in the <code>ProjectMetaSerializer</code>, the fields <code>id</code> and <code>name</code> are ReadOnlyFields. So you can't use them in <code>post</code> request.</p>
<pre><code>class ProjectMetaSerializer(serializers.ModelSerializer):
seqrecords = SeqRecordSerializer(many=True)
class Meta:
model = ProjectMeta
fields = ['seqrecords',]
class ProjectSerializer(serializers.ModelSerializer):
project_meta = ProjectMetaSerializer(many=True)
class Meta:
model = Project
fields = ['id', 'name', 'project_meta']
ReadOnlyField = ['id']
def create(self, validated_data):
project = Project(name=validated_data['name'])
project.save()
# This is where it all fails
for seq in validated_data['seqrecords']:
sequence = SeqRecord.objects.filter(id=seq['id'])
meta = ProjectMeta(project=project,
sequence=sequence,
order=seq['order'])
meta.save()
return project
class SeqRecordSerializer(serializers.ModelSerializer):
class Meta:
model = SeqRecord
fields = ['id', 'name', 'sequence']
</code></pre>
|
how to reconnect after autobahn websocket timeout? <p>I'm using Autobahn to connect to a websocket like this.</p>
<pre><code>class MyComponent(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
print("session ready")
def oncounter(*args, **args2):
print("event received: args: {} args2: {}".format(args, args2))
try:
yield self.subscribe(oncounter, u'topic')
print("subscribed to topic")
except Exception as e:
print("could not subscribe to topic: {0}".format(e))
if __name__ == '__main__':
addr = u"wss://mywebsocketaddress.com"
runner = ApplicationRunner(url=addr, realm=u"realm1", debug=False, debug_app=False)
runner.run(MyComponent)
</code></pre>
<p>This works great, and I am able to receive messages. However, after around 3-4 hours, sometimes much sooner, the messages abruptly stop coming. It appears that the websocket times out (does that happen?), possibly due to connection issues. </p>
<p>How can I auto-reconnect with autobahn when that happens?</p>
<hr>
<p>Here's my attempt, but the reconnecting code is never called.</p>
<pre><code>class MyClientFactory(ReconnectingClientFactory, WampWebSocketClientFactory):
maxDelay = 10
maxRetries = 5
def startedConnecting(self, connector):
print('Started to connect.')
def clientConnectionLost(self, connector, reason):
print('Lost connection. Reason: {}'.format(reason))
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
def clientConnectionFailed(self, connector, reason):
print('Connection failed. Reason: {}'.format(reason))
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
class MyApplicationRunner(object):
log = txaio.make_logger()
def __init__(self, url, realm, extra=None, serializers=None,
debug=False, debug_app=False,
ssl=None, proxy=None):
assert(type(url) == six.text_type)
assert(realm is None or type(realm) == six.text_type)
assert(extra is None or type(extra) == dict)
assert(proxy is None or type(proxy) == dict)
self.url = url
self.realm = realm
self.extra = extra or dict()
self.serializers = serializers
self.debug = debug
self.debug_app = debug_app
self.ssl = ssl
self.proxy = proxy
def run(self, make, start_reactor=True):
if start_reactor:
# only select framework, set loop and start logging when we are asked
# start the reactor - otherwise we are running in a program that likely
# already tool care of all this.
from twisted.internet import reactor
txaio.use_twisted()
txaio.config.loop = reactor
if self.debug or self.debug_app:
txaio.start_logging(level='debug')
else:
txaio.start_logging(level='info')
isSecure, host, port, resource, path, params = parseWsUrl(self.url)
# factory for use ApplicationSession
def create():
cfg = ComponentConfig(self.realm, self.extra)
try:
session = make(cfg)
except Exception as e:
if start_reactor:
# the app component could not be created .. fatal
self.log.error(str(e))
reactor.stop()
else:
# if we didn't start the reactor, it's up to the
# caller to deal with errors
raise
else:
session.debug_app = self.debug_app
return session
# create a WAMP-over-WebSocket transport client factory
transport_factory = MyClientFactory(create, url=self.url, serializers=self.serializers,
proxy=self.proxy, debug=self.debug)
# supress pointless log noise like
# "Starting factory <autobahn.twisted.websocket.WampWebSocketClientFactory object at 0x2b737b480e10>""
transport_factory.noisy = False
# if user passed ssl= but isn't using isSecure, we'll never
# use the ssl argument which makes no sense.
context_factory = None
if self.ssl is not None:
if not isSecure:
raise RuntimeError(
'ssl= argument value passed to %s conflicts with the "ws:" '
'prefix of the url argument. Did you mean to use "wss:"?' %
self.__class__.__name__)
context_factory = self.ssl
elif isSecure:
from twisted.internet.ssl import optionsForClientTLS
context_factory = optionsForClientTLS(host)
from twisted.internet import reactor
if self.proxy is not None:
from twisted.internet.endpoints import TCP4ClientEndpoint
client = TCP4ClientEndpoint(reactor, self.proxy['host'], self.proxy['port'])
transport_factory.contextFactory = context_factory
elif isSecure:
from twisted.internet.endpoints import SSL4ClientEndpoint
assert context_factory is not None
client = SSL4ClientEndpoint(reactor, host, port, context_factory)
else:
from twisted.internet.endpoints import TCP4ClientEndpoint
client = TCP4ClientEndpoint(reactor, host, port)
d = client.connect(transport_factory)
# as the reactor shuts down, we wish to wait until we've sent
# out our "Goodbye" message; leave() returns a Deferred that
# fires when the transport gets to STATE_CLOSED
def cleanup(proto):
if hasattr(proto, '_session') and proto._session is not None:
if proto._session.is_attached():
return proto._session.leave()
elif proto._session.is_connected():
return proto._session.disconnect()
# when our proto was created and connected, make sure it's cleaned
# up properly later on when the reactor shuts down for whatever reason
def init_proto(proto):
reactor.addSystemEventTrigger('before', 'shutdown', cleanup, proto)
return proto
# if we connect successfully, the arg is a WampWebSocketClientProtocol
d.addCallback(init_proto)
# if the user didn't ask us to start the reactor, then they
# get to deal with any connect errors themselves.
if start_reactor:
# if an error happens in the connect(), we save the underlying
# exception so that after the event-loop exits we can re-raise
# it to the caller.
class ErrorCollector(object):
exception = None
def __call__(self, failure):
self.exception = failure.value
reactor.stop()
connect_error = ErrorCollector()
d.addErrback(connect_error)
# now enter the Twisted reactor loop
reactor.run()
# if we exited due to a connection error, raise that to the
# caller
if connect_error.exception:
raise connect_error.exception
else:
# let the caller handle any errors
return d
</code></pre>
<p>The error I'm getting:</p>
<pre>
2016-10-09T21:00:40+0100 Connection to/from tcp4:xxx.xx.xx.xx:xxx was lost in a non-clean fashion: Connection lost
2016-10-09T21:00:40+0100 _connectionLost: [Failure instance: Traceback (failure with no frames): : Connection to the other side was lost in a non-clean fashion: Connection l
ost.
]
2016-10-09T21:00:40+0100 WAMP-over-WebSocket transport lost: wasClean=False, code=1006, reason="connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)"
2016-10-09T21:10:39+0100 EXCEPTION: no messages received
2016-10-09T21:10:39+0100 Traceback (most recent call last):
</pre>
| <p>You can use a <code>ReconnectingClientFactory</code> if you're using Twisted. <a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_variants/client_reconnecting.py" rel="nofollow">There's a simple example by the autobahn developer on github</a>. Unfortunately there doesn't seem to be an implementation of an <code>ApplicationRunner</code> that comes pre-built with this functionality but it doesn't look too difficult to implement on your own. <a href="https://github.com/isra17/autobahn-autoreconnect/blob/master/autobahn_autoreconnect/__init__.py" rel="nofollow">Here's an <code>asyncio</code> variant</a> which should be straight forward to Twisted. You could follow <a href="https://github.com/crossbario/autobahn-python/issues/295" rel="nofollow">this issue</a> as it seems there is a desire by the dev team to incorporate reconnecting client.</p>
|
Mapping a dynamic json object field in Jackson? <p>I have json objects in the following schema:</p>
<pre><code>{
name: "foo",
timestamp: 1475840608763,
payload:
{
foo: "bar"
}
}
</code></pre>
<p>Here, the <code>payload</code> field contains an embedded json object, and the schema of this object is dynamic, and different each time.</p>
<p>The <code>payload</code> object is the raw output obtained from different API services, and different methods of different API services. It isn't possible to map it to all possible values.</p>
<p>Is it possible to have a java class such as the following:</p>
<pre><code>public class Event
{
public String name;
public long timestamp;
public JsonObject payload;
}
</code></pre>
<p>Or something along those lines, so I can receive the basic schema and process it, then send it to the relevant class which will convert <code>payload</code> to its appropriate expected class?</p>
| <h2>Using <code>JsonNode</code></h2>
<p>You could use <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html" rel="nofollow"><code>JsonNode</code></a> from the <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/package-summary.html" rel="nofollow"><code>com.fasterxml.jackson.databind</code></a> package:</p>
<pre class="lang-java prettyprint-override"><code>public class Event {
public String name;
public long timestamp;
public JsonNode payload;
// Getters and setters
}
</code></pre>
<p>Then parse it using:</p>
<pre class="lang-java prettyprint-override"><code>String json = "{\"name\":\"foo\",\"timestamp\":1475840608763,"
+ "\"payload\":{\"foo\":\"bar\"}}";
ObjectMapper mapper = new ObjectMapper();
Event event = mapper.readValue(json, Event.class);
</code></pre>
<h2>Mapping <code>JsonNode</code> to a POJO</h2>
<p>Consider, for example, you want to map the <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html" rel="nofollow"><code>JsonNode</code></a> instance to the following class:</p>
<pre><code>public class Payload {
private String foo;
// Getters and setters
}
</code></pre>
<p>It can be achieved with the following piece of code: </p>
<pre class="lang-java prettyprint-override"><code>Payload payload = mapper.treeToValue(event.getPayload(), Payload.class);
</code></pre>
<h2>Considering a <code>Map<String, Object></code></h2>
<p>Depending on your requirements, you could use a <code>Map<String, Object></code> instead of <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonNode.html" rel="nofollow"><code>JsonNode</code></a>:</p>
<pre class="lang-java prettyprint-override"><code>public class Event {
public String name;
public long timestamp;
public Map<String, Object> payload;
// Getters and setters
}
</code></pre>
<p>If you need to convert a <code>Map<String, Object></code> to a POJO, use:</p>
<pre class="lang-java prettyprint-override"><code>Payload payload = mapper.convertValue(event.getPayload(), Payload.class);
</code></pre>
<p>According to the Jackson <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html#convertValue(java.lang.Object,%20java.lang.Class)" rel="nofollow">documentation</a>, the <code>convertValue()</code> method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers and deserializers) will be used as for data binding, meaning same object mapper configuration works.</p>
|
MongoDB AggregationOutput longer response time <p>I have a collection named "logTransaction". I want to get the results as you can see in the attached image.</p>
<p><a href="http://i.stack.imgur.com/u60QQ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/u60QQ.jpg" alt="output"></a></p>
<p>logTransaction has many fields but the ones used for this image are:</p>
<p><code>customer</code>, <code>environment</code>, <code>firstTime</code>, <code>lastTime</code>, <code>integrationIds[]</code> (a transaction can have more than 1 integration), <code>transactionStatus</code> (FINISHED, UNFINISHED, FAILED)</p>
<p>I am using <code>AggregationOutput</code> for this result but it is taking more than 30 seconds which is much longer (I think) than the amount of data I have. I just wonder if I can improve this by modifing what I already have or should
I change it totally. What type of indexing should I use to make things even faster?</p>
<p>I use <code>MongoDB</code> and <code>Grails</code>. My current method looks like this:</p>
<pre><code>def myCustomAggregation(integrations, timestamp_lt, timestamp_gt, cust, env) {
def currentRequest = RequestContextHolder.requestAttributes
def customer = cust ?: currentRequest?.session?.customer
def environment = env ?: currentRequest?.session?.environment
//$match
DBObject matchMap = new BasicDBObject('integrationIds', new BasicDBObject('$in', integrations.collectAll { it?.baselineId }))
matchMap.put("firstTimestamp", new BasicDBObject('$lte', timestamp_lt as Long).append('$gte', timestamp_gt as Long))
matchMap.put("customer",customer)
matchMap.put("environment",environment)
DBObject match = new BasicDBObject('$match',matchMap);
//$group1
Map<String, Object> dbObjIdMap1 = new HashMap<String, Object>();
dbObjIdMap1.put('integrationId', '$integrationIds');
dbObjIdMap1.put('transactionStatus', '$transactionStatus');
DBObject groupFields1 = new BasicDBObject( "_id", new BasicDBObject(dbObjIdMap1));
groupFields1.put('total', new BasicDBObject( '$sum', 1));
DBObject group1 = new BasicDBObject('$group', groupFields1);
//$group2
DBObject groupFields2 = new BasicDBObject( "_id", '$_id.integrationId');
groupFields2.put('total_finished',
new BasicDBObject('$sum', new BasicDBObject('$cond', [
new BasicDBObject('$eq', ['$_id.transactionStatus', 'FINISHED']), '$total', 0
]))
);
groupFields2.put('total_unfinished',
new BasicDBObject('$sum', new BasicDBObject('$cond', [
new BasicDBObject('$eq', ['$_id.transactionStatus', 'UNFINISHED']), '$total', 0
]))
);
groupFields2.put('total_failed',
new BasicDBObject('$sum', new BasicDBObject('$cond', [
new BasicDBObject('$eq', ['$_id.transactionStatus', 'FAILED']), '$total', 0
]))
);
DBObject group2 = new BasicDBObject('$group', groupFields2);
// This taking more than 30 seconds. Its too much for the amount of data I have in Database.
AggregationOutput output = db.logTransaction.aggregate(match,group1,group2)
return output.results()
}
</code></pre>
<p>Edit:</p>
<p>I created a compound index as HoefMeistert suggested:</p>
<pre><code>db.logTransaction.createIndex({integrationIds: 1, firstTimestamp: -1, customer: 1, environment: 1})
</code></pre>
<p>But when I use explain on this aggregate:</p>
<pre><code>db.logTransaction.explain().aggregate( [
{ $match: {integrationIds: {$in: ["INT010","INT011","INT012A","INT200"]}, "firstTimestamp": { "$lte" : 1476107324000 , "$gte" : 1470002400000}, "customer": "Awsome_Company", "environment": "PROD"}},
{ $group: { _id: {"integrationId": '$integrationIds', "transactionStatus": '$transactionStatus'}, total: {$sum: 1}}},
{ $group: { _id: "$_id.integrationId", "total_finished": {$sum: {$cond: [{$eq: ["$_id.transactionStatus", "FINISHED"]}, "$total", 0]}}, "total_unfinished": {$sum: {$cond: [{$eq: ["$_id.transactionStatus", "UNFINISHED"]}, "$total", 0]}}, "total_failed": {$sum: {$cond: [{$eq: ["$_id.transactionStatus", "FAILED"]}, "$total", 0]}}}}
]);
</code></pre>
<p>I still get this winningPlan every single time:</p>
<pre><code>"winningPlan" : {
"stage" : "CACHED_PLAN",
"inputStage" : {
"stage" : "FETCH",
"filter" : {
"$and" : [
{
"environment" : {
"$eq" : "PROD"
}
},
{
"integrationIds" : {
"$in" : [
"INT010",
"INT011",
"INT012A",
"INT200"
]
}
}
]
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"tenant" : 1,
"firstTimestamp" : -1
},
"indexName" : "customer_1_firstTimestamp_-1",
"isMultiKey" : false,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "forward",
"indexBounds" : {
"customer" : [
"[\"Awsome_Company\", \"Awsome_Company\"]"
],
"firstTimestamp" : [
"[1476107324000.0, 1470002400000.0]"
]
}
}
}
},
</code></pre>
<p>Current indexes for the collection in development env. and the speed is good compared to before but when timespan is greater than 1 week, I still get sockettimeoutexception (3 minutes):</p>
<pre><code>"customer_1_firstTimestamp_-1" : 56393728,
"firstTimestamp_-1_customer_1" : 144617472,
"integrationIds_1_firstTimestamp_-1" : 76644352,
"integrationId_1_firstTimestamp_-1" : 56107008,
"transactionId_1_firstTimestamp_-1" : 151429120,
"firstTimestamp_1" : 56102912,
"transactionId_1" : 109445120,
"integrationIds_1_firstTimestamp_-1_customer_1_environment_1" : 247790976
</code></pre>
| <p>What indexes you currently have?
When i look at your aggregation make sure you have a indexes on the field you are matching on:</p>
<ul>
<li>integrationIds</li>
<li>firstTimestamp</li>
<li>customer</li>
<li>environment</li>
</ul>
<p>After the first (match) stage indexes are no longer relevant.
As asked by elixir, how is the performance in shell / editor? Is it also slow there. If so try find the "slow" stage.</p>
<p><strong>Update:</strong>
you can also help the <a href="https://docs.mongodb.com/v3.2/core/aggregation-pipeline-optimization/" rel="nofollow">Aggregation Pipeline optimizer</a> ;-) Rewrite the match to a single <a href="https://docs.mongodb.com/manual/reference/operator/query/and/" rel="nofollow">$and</a> match</p>
<pre><code>{ $match: {integrationIds: {$in: ["INT010","INT011","INT012A","INT200"]}, "firstTimestamp": { "$lte" : 1476107324000 , "$gte" : 1470002400000}, "customer": "Awsome_Company", "environment": "PROD"}}
</code></pre>
<p>to:</p>
<pre><code> { $match: { $and : [
{integrationIds: {$in: ["INT010","INT011","INT012A","INT200"]}},
{"firstTimestamp": { "$lte" : 1476107324000 , "$gte" : 1470002400000}},
{"customer": "Awsome_Company"},
{"environment": "PROD"}]
}
</code></pre>
|
excel calculate based on field value <p>I would like to calculate average percentage of the applications marked as in use (Yes)</p>
<p>Anyone?</p>
<pre><code> Average Percentage:
A B C
1 Name Percentage In Use
2 Hammer 65% Yes
3 Fork 77% Yes
4 Spoon 65% No
5 Cars 33% No
6 Wheel 87% Yes
</code></pre>
| <p>I would just use the built-in <code>AVERAGEIF()</code>. </p>
<pre><code>=AVERAGEIF($C$2:$C$6,"Yes",$B$2:$B$6)
</code></pre>
|
Jersey ClassNotFoundException when contextInitialized <p>When I connect to the selected servlet, it throw me a ClassNotFoundException. I am using eclipse neon with Tomcat8 and jersey RESTful framework. Its possible that I have the servlet conf in wrong in the web.xml? </p>
<p><strong>Error showed:</strong></p>
<pre><code>SEVERE: Allocate exception for servlet jersey
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1332)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:518)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:499)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1102)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:828)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p><strong>My web.xml</strong>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>org.CTAG.DATEX2REST</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<display-name>CTAG DATEX2</display-name>
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.CTAG.DATEX2REST</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/rest</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
com.CTAG.application.Init
</listener-class>
</listener>
</web-app>
</code></pre>
<p><strong>The POM.xml:</strong></p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.CTAG.DATEX2REST</groupId>
<artifactId>org.CTAG.DATEX2REST</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>org.CTAG.DATEX2REST Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>org.CTAG.DATEX2REST</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>true</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| <p>Your <code>web.xml</code> content is incorrect, it matches with <code>Jersey 2.x</code> while you obviously use <code>Jersey 1.x</code>, indeed the package names start with <code>com.sun.jersey</code> in <code>Jersey 1.x</code> while in <code>Jersey 2.x</code> they start with <code>org.glassfish.jersey</code>.</p>
<p>Check <a href="https://jersey.java.net/documentation/1.18/jax-rs.html#d4e223" rel="nofollow">here</a> what should be the content of your <code>web.xml</code> in case of <code>Jersey 1.x.</code>.</p>
<pre><code><servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.CTAG.DATEX2REST</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/rest</url-pattern>
</servlet-mapping>
</code></pre>
<p>Or switch to <code>Jersey 2.x</code>.</p>
|
Collapsing and displaying of divs is reverted all at once <p>I'm working with HTML, CSS, JavaScript and jQuery on a prototype for a web application which shall be used on iPad.
I have programmed a test page, which have two divs: one for input fields and the other for displaying a help file (in my case a PDF).
After the page was started, the first div is displayed and the second collapsed.
Above the div-tags i got a button.
When i start the page for the first time and click on that button, i want to collapse the div with the input fields and show the other div with the help file.
Next time i click on the button i want to show the div with the input fields again and collapse the div with the help file.
But when i click the button after starting my test page, the first div (with id "content") is collapsed and the help-div displayed for the fraction of a second and the the original state of the page is restored.</p>
<p>Can anybody help me please?</p>
<p>Here's the HTML i'm using:</p>
<pre><code><form style="position:relative; height:100%; width:100%; overflow-x:scroll; overflow-y:scroll;">
<table>
<tr>
<td>
<button id="load_help" style="font-weight:bold; margin:5px; float:right;">i</button>
</td>
</tr>
<tr>
<td>
<div id="content" style="height:300px; width:500px; background-color:yellow; display:block;">
<label style="position:absolute; top:10px; left:10px; font-family:Arial; font-style:normal; font-weight:bold; font-size:16px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Test page</label>
<label style="position:absolute; top:50px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 1</label>
<label style="position:absolute; top:90px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 2</label>
<label style="position:absolute; top:130px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 3</label>
</div>
</td>
</tr>
<tr>
<td>
<div id="help" style="width:500px; height:200px; background-color:aqua; display:none;">
<object type="application/pdf" data="../HelpDocuments/MyPdf.pdf" style="width:500px; height:500px;"></object>
</div>
</td>
</tr>
</table>
<script src="../scripts/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#load_help").click(function () {
var contentElement = document.getElementById("content");
var helpElement = document.getElementById("help");
if (contentElement.style.display == "block") {
contentElement.style.display = "none";
helpElement.style.display = "block";
}
else {
contentElement.style.display = "block";
helpElement.style.display = "none";
}
});
});
</script>
</form>
</code></pre>
| <p>Your problem is that you are "submitting" the form when you click the button, you need to prevent that event like this: </p>
<pre><code>e.preventDefault()
</code></pre>
<p>You can also type your button as a button to prevent submit like this:</p>
<pre><code><button type="button"></button>
</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>$(document).ready(function() {
$("#load_help").click(function(e) {
var contentElement = document.getElementById("content");
var helpElement = document.getElementById("help");
if (contentElement.style.display == "block") {
contentElement.style.display = "none";
helpElement.style.display = "block";
} else {
contentElement.style.display = "block";
helpElement.style.display = "none";
}
e.preventDefault();
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form style="position:relative; height:100%; width:100%; overflow-x:scroll; overflow-y:scroll;">
<table>
<tr>
<td>
<button id="load_help" style="font-weight:bold; margin:5px; float:right;">i</button>
</td>
</tr>
<tr>
<td>
<div id="content" style="height:300px; width:500px; background-color:yellow; display:block;">
<label style="position:absolute; top:10px; left:10px; font-family:Arial; font-style:normal; font-weight:bold; font-size:16px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Test page</label>
<label style="position:absolute; top:50px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 1</label>
<label style="position:absolute; top:90px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 2</label>
<label style="position:absolute; top:130px; left:20px; font-family:Arial; font-style:normal; font-weight:bold; font-size:12px; text-align:left; border-left-style:none; border-left-width:unset; border-top-style:none; border-top-width:unset; border-right-style:none; border-right-width:unset; border-bottom-style:none; border-bottom-width:unset; height:auto; width:auto; word-wrap:normal; overflow:auto;">Label 3</label>
</div>
</td>
</tr>
<tr>
<td>
<div id="help" style="width:500px; height:200px; background-color:aqua; display:none;">
<object type="application/pdf" data="../HelpDocuments/MyPdf.pdf" width="500px" height="500px"></object>
</div>
</td>
</tr>
</table>
</form></code></pre>
</div>
</div>
</p>
|
second iteration of ddply changes result of first iteration <p>I am trying to run <code>ddply</code> to calculate the number of occurrences of each element in column 1 and then column 2. So I use <code>ddply</code> twice:</p>
<p>1) When I run the operation first time it creates the value I would expect</p>
<pre><code>xx <- ddply(
xx, "Annotated.Sequence", transform,
PSMPerPep = length(Annotated.Sequence)
)
</code></pre>
<p>2) however when I run the same operations second time on a different column, not only does it create a column with wrong numbers, it also manages to change the numbers in the first column. Any suggestions? </p>
<pre><code>xx <- ddply(
xx, "Protein.Accessions", transform,
PSMPerProt = length(Protein.Accessions)
)
</code></pre>
<hr>
<pre><code>xx <- structure(list(Annotated.Sequence = c("ACDLPAWVHFPDTER", "ACIGDTLCQK",
"ACIGDTLCQK", "ADEEFFAK", "AENPGISFGQVGK", "AETLYEGPSDDPFCTAIR",
"AETLYEGPSDDPFCTAIR", "AFDDESVQK", "AILGATNPLQSAPGTIR", "AILGATNPLQSAPGTIR",
"AIVNATTHYNDPVK", "AKGDNDPLDVCEIGEK", "ALALLEDEER", "ALALLEDEER",
"ALALLEDEER", "ALALLEDEER", "APVGNPEGADKPNKK", "APVVQQPAPSFK",
"AQPPEAGPQGLHDLGR", "AQPPEAGPQGLHDLGR", "AQPPEAGPQGLHDLGR", "ASTGEEYTAETDPGVQSVK",
"ASTSTSAPASTPSPSSK", "ATGTTIVTDTGEFEQIAK", "AVANVNDIIAPALIK",
"AVANVNDIIAPALIK", "AVANVNDIIAPALIK", "AVANVNDIIAPALIK", "AVASSGQELSVEER",
"AYLAENDPDSVEAFEK", "AYLAENDPDSVEAFEK", "CLANLRPLLDSGTMGTK",
"CLANLRPLLDSGTMGTK", "DDDHNGHIDFITAASNLR", "DDGYGGGYGGGRPDDR",
"DDLFNTNASIVR", "DFNTGSANAAADAGGEDIPDLVDQKFDDVE", "DFPQLDSQLPK",
"DLFDYAQEK", "DLFDYAQEK", "DLQELIAEGNTK", "DNDSYGSSNRR", "DNDSYGSSNRR",
"DQANDGLSSALLILYLDSAR", "DQANDGLSSALLILYLDSAR", "DQANDGLSSALLILYLDSAR",
"DVGADGQPTEELK", "DVYEDELVPVFEAVGR", "DVYEDELVPVFEAVGR", "DVYEDELVPVFEAVGR",
"DVYEDELVPVFEAVGR", "DVYEDELVPVFEAVGR", "EADTNNDGEIDIQEFTSLLAAK",
"EADTNNDGEIDIQEFTSLLAAK", "EDFTLLDFINAVK", "EDFTLLDFINAVK", "EEEQEEEEDAEK",
"EFILEQHNK", "EGETETEGAATATAAATEAK", "EGTIPTDYEQATGLQR", "EGTIPTDYEQATGLQR",
"EIFDNVNSEFNVALK", "EIFISNITQANPGIVTCLENHPHK", "ELIEPAEGEEVDEDAEPQYR",
"ELIEPAEGEEVDEDAEPQYR", "ELNNYEIRPGR", "ELNNYEIRPGR", "EPTPSIASDISLPIATQELR",
"EPTPSIASDISLPIATQELR", "EPTPSIASDISLPIATQELR", "EPTPSIASDISLPIATQELR",
"EPTPSIASDISLPIATQELR", "EPTPSIASDISLPIATQELR", "EPTPSIASDISLPIATQELR",
"ERLLDEWFTLDEVPK", "ERPPDHQHSAQVK", "ESDEFIAEK", "ESNPADGRENLQSIEDR",
"ETIEPAVR", "FDLNEPLHLSFLQNAAK", "FGGGRPDDR", "FRQELTSLADVYINDAFGTAHR",
"FVSEVAGTNPVNENVPVVGGHSGVTIVPLLSQTK", "FWQTYSSAEEVLQK", "GANTHLSTFSFTK",
"GAPGVAADVSHVPTNSTVK", "GAPGVAADVSHVPTNSTVK", "GATYGKPTNQGVNQLK",
"GDNDPLDVCEIGEK", "GEGEGGELPGVTPYPNENELIK", "GEVTASGDDLVIDGHK",
"GEVTASGDDLVIDGHK", "GFDSAEGLQTSGLHVQGQK", "GGDVSSTTYDA", "GGNDYEIYNDPR",
"GGVIMDVVNADQAK", "GIFGYGYETPSAIQQR", "GISELGIYPAVDPLDSK", "GMITVTDPDLIEK",
"GNPTVEVDFTTDK", "GNPTVEVDFTTDK", "GSGHSNTVR", "GTDEANGATEFDR",
"GTEVNDTGAPISVPVGR", "GTEVNDTGAPISVPVGR", "GTQFGLQTPGSR", "GTQFGLQTPGSR",
"GWDISLTNNYGK", "GWTQWYDLTEDGTRPQAMT", "GWTQWYDLTEDGTRPQAMT",
"HEGGFGGGRPDDR", "HIANISNAK", "HNDDEQYVWESNAGGK", "HSEFVAYPIQLVVTK",
"HVVFGEVTDGLDIVK", "HVVFGEVTDGLDIVK", "HVVFGEVTDGLDIVK", "IADSGLTALSYTQELRPGVK",
"IADSGLTALSYTQELRPGVK", "IDEFLLSLDGTPNK", "IDEFLLSLDGTPNK", "IEEELGSEAIYAGK",
"IEEELGSEAIYAGK", "IEEELGSEAIYAGK", "IESFGSGSGATSK", "IHFIEAQDLQGK",
"IIPAIATTTATVSGLVALEMIK", "IIAAVPNASDVAVCSSR", "ILENSEGGR", "IPRDVYEDELVPVFEAVGR",
"IQEFKPSNK", "IQIVGDDLTVTNPTR", "ISPSDQSSTVISASWDK", "ISPSDQSSTVISASWDK",
"ISSNPNPVVQMSVGHK", "ISSNPNPVVQMSVGHK", "ISSNPNPVVQMSVGHK", "ISSNPNPVVQMSVGHK",
"ISSNPNPVVQMSVGHK", "ISSNPNPVVQMSVGHK", "IVDMSTSK", "IVIEESGQL",
"IVSDWSNIVVAYEPVWAIGTGLAATPEDAEETHK", "IVTGVNPQSAVK", "IWCFGPDGNGPNLVVDQTK",
"KAEDEEEDEGEIDETGLDPK", "KIESCGTSSGTPSASVVIEESGEAEK", "KIESFGSGSGATSK",
"KLEDLSPSTHNMEVPNVSR", "KLQINLVVEDALVSLDDLQAAVEEDEDHVQSTDIAAMQK",
"KPNVGCQQDSEELLK", "KPNVGCQQDSEELLK", "KPNVGCQQDSEELLK", "KPNVGCQQDSEELLK",
"KPNVGCQQDSEELLK", "KPTATTETCAVAAVSAAYEQDAK", "KREEILEEIAK",
"KYDVVVIGGGPGGYVAAIK", "LADYLINVGY", "LEWLTLMPNASNLDK", "LEWLTLMPNASNLDK",
"LFCDFGDEFEVLDTTGEEPK", "LFCDFGDEFEVLDTTGEEPK", "LFCDFGDEFEVLDTTGEEPK",
"LFCDFGDEFEVLDTTGEEPK", "LGANAILGVSLAAANAAAAAQGIPLYK", "LGIHEDAQNR",
"LISWYDNEYGYSTR", "LLGVCCSVDNCR", "LLYGHLDDPHNQEIER", "LLYNDYVSNPSK",
"LQSENFTYEIVK", "LRDQAINNAQR", "LSHVSTGGGASLELLEGK", "LTGGEDNQYGIPK",
"LVEALCNEPEEK", "LVEDPQIVAPFMDK", "LWDLETGETTQR", "LWDLETGETTQR",
"MGHAGAIVAGGK", "MLIFEDVISGDELLSDAYDVK", "MLIFEDVISGDELLSDAYDVK",
"MPIGDSLFDEAGAK", "MQLVQESEEK", "MQLVQESEEK", "MQLVQESEEK", "NCFLNLAIPIVVFTETTEVRKTK",
"NDREFNGIIAQTTNDNITEAGK", "NFALLGVGTSK", "NGDQDLVLEVAQHLGENTVR",
"NLIAFSEDGSDPYVR", "NLIAFSEDGSDPYVR", "NLIAFSEDGSDPYVR", "NLIAFSEDGSDPYVR",
"NLIAFSEDGSDPYVR", "NLIAFSEDGSDPYVR", "NLIAFSEDGSDPYVR", "NQAALNPK",
"NVPGVETASVK", "NWSQCVELAR", "QAFDDAVADLETLSEDSYK", "QATFPGVQMK",
"QATFPGVQMK", "QDVIITALDNVEAR", "QDVIITALDNVEAR", "QDVIITALDNVEAR",
"QEEEEEEK", "QGDNEIEGLTDTTVPK", "QLENGTTLGQSPLGQIQLTIR", "RAGELTQEELER",
"REAQLCVLCDSVTEESIIK", "RERPPDHQHSAQVK", "RERPPDHQHSAQVK", "RERPPDHQHSAQVK",
"RISTVGELNDLFADK", "RISTVGELNDLFADK", "RQENLAK", "RQGTSPDTMR",
"SEPLPTEEEK", "SFGQFNPGCVER", "SFGQFNPGCVER", "SFGQFNPGCVER",
"SFGQFNPGCVER", "SFGQFNPGCVER", "SGETEDTFIADLSVGLR", "SGLAEGYSYTDANK",
"SGLAEGYSYTDANK", "SGQAAFGNMCR", "SGYTLPSNIISNTDVTR", "SHMSGSPGPGGSNTAPSTPVIGGSDKPGMEEK",
"SIDDSVAQIIG", "SINPNYTPVPVPETK", "SIVPSGASTGVHEALELR", "SLQDIIAILGMDELSEADK",
"SNETGILDAIK", "SSSSLLASPGHISVK", "STGDDNEVAEEEEADVEFTPVVQLDK",
"STAAEELANTFGYK", "SVEQIDDCPAGNIIGLVGIDQFLLK", "SYTAADATLK",
"SAAGTYVVFGEAK", "TAEDVIAAFECN", "TASGNIIPSSTGAAK", "TASGNIIPSSTGAAK",
"TASGNIIPSSTGAAK", "TCNVLVAIEQQSPDIAQGLHYEK", "TCYNCGK", "TGQFGWSANMER",
"TGTPLFSSHMLDLSEETDDENIATCAK", "TGYSMVQENGQR", "TGYSMVQENGQR",
"THGPQIK", "TKQTILIAHYPSGVQPGEATTLVEK", "TLNPVFDQSFDFSVSLPEVQR",
"TLNPVFDQSFDFSVSLPEVQRR", "TLNPVFDQSFDFSVSLPEVQRR", "TLTTVQGVPNEYDLK",
"TLTTVQGVPNEYDLKK", "TVEDDHPIPEDVHENYQNTVAEFASR", "VATLYDMIDHQDATNLDDK",
"VCPTTETIYNDEFYTK", "VCPTTETIYNDEFYTK", "VCPTTETIYNDEFYTK", "VDFNVPLDGK",
"VDVGQQPLR", "VEEPLGSYAPNTIDKPFYER", "VEQEAEQQIHK", "VHADQTPEDLDMDDGDTIEAHR",
"VHLVAIDIFTGK", "VIITAPSADAPMFVVGVNEDK", "VIITAPSADAPMFVVGVNEDK",
"VITSSAR", "VNLDTDCQYAYLTGIR", "VNLDTDCQYAYLTGIRDYVTNK", "VNSAVVTCPAYFNDAQR",
"VVDLLEHVAK", "VVDLLEHVAK", "VVDLLEHVAK", "VVNDTFGIEEGLMTTVHSITATQK",
"VVQTDETAR", "WAGNANELNAGYAADGYAR", "WVVIGDENFGEGSSR", "YGGPPPGWEGPHPQR",
"YGIEPTMVVQGVK", "YGQSAGNVGDEGGVAPDIK", "YHIEEEGSSK", "YHIEEEGSSK",
"YKGEVTASGDDLVIDGHK", "YLDQVLDHQR", "YQALSDPSQLESEPELFIR", "YQCVVLTEMK",
"YVDEQVAAAEADAPPEAK", "YVECSALTQR", "YVHGGNVLIDPTAK", "YAATPANPAK",
"YAATPANPAK", "AAADYAPNAAVCIISNPVNSTVPIVAEVFK", "AAADYAPNAAVCIISNPVNSTVPIVAEVFK",
"AAIRDPNPVVFLENEIAYGETFK", "AAVEEGILPGGGTALIK"), Protein.Accessions = c("HS_A0FGR8",
"HS_A0AVT1", "HS_A0AVT1", "CA_Q9URB4", "CA_Q9UVL1", "CA_Q5A0M4",
"CA_Q5A0M4", "CA_Q5A397", "CA_Q5AG68", "CA_Q5AG68", "CA_Q5AIA6",
"CA_P83777", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"CA_Q9URB4", "CA_Q9Y7F0", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"CA_Q5A017", "CA_Q5AGX8", "CA_Q5A017", "CA_P30575", "CA_P30575",
"CA_P30575", "CA_P30575", "CA_O42766", "CA_Q5A860", "CA_Q5A860",
"HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1", "CA_Q5A4I4", "CA_Q5AMP4",
"CA_Q59TU0", "CA_P83775", "CA_Q9URB4", "CA_Q9URB4", "CA_Q5ANH5",
"CA_Q59X49", "CA_Q59X49", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"CA_Q5AL30", "HS_A0AV96", "HS_A0AV96", "HS_A0AV96", "HS_A0AV96",
"HS_A0AV96", "CA_Q59Q76", "CA_Q59Q76", "HS_A0AVT1", "HS_A0AVT1",
"CA_Q59N01", "CA_Q5AGD1", "CA_Q59S96", "CA_Q5ALV5", "CA_Q5ALV5",
"CA_Q5AF03", "HS_A0AVT1", "CA_Q96VB9", "CA_Q96VB9", "HS_A0AV96",
"HS_A0AV96", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"CA_Q9P940", "CA_Q59QN7", "HS_A0FGR8", "HS_A0AVT1", "CA_Q5A4I4",
"CA_P46273", "CA_Q5AMP4", "HS_A0AVT1", "HS_A0FGR8", "CA_Q5AMP4",
"CA_Q5AMP4", "CA_Q5A6R1", "CA_P83777", "CA_Q59P14", "CA_Q5ADM7",
"CA_Q5ADM7", "CA_Q5A786", "CA_Q5AKV3", "CA_P31353", "CA_Q5AIA6",
"CA_P87206", "CA_Q59UR7", "HS_A0AVT1", "CA_P30575", "CA_P30575",
"CA_P46614", "CA_Q59LS1", "CA_Q59UR7", "CA_Q59UR7", "CA_Q59MR4",
"CA_Q59MR4", "CA_P28870", "HS_A0FGR8", "HS_A0FGR8", "CA_Q5A4I4",
"CA_P30575", "CA_P46598", "CA_P46598", "CA_P22011", "CA_P22011",
"CA_P22011", "CA_P83781", "CA_P83781", "CA_P30575", "CA_P30575",
"CA_P30575", "CA_P30575", "CA_P30575", "CA_P22011", "HS_A0FGR8",
"HS_A0AVT1", "CA_O42817", "CA_P83784", "HS_A0AV96", "HS_A0AVT1",
"CA_P30575", "CA_P83774", "CA_P83774", "HS_A0FGR8", "HS_A0FGR8",
"HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "CA_O94083",
"CA_P22011", "CA_Q9P940", "CA_Q5AF03", "CA_Q5A0M4", "CA_Q5ANP2",
"CA_Q5ALM6", "CA_P22011", "CA_O94083", "CA_Q5A652", "HS_A0AVT1",
"HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1", "CA_P46614",
"HS_A0AV96", "CA_Q59RQ6", "CA_Q5A786", "HS_A0FGR8", "HS_A0FGR8",
"HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1", "CA_P30575",
"CA_P46598", "CA_Q5ADM7", "HS_A0AV96", "CA_P82611", "CA_Q5A3Z7",
"CA_P83775", "CA_Q59RJ3", "CA_P46273", "CA_P83774", "CA_Q5ADQ6",
"CA_P25997", "CA_P83774", "CA_P83774", "CA_Q5A8X6", "CA_Q5A860",
"CA_Q5A860", "CA_P46273", "HS_A0A0B4J2F0", "HS_A0A0B4J2F0", "HS_A0A0B4J2F0",
"HS_A0AVT1", "CA_Q5AK04", "HS_A0AVT1", "CA_Q59UR7", "HS_A0FGR8",
"HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"HS_A0FGR8", "CA_Q5A397", "CA_Q59ZX4", "HS_A0AVT1", "CA_O42766",
"CA_P83779", "CA_P83779", "HS_A0AVT1", "HS_A0AVT1", "HS_A0AVT1",
"CA_Q5A795", "CA_Q5AMI6", "HS_A0FGR8", "CA_Q5AFQ0", "CA_Q5ADQ6",
"HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8", "CA_P83779", "CA_P83779",
"CA_Q5A2U8", "CA_Q59W54", "CA_Q5A5F2", "HS_A0AV96", "HS_A0AV96",
"HS_A0AV96", "HS_A0AV96", "HS_A0AV96", "CA_P30575", "CA_P53698",
"CA_P53698", "CA_Q59ZX4", "CA_Q59ZX4", "HS_A0FGR8", "CA_P83775",
"CA_P83779", "CA_P30575", "CA_Q59UR7", "CA_Q59RD8", "HS_A0FGR8",
"CA_Q5AAL2", "CA_Q59SM9", "CA_Q5A0M4", "HS_A0AVT1", "CA_Q5ANP2",
"CA_Q5AF03", "CA_Q5ADM7", "CA_Q5ADM7", "CA_Q5ADM7", "CA_Q59W67",
"CA_Q59YJ9", "CA_P46598", "CA_Q9URB4", "HS_A0AV96", "HS_A0AV96",
"CA_P83775", "CA_Q5A786", "HS_A0FGR8", "HS_A0FGR8", "HS_A0FGR8",
"CA_Q59LQ6", "CA_Q59LQ6", "CA_Q5A7T3", "CA_Q5A5A0", "HS_A0AVT1",
"HS_A0AVT1", "HS_A0AVT1", "CA_P46273", "HS_A0FGR8", "CA_Q5AND4",
"CA_Q5A389", "CA_Q59W54", "CA_O94083", "CA_Q5ADM7", "CA_Q5ADM7",
"CA_Q5A5P4", "CA_Q9URB4", "CA_Q9URB4", "CA_P83784", "CA_Q5ADM7",
"CA_Q5ADM7", "CA_Q5ADM7", "CA_Q5ADM7", "HS_A0AVT1", "CA_P83779",
"CA_P82611", "HS_A0AV96", "HS_A0AVT1", "CA_P30575", "CA_P46273",
"CA_P46273", "CA_Q5ADM7", "CA_Q59TE0", "CA_P46598", "HS_A0AVT1",
"CA_Q5A0Z9", "CA_P0CY33", "CA_O93827", "CA_Q59TE0", "CA_Q59TE0",
"CA_Q5AMP4", "CA_Q5AMP4", "CA_Q5A5V6", "CA_O74261"), PSMPerPep = c(1L,
2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 4L, 4L, 4L, 4L, 1L,
1L, 3L, 3L, 3L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 3L, 3L, 3L, 1L, 5L, 5L,
5L, 5L, 5L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L,
2L, 2L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L,
1L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 6L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 5L, 5L, 5L, 5L, 5L, 1L, 1L, 1L, 1L, 2L, 2L,
4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 1L, 2L, 2L, 1L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L,
1L, 1L, 3L, 3L, 3L, 2L, 2L, 1L, 1L, 1L, 5L, 5L, 5L, 5L, 5L, 1L,
2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L,
1L, 1L, 1L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 1L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L)), .Names = c("Annotated.Sequence",
"Protein.Accessions", "PSMPerPep"), row.names = c(NA, -300L), class = "data.frame")
</code></pre>
| <ol>
<li>a few, major R IDEs will have issues with long lines like the <code>dput()</code> you did (i.e. format it more appropriately in the future like the way @nrussell did)</li>
<li>are you just looking at the modified columns or the entire row since <code>ddply</code> doesn't guarantee you get things back in the same order</li>
</ol>
<p>i.e.:</p>
<pre><code>head(xx)
## Annotated.Sequence Protein.Accessions PSMPerPep
## 1 ACDLPAWVHFPDTER HS_A0FGR8 1
## 2 ACIGDTLCQK HS_A0AVT1 2
## 3 ACIGDTLCQK HS_A0AVT1 2
## 4 ADEEFFAK CA_Q9URB4 1
## 5 AENPGISFGQVGK CA_Q9UVL1 1
## 6 AETLYEGPSDDPFCTAIR CA_Q5A0M4 2
yy <- plyr::ddply(xx, "Annotated.Sequence", transform,
PSMPerPep = length(Annotated.Sequence))
y1 <- yy
head(yy)
## Annotated.Sequence Protein.Accessions PSMPerPep
## 1 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 2 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 3 AAIRDPNPVVFLENEIAYGETFK CA_Q5A5V6 1
## 4 AAVEEGILPGGGTALIK CA_O74261 1
## 5 ACDLPAWVHFPDTER HS_A0FGR8 1
## 6 ACIGDTLCQK HS_A0AVT1 2
yy <- plyr::ddply(yy, "Protein.Accessions", transform,
PSMPerProt = length(Protein.Accessions))
head(yy)
## Annotated.Sequence Protein.Accessions PSMPerPep PSMPerProt
## 1 AVASSGQELSVEER CA_O42766 1 2
## 2 QAFDDAVADLETLSEDSYK CA_O42766 1 2
## 3 IIAAVPNASDVAVCSSR CA_O42817 1 1
## 4 AAVEEGILPGGGTALIK CA_O74261 1 1
## 5 YVHGGNVLIDPTAK CA_O93827 1 1
## 6 IVDMSTSK CA_O94083 1 3
head(dplyr::arrange(y1, Annotated.Sequence))
## Annotated.Sequence Protein.Accessions PSMPerPep
## 1 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 2 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 3 AAIRDPNPVVFLENEIAYGETFK CA_Q5A5V6 1
## 4 AAVEEGILPGGGTALIK CA_O74261 1
## 5 ACDLPAWVHFPDTER HS_A0FGR8 1
## 6 ACIGDTLCQK HS_A0AVT1 2
head(dplyr::arrange(yy, Annotated.Sequence))
## Annotated.Sequence Protein.Accessions PSMPerPep PSMPerProt
## 1 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2 6
## 2 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2 6
## 3 AAIRDPNPVVFLENEIAYGETFK CA_Q5A5V6 1 1
## 4 AAVEEGILPGGGTALIK CA_O74261 1 1
## 5 ACDLPAWVHFPDTER HS_A0FGR8 1 50
## 6 ACIGDTLCQK HS_A0AVT1 2 35
head(dplyr::arrange(xx, Annotated.Sequence))
## Annotated.Sequence Protein.Accessions PSMPerPep
## 1 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 2 AAADYAPNAAVCIISNPVNSTVPIVAEVFK CA_Q5AMP4 2
## 3 AAIRDPNPVVFLENEIAYGETFK CA_Q5A5V6 1
## 4 AAVEEGILPGGGTALIK CA_O74261 1
## 5 ACDLPAWVHFPDTER HS_A0FGR8 1
## 6 ACIGDTLCQK HS_A0AVT1 2
</code></pre>
<p>You could move to <code>dplyr</code> and do something like:</p>
<pre><code>library(dplyr)
xx %>%
group_by(Annotated.Sequence) %>%
mutate(PSMPerPep = n()) %>%
group_by(Protein.Accessions) %>%
mutate(PSMPerProt = n()) %>%
ungroup()
## # A tibble: 300 Ã 4
## Annotated.Sequence Protein.Accessions PSMPerPep PSMPerProt
## <chr> <chr> <int> <int>
## 1 ACDLPAWVHFPDTER HS_A0FGR8 1 50
## 2 ACIGDTLCQK HS_A0AVT1 2 35
## 3 ACIGDTLCQK HS_A0AVT1 2 35
## 4 ADEEFFAK CA_Q9URB4 1 7
## 5 AENPGISFGQVGK CA_Q9UVL1 1 1
## 6 AETLYEGPSDDPFCTAIR CA_Q5A0M4 2 4
## 7 AETLYEGPSDDPFCTAIR CA_Q5A0M4 2 4
## 8 AFDDESVQK CA_Q5A397 1 2
## 9 AILGATNPLQSAPGTIR CA_Q5AG68 2 2
## 10 AILGATNPLQSAPGTIR CA_Q5AG68 2 2
## # ... with 290 more rows
</code></pre>
<p>which preserves the original <code>xx</code> <code>Annotated.Sequence</code> order, too.</p>
|
PreventDefault on null value <p>i am using this code to select an row(id) from a table then modify it in another page in case no row(id) was selected nothing should happen.</p>
<pre><code>$('#modify').click(function (e) {
var id = $.map(table.rows('.selected').data(), function (item) {
return item[0];
});
console.log(id);
if (id === null) {
e.preventDefault();
} else {
window.location = "<spring:url value='/secure/purchaseRequests/item/'/>" + id + "/modify";
}
});
</code></pre>
<p>I am printing the id value and it's null why the preventDefault is not working ?</p>
| <p>Try something like below</p>
<pre><code> $(document).on('click', "#modify", function(e) {
var id = $.map(table.rows('.selected').data(), function (item) {
return item[0];
});
console.log(id);
if (id === null) {
e.stopPropagation();
e.preventDefault();
} else {
window.location = "<spring:url value='/secure/purchaseRequests/item/'/>" + id + "/modify";
}
});
</code></pre>
|
gradle: Exclude all - except one file <p>In a gradle build I would like to exclude all files except one. I tried to do it like this:</p>
<pre><code>processResources {
// exclude everything
exclude '*.*'
// except this file
include 'fileA.xml'
}
</code></pre>
<p>..but it does not seem to work - all files are excluded. Is this possible in some way?</p>
<p>Thanks for your help and input.</p>
| <p>Remove the 'exclude' part, because when you use 'include', you don't have to use 'exclude' patterns - gradle automatically excludes all others.</p>
|
Error inflating class android.support.design.widget.FloatingActionButton in Android <p>When I'm trying to build the application it will show the <code>android.view.InflateException</code> in FloatingActionButton? I really don't know what causes the error.</p>
<p><strong>Login.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@drawable/bg_image" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/lLayout_logincontainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="40dp"
android:orientation="vertical">
<ImageView
android:layout_width="130dp"
android:layout_height="125dp"
android:src="@drawable/project"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<EditText
android:id="@+id/aTxt_UserName"
style="@style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:imeOptions="actionNext"
android:textColorHint="@color/white"
>
</EditText>
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<EditText
android:id="@+id/eTxt_PassWord"
style="@style/edittextstyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:textColorHint="@color/white"
android:textColor="@color/white" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="3dp"
android:background="@drawable/button_shape"
android:padding="12dp"
android:text="Login"
android:textAllCaps="false"
android:textColor="#ffffff" />
</LinearLayout>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_gravity="bottom|end"
android:layout_marginRight="@dimen/fab_margin"
android:visibility="visible"
app:backgroundTint="@color/colorTrade_2"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
app:fabSize="normal"
app:rippleColor="@android:color/transparent"
android:src="@drawable/ic_user_add" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>styles.xml</p>
<pre><code><resources>
<style name="AppBaseTheme" parent="MyMaterialTheme.Base">
</style>
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimaryDark</item>
<item name="android:itemBackground">@color/white</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">12sp</item>
<item name="textAllCaps">false</item>
</style>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="edittextstyle">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">14sp</item>
<item name="android:padding">10dp</item>
<item name="android:singleLine">true</item>
<item name="android:textColorHint">@color/white</item>
<item name="android:inputType">textFilter</item>
</style>
<style name="userProfileText">
<item name="android:textColor">@color/white</item>
<item name="android:textSize">14sp</item>
<item name="android:padding">5dp</item>
</style>
</resources>
</code></pre>
<p>AndroidManifest.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android" package="com.trade.seems">
<uses-library android:name="com.google.android.maps" android:required="true" />
<application android:allowBackup="true"
android:name=".utils.MyApplication"
android:isolatedProcess="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@style/AppTheme">
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="@string/google_api_key" />
<activity android:name=".uil.SplashActivity"
android:screenOrientation="sensorPortrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ual.login.LoginActivity"
android:screenOrientation="sensorPortrait"/>
</application>
</manifest>
</code></pre>
<p><strong>build.gradle</strong></p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '23.0.3'
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.trade.seems"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/maven/ch.acra/acra/pom.xml'
exclude 'META-INF/maven/ch.acra/acra/pom.properties'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
}
}
dexOptions {
javaMaxHeapSize "2g"
}
}
dependencies {
testCompile 'junit:junit:4.12'
compile files('libs/picasso-2.5.2.jar')
compile files('libs/httpclient-4.3.6.jar')
compile files('libs/httpcore-4.3.3.jar')
compile files('libs/httpmime-4.3.6.jar')
compile files('libs/YouTubeAndroidPlayerApi.jar')
compile fileTree(include: ['*.jar'], dir: 'libs')
/*Support Libraries */
compile project(':autocomplete_library')
compile project(':ViewPagerIndicator-Library')
/*Third party Libraries */
compile 'es.guiguegon:gallerymodule:1.3.1'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.nineoldandroids:library:2.4.+'
compile 'com.makeramen:roundedimageview:2.0.1'
//Library to handle Material design for all Version of android
compile 'com.rengwuxian.materialedittext:library:2.1.4'
//Library Glide is to handle Images Instead of picasso
compile 'com.github.bumptech.glide:glide:3.5.2'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
/*Google Android Support Library*/
compile 'com.google.android.gms:play-services-maps:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:multidex:1.0.0'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
}
</code></pre>
<p><strong>Complete Error Trace</strong></p>
<pre><code>com.trade.seems E/AndroidRuntime: FATAL EXCEPTION: main Process: com.trade.seemys, PID: 8225 java.lang.RuntimeException: Unable to start activityComponentInfo{com.tradezap.seemysteps/com.trade.seems.ual.login.LoginActivity}: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)Â
at android.app.ActivityThread.-wrap11(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:148)Â
at android.app.ActivityThread.main(ActivityThread.java:5417)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)Â
Caused by: android.view.InflateException: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)Â
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)Â
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)Â
at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)Â
at android.app.Activity.performCreate(Activity.java:6251)Â
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)Â
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)Â
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)Â
at android.app.ActivityThread.-wrap11(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:148)Â
at android.app.ActivityThread.main(ActivityThread.java:5417)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)Â
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)Â
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)Â
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)Â
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)Â
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)Â
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)Â
at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)Â
at android.app.Activity.performCreate(Activity.java:6251)Â
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)Â
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)Â
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)Â
at android.app.ActivityThread.-wrap11(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:148)Â
at android.app.ActivityThread.main(ActivityThread.java:5417)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)Â
Caused by: java.lang.NoSuchMethodError: No direct method <init>(Landroid/widget/ImageView;Landroid/support/v7/widget/AppCompatDrawableManager;)V in class Landroid/support/v7/widget/AppCompatImageHelper; or its super classes (declaration of 'android.support.v7.widget.AppCompatImageHelper' appears in /data/app/com.tradezap.seemysteps-1/base.apk)
at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:133)
at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:110)
at java.lang.reflect.Constructor.newInstance(Native Method)Â
at android.view.LayoutInflater.createView(LayoutInflater.java:619)Â
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)Â
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)Â
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)Â
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)Â
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)Â
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)Â
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)Â
at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)Â
at android.app.Activity.performCreate(Activity.java:6251)Â
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)Â
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)Â
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)Â
at android.app.ActivityThread.-wrap11(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:148)Â
at android.app.ActivityThread.main(ActivityThread.java:5417)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)Â
</code></pre>
| <p>In your Case, Problem is in your styles.xml, your base theme name is AppBaseTheme. Change it to AppTheme as you can see you have used AppTheme in your Mainfest file.</p>
<p>I have listed all the reasons that may cause class android.support.design.widget.FloatingActionButton. Please read the points carefully.</p>
<ol>
<li><p>FAB button is Design Library Cpmponent. Your Activity must extend <strong>AppCompatActivity</strong> instead of <strong>Activity</strong>.</p></li>
<li><p>Your activity theme also should be appropriate <strong>Theme.AppCompat</strong> theme. Also FAB requires colorAccent. Make sure you have them inside your styles.xml.</p>
<pre><code><!-- Base application theme. -->
<style name="AppTheme" parent="Base.AppTheme">
<!-- Customize your theme here. -->
</style>
<style name="Base.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<item name="android:colorAccent">@color/accent</item>
</style>
</code></pre></li>
<li><p>Use <strong>app:backgroundTint="@color/your_color"</strong> instead of android:backgroundTint.</p></li>
<li><p>Don't miss out on adding design library inside your project build.gradle file</p>
<pre><code>dependencies {
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
...
}
</code></pre></li>
<li><p>Update Support Library on SDK Manager in Extras > Android Support Repository and Android Support Library </p></li>
</ol>
<p>Hope it solves your error.</p>
|
How to use html webworkers with angularjs? <p>I am handling very hight dataset with type arry. While iterating through this arrays my application gets performance hit. I want to use webworkers which will perform manipulation operations on huge array and it will directly return the processed dataset back to application.web</p>
| <p>Take a look at <a href="https://github.com/vkiryukhin/ng-vkthread" rel="nofollow">https://github.com/vkiryukhin/ng-vkthread</a> I develop it exactly for such kind of tasks. It let you easily export function in a thread, execute it and get result in UI. Even more: you can download data directly in a thread rather than transfer it from UI to a thread.</p>
<p>the very basic usage is:</p>
<pre><code>/* function to execute in a thread */
function foo(n, m){
return n + m;
}
/* create an object, which you pass to vkThread as an argument*/
var param = {
fn: foo // <-- function to execute
args: [1, 2] // <-- arguments for this function
};
/* run thread */
vkThread.exec(param).then(
function (data) {
console.log(data); // <-- thread returns 3
},
function(err) {
alert(err); // <-- thread returns error message
}
);
</code></pre>
<p>Doc and examples: <a href="http://www.eslinstructor.net/ng-vkthread/demo/" rel="nofollow">http://www.eslinstructor.net/ng-vkthread/demo/</a></p>
|
4th column is shown when specifying column-count of 3 <p>I'm trying to leverage the css 'column-count' in combination with CSS padding, and and I'm observing that if I specify a column count of 3, the browser renders part of a fourth column if content doesn't fit. as shown below</p>
<p><a href="http://i.stack.imgur.com/O6GO1.png" rel="nofollow"><img src="http://i.stack.imgur.com/O6GO1.png" alt="enter image description here"></a></p>
<p>Here is a JSFidle -> <a href="https://jsfiddle.net/49Lfnao3/" rel="nofollow">https://jsfiddle.net/w40jcykp/1/</a></p>
<p>I'm seeing this in Chrome & Edge. is this a known issue, or is there a workaround for this? </p>
<p>Thank you kindly.</p>
<p>The CSS below.</p>
<pre><code>.newspaper {
column-count: 3;
min-height:144px;
height:144px;
padding:20px;
column-gap:10px;
border: 1px solid black;
overflow:hidden;
}
</code></pre>
| <p>I think the issue here is that you've set a fixed height on your container. With the fixed height, the columns can't grow, so the rendering engine keeps making more columns to fit your content inside the container.</p>
<p>If you turn off <code>overflow: hidden</code> in your fiddle, you'll see that there actually a bunch more columns overflowing out of the side of your box. The <code>padding</code> just allows part of one of them to be visible.</p>
<p>The root cause here is <em>height balancing</em>. <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts" rel="nofollow">From MDN</a>:</p>
<blockquote>
<p>The CSS3 Column specification requires that the column heights must be
balanced: that is, the browser automatically sets the maximum column
height so that the heights of the content in each column are
approximately equal. Firefox does this.</p>
<p>However, in some situations it is also useful to set the maximum
height of the columns explicitly, and then lay out content starting at
the first column and creating as many columns as necessary, possibly
overflowing to the right. Therefore, if the height is constrained, by
setting the CSS height or max-height properties on a multi-column
block, each column is allowed to grow to that height and no further
before adding new column. This mode is also much more efficient for
layout.</p>
</blockquote>
<p>Since you've set the height, height balancing says that the browser will fix columns to that height, and will create as many columns as it needs to display your content.</p>
<p>You'll need to remove your fixed height if you want your columns to grow and flow correctly and obey your <code>column-count</code> property.</p>
|
More explanation for Java multiTab <p>Is it possible to explain multiTab in Java ?
For this example : </p>
<pre><code>int[][] multiTab = {{1,2,3,4,5,6},
{1,2,3,4},
{1,2,3,4,5,6,7,8,9}};
</code></pre>
<p>What would be the rows and the columns ?</p>
| <pre><code>int[][] multiTab = {{1,2,3,4,5,6},//[0][x]
{1,2,3,4},//[1][x]
{1,2,3,4,5,6,7,8,9}};//[2][x]
</code></pre>
<p>This type of array can also be called a multidimensional array. This is a type of array that is useful if you want to get information that hangs together. Example:</p>
<p>if [0][x] is a country, [1][x] is a city and [2][x] is some other info, you can use the same var for x but change the first var to get the info that hangs together.</p>
<p>Read more here: <a href="http://www.homeandlearn.co.uk/java/multi-dimensional_arrays.html" rel="nofollow">http://www.homeandlearn.co.uk/java/multi-dimensional_arrays.html</a></p>
<p>Or here: <a href="http://stackoverflow.com/questions/12231453/syntax-for-creating-a-two-dimensional-array">Syntax for creating a two-dimensional array</a></p>
<p>Or here: <a href="http://www.dailyfreecode.com/code/multi-dimensional-array-1352.aspx" rel="nofollow">http://www.dailyfreecode.com/code/multi-dimensional-array-1352.aspx</a></p>
|
How to extract all href content from a page using scrapy <p>I am trying to crawl <a href="https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release" rel="nofollow">https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release</a>.</p>
<p>I want to get all links from a given website using Scrapy</p>
<p>I am trying to this way -</p>
<pre><code>import scrapy
import unidecode
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from lxml import html
class ElementSpider(scrapy.Spider):
name = 'linkdata'
start_urls = ["https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release",]
def parse(self, response):
links = response.xpath('//div[@id="all_votes"]/table[@class="tableList js-dataTooltip"]/div[@class="js-tooltipTrigger tooltipTrigger"]/a/@href').extract()
print links
</code></pre>
<p>But i am getting nothing in output.</p>
| <p>I think your xpath is worng. Try this-</p>
<pre><code>for href in response.xpath('//div[@id="all_votes"]/table[@class="tableList js-dataTooltip"]/tr/td[2]/div[@class="js-tooltipTrigger tooltipTrigger"]/a/@href'):
full_url = response.urljoin(href.extract())
print full_url
</code></pre>
<p>Hope it helps :)</p>
<p>Good luck...</p>
|
Open different Web page with button on single ViewController <p>I know how to implement webview in my app and now I want to use only one ViewController to open different webpages of my site, like this:</p>
<p>First viewcontroller has buttons: button1, button2 and button3.</p>
<p>Then in second viewcontroller:</p>
<ul>
<li>if button1 clicked: <code>mysite.com</code></li>
<li>if button2 clicked: <code>mysite.com/page</code></li>
<li>if button3 clicked: <code>mySite.com/Page2</code></li>
</ul>
<p>So far I have created one viewcontroler per category, so I have many categories and it is more frustrating.</p>
<p>I want sumthing like this:
<a href="http://i.stack.imgur.com/ochHU.png" rel="nofollow"><img src="http://i.stack.imgur.com/ochHU.png" alt="enter image description here"></a></p>
| <p><a href="http://i.stack.imgur.com/qkqUm.png" rel="nofollow"><img src="http://i.stack.imgur.com/qkqUm.png" alt="enter image description here"></a>Yes you can open multiple links in same web view by clicking on different buttons like</p>
<pre><code> myWebView = UIWebView(frame: CGRectMake(0,0, self.view.frame.size.width,self.view.frame.size.height-100))
myWebView.delegate = self
self.view.addSubview(myWebView)
let Button1 = UIButton(frame: CGRectMake(10,self.view.frame.size.height-50,50,50))
Button1.setTitle("Link 1", forState: .Normal)
Button1.setTitleColor(UIColor.redColor(), forState: .Normal)
Button1.addTarget(self, action: #selector(button1Action), forControlEvents: .TouchUpInside)
self.view.addSubview(Button1)
let Button2 = UIButton(frame: CGRectMake(150,self.view.frame.size.height-50,50,50))
Button2.setTitle("Link 1", forState: .Normal)
Button2.setTitleColor(UIColor.redColor(), forState: .Normal)
Button2.addTarget(self, action: #selector(button2Action), forControlEvents: .TouchUpInside)
self.view.addSubview(Button2)
let Button3 = UIButton(frame: CGRectMake(250,self.view.frame.size.height-50,50,50))
Button3.setTitle("Link 1", forState: .Normal)
Button3.setTitleColor(UIColor.redColor(), forState: .Normal)
Button3.addTarget(self, action: #selector(button3Action), forControlEvents: .TouchUpInside)
self.view.addSubview(Button3)
}
func button1Action()
{
let myUrl = NSURL(string: "https://www.google.co.in")
let request = NSMutableURLRequest(URL: myUrl!)
myWebView.loadRequest(request)
}
func button2Action()
{
let myUrl = NSURL(string: "http://stackoverflow.com/questions/tagged/ios")
let request = NSMutableURLRequest(URL: myUrl!)
myWebView.loadRequest(request)
}
func button3Action()
{
let myUrl = NSURL(string: "http://stackoverflow.com/questions/39916960/open-diffrent-webpage-with-button-on-single-viewcontroller")
let request = NSMutableURLRequest(URL: myUrl!)
myWebView.loadRequest(request)
}
</code></pre>
<p>And don't forget to set in info.plist App Transport Security Settings to Allow arbitrary load true<a href="http://i.stack.imgur.com/xyN6F.png" rel="nofollow"><img src="http://i.stack.imgur.com/xyN6F.png" alt="enter image description here"></a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.