id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
37,349,470 | Codeigniter Controller return to previous page | <p>I'd like to ask you how can I instead of $this->load->view('some_view.php') at the end of controller code, return user to page from where he invoked controller method? Simple return statement is not working. </p>
<p>ie.</p>
<pre><code>public function someMethod($IDCustomer) {
$this->Some_modal->persist($IDCustomer);
// how to return to previous page instead of line after?
// i've used $this->load->view('someView.php');
}
</code></pre> | 37,349,696 | 6 | 0 | null | 2016-05-20 14:33:53.327 UTC | 1 | 2021-05-01 12:32:13.47 UTC | null | null | null | null | 5,752,522 | null | 1 | 14 | php|codeigniter | 63,354 | <p>This should help <a href="http://www.codeigniter.com/user_guide/libraries/user_agent.html" rel="noreferrer">http://www.codeigniter.com/user_guide/libraries/user_agent.html</a></p>
<pre><code>$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
</code></pre>
<p>or straight PHP:</p>
<pre><code>redirect($_SERVER['HTTP_REFERER']);
</code></pre> |
25,559,332 | Qt Designer vs Qt Quick Designer vs Qt Creator? | <p>I have seen references to all three of these applications on various parts of the Qt website but am completely unclear as to the exact differences between them and whether they are actually separate things or just different names for the same thing, or the name changed over time? Or is one no longer supported? What's the deal with these?</p> | 25,559,413 | 4 | 0 | null | 2014-08-28 23:04:19.213 UTC | 13 | 2021-11-05 15:51:54.833 UTC | 2019-06-06 07:37:15.06 UTC | null | 6,622,587 | null | 1,029,146 | null | 1 | 81 | qt|qml|qt-creator|qt-designer|qt-quick | 71,288 | <p>Qt Creator is Qt's IDE. You don't <em>have</em> to use it, but it greatly simplifies Qt development.</p>
<p>Qt Designer is a graphical tool that lets you build QWidget GUIs. Qt Quick Designer is similar, but for building QML GUIs. Both are built in to Qt Creator.</p>
<p>This is explained in a little more detail <a href="http://en.wikipedia.org/wiki/Qt_Creator#Editors">over at Wikipedia</a>.</p> |
47,584,359 | Angular Error: 'Component 'X' is not included in a module...' when declared in a sub module | <p>I'm trying to consolidate my dialogs into an Angular module, but I'm getting a linting error in the IDE:</p>
<blockquote>
<p>Component 'X' is not included in a module and will not be available
inside a template. Consider adding it to an NgModule declaration.</p>
</blockquote>
<p>Despite this error the application still loads and runs successfully.</p>
<p><strong>Example Component Definition</strong></p>
<pre><code>import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
export interface AlertDialogData {
titleText: string;
dismissalText: string;
contentComponent: string;
}
@Component({
selector: 'app-alert-dialog',
templateUrl: './alert-dialog.component.html',
styleUrls: ['./alert-dialog.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class AlertDialogComponent implements OnInit {
constructor(private dialogRef: MatDialogRef<AlertDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { }
ngOnInit() {
}
handleCloseClick(): void {
this.dialogRef.close();
}
}
</code></pre>
<p><strong>Sub module making Declaration/Export</strong></p>
<pre><code>import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ZipLocatorDialogComponent } from './zip-locator-dialog/zip-locator-dialog.component';
import { AlertDialogComponent } from './alert-dialog/alert-dialog.component';
import { HelperDialogComponent } from './helper-dialog/helper-dialog.component';
import {
MatAutocompleteModule, MatButtonModule, MatDialogModule, MatFormFieldModule, MatInputModule,
MatSelectModule
} from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FlexLayoutModule,
FormsModule,
ReactiveFormsModule,
MatDialogModule,
MatInputModule,
MatFormFieldModule,
MatSelectModule,
MatAutocompleteModule,
MatButtonModule
],
exports: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
declarations: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
entryComponents: [
ZipLocatorDialogComponent,
HelperDialogComponent,
AlertDialogComponent
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
})
export class AppDialogsModule { }
</code></pre>
<p><strong>App Module</strong></p>
<pre><code>// <editor-fold desc="Global Application Imports">
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { RouteDefinitions } from './app.routes';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FlexLayoutModule } from '@angular/flex-layout';
import { WebWrapperModule } from 'web-wrapper';
import { UiComponentsModule } from './ui-components.module';
import { AppComponent } from './app.component';
// OPERATORS
import './rxjs-operators';
// SERVICES
import { LoginManagerService } from './services/login-manager.service';
import { UtilsService } from './services/utils.service';
import { DataManagerService } from './services/data-manager.service';
import { ReferenceDataManagerService } from './services/reference-data-manager.service';
import { InfrastructureApiService } from './services/infrastructure-api.service';
// </editor-fold>
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
FlexLayoutModule,
HttpClientModule,
WebWrapperModule,
UiComponentsModule,
AppDialogsModule,
RouterModule.forRoot(RouteDefinitions)
],
providers: [
UtilsService,
LoginManagerService,
DataManagerService,
InfrastructureApiService,
ReferenceDataManagerService
],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p><strong>Versions</strong></p>
<pre><code>Angular CLI: 1.5.0
Node: 7.2.1
OS: win32 x64
Angular: 4.4.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router, tsc-wrapped
@angular/cdk: 2.0.0-beta.12
@angular/cli: 1.5.0
@angular/flex-layout: 2.0.0-beta.11-b01c2d7
@angular/material: 2.0.0-beta.12
@angular-devkit/build-optimizer: 0.0.32
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.35
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0
@schematics/angular: 0.1.2
typescript: 2.4.2
webpack: 3.8.1
</code></pre> | 50,678,966 | 6 | 8 | null | 2017-11-30 23:31:43.267 UTC | 3 | 2021-05-05 13:39:57.42 UTC | 2019-01-23 19:10:04.123 UTC | null | 2,432,532 | null | 2,432,532 | null | 1 | 27 | angular|typescript|angular-cli|lint | 52,924 | <p>I had this same issue and this is how it got resolved :</p>
<p>1) Goto Intellij / IDE settings and tick(set) the Recompile on changes to :</p>
<p><a href="https://i.stack.imgur.com/joVlj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/joVlj.png" alt="enter image description here"></a></p>
<p>2) Goto <em>tsconfig.json</em> and set the <em>compileOnSave</em> to true :</p>
<p><a href="https://i.stack.imgur.com/pd48Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pd48Z.png" alt="enter image description here"></a></p>
<p>Now go and remove the @Component that's causing the issue, and retype @Component.</p>
<p>This worked for me :) Good Luck.</p> |
47,702,220 | What made i = i++ + 1; legal in C++17? | <p>Before you start yelling undefined behaviour, this is <em>explicitly</em> listed in <a href="https://timsong-cpp.github.io/cppwp/n4659/intro.execution#17" rel="noreferrer">N4659 (C++17)</a></p>
<pre><code> i = i++ + 1; // the value of i is incremented
</code></pre>
<p>Yet in <a href="https://timsong-cpp.github.io/cppwp/n3337/intro.execution#15" rel="noreferrer">N3337 (C++11)</a></p>
<pre><code> i = i++ + 1; // the behavior is undefined
</code></pre>
<p>What changed?</p>
<p>From what I can gather, from <a href="https://timsong-cpp.github.io/cppwp/n4659/intro.execution#17" rel="noreferrer">[N4659 basic.exec]</a></p>
<blockquote>
<p>Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.</p>
</blockquote>
<p>Where <em>value</em> is defined at <a href="https://timsong-cpp.github.io/cppwp/n4659/basic.types#4" rel="noreferrer">[N4659 basic.type]</a></p>
<blockquote>
<p>For trivially copyable types, the value representation is a set of bits in the object representation that determines a <em>value</em>, which is one discrete element of an implementation-defined set of values</p>
</blockquote>
<p>From <a href="https://timsong-cpp.github.io/cppwp/n3337/intro.execution#15" rel="noreferrer">[N3337 basic.exec]</a></p>
<blockquote>
<p>Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.</p>
</blockquote>
<p>Likewise, value is defined at <a href="https://timsong-cpp.github.io/cppwp/n3337/basic.types#4" rel="noreferrer">[N3337 basic.type]</a></p>
<blockquote>
<p>For trivially copyable types, the value representation is a set of bits in the object representation that determines a <em>value</em>, which is one discrete element of an implementation-defined set of values.</p>
</blockquote>
<p>They are identical except mention of concurrency which doesn't matter, and with the usage of <em>memory location</em> instead of <em>scalar object</em>, where</p>
<blockquote>
<p>Arithmetic types, enumeration types, pointer types, pointer to member types, <code>std::nullptr_t</code>, and cv-qualified versions of these types are collectively called scalar types.</p>
</blockquote>
<p>Which doesn't affect the example.</p>
<p>From <a href="https://timsong-cpp.github.io/cppwp/n4659/expr.ass#1" rel="noreferrer">[N4659 expr.ass]</a></p>
<blockquote>
<p>The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.</p>
</blockquote>
<p>From <a href="https://timsong-cpp.github.io/cppwp/n3337/expr.ass#1" rel="noreferrer">[N3337 expr.ass]</a></p>
<blockquote>
<p>The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.</p>
</blockquote>
<p>The only difference being the last sentence being absent in N3337.</p>
<p>The last sentence however, shouldn't have any importance as the left operand <code>i</code> is neither <em>"another side effect"</em> nor <em>"using the value of the same scalar object"</em> as the <em>id-expression</em> is a lvalue.</p> | 47,702,440 | 4 | 17 | null | 2017-12-07 19:16:32.08 UTC | 52 | 2020-01-19 21:20:33.057 UTC | 2017-12-11 12:51:50.333 UTC | null | 4,778,809 | null | 4,832,499 | null | 1 | 196 | c++|language-lawyer|c++17 | 15,677 | <p>In C++11 the act of "assignment", i.e. the side-effect of modifying the LHS, is sequenced after the <em>value computation</em> of the right operand. Note that this is a relatively "weak" guarantee: it produces sequencing only with relation to <em>value computation</em> of the RHS. It says nothing about the <em>side-effects</em> that might be present in the RHS, since occurrence of side-effects is not part of <em>value computation</em>. The requirements of C++11 establish no relative sequencing between the act of assignment and any side-effects of the RHS. This is what creates the potential for UB. </p>
<p>The only hope in this case is any additional guarantees made by specific operators used in RHS. If the RHS used a prefix <code>++</code>, sequencing properties specific to the prefix form of <code>++</code> would have saved the day in this example. But postfix <code>++</code> is a different story: it does not make such guarantees. In C++11 the side-effects of <code>=</code> and postfix <code>++</code> end up unsequenced with relation to each other in this example. And that is UB.</p>
<p>In C++17 an extra sentence is added to the specification of assignment operator: </p>
<blockquote>
<p>The right operand is sequenced before the left operand.</p>
</blockquote>
<p>In combination with the above it makes for a very strong guarantee. It sequences <em>everything</em> that happens in the RHS (including any side-effects) before <em>everything</em> that happens in the LHS. Since the actual assignment is sequenced <em>after</em> LHS (and RHS), that extra sequencing completely isolates the act of assignment from any side-effects present in RHS. This stronger sequencing is what eliminates the above UB.</p>
<p>(Updated to take into account @John Bollinger's comments.)</p> |
37,405,265 | Value was either too large or too small for a UInt32: TFS Checkin Error | <p>When I'm trying to check in some code TFS and below error message is coming.</p>
<blockquote>
<p><strong>Value was either too large or too small for a UInt32.</strong></p>
</blockquote>
<p>What is causing this issue and how can I fix this issue?</p> | 37,405,385 | 4 | 1 | null | 2016-05-24 05:43:32.277 UTC | 12 | 2020-05-16 17:06:42.85 UTC | 2016-05-24 06:05:44.773 UTC | null | 2,674,680 | null | 2,674,680 | null | 1 | 118 | tfs | 33,375 | <p>I have found the solution for this issue.</p>
<p><strong>Solution:</strong> </p>
<blockquote>
<p>Save your files before check-in and then initiate check in. This issue
will not come.</p>
</blockquote>
<p><strong>Root Cause:</strong> </p>
<blockquote>
<p>It seems to be a bug in the dialog (Not sure), but certainly error
message is confusing to user.</p>
</blockquote>
<p>Hope this solution will resolve your issue.</p> |
37,489,280 | Python3 list files from particular directory | <p>How to list file names which are only from a particular directory? I don't want file names from sub-directory or anything. </p> | 37,489,342 | 1 | 1 | null | 2016-05-27 17:30:01.747 UTC | 1 | 2018-01-26 00:49:53.087 UTC | null | null | null | null | 3,597,719 | null | 1 | 28 | python|linux|file|python-3.x|filenames | 45,694 | <pre><code>os.listdir(dir)
</code></pre>
<p>Also see
<a href="https://stackoverflow.com/questions/11968976/list-files-in-only-the-current-directory">List files in ONLY the current directory</a></p> |
29,676,170 | AdminTokenAction: FATAL ERROR: Cannot obtain Application SSO token | <p>I was trying to install openam 12 war with apache tomcat agent as configured sso.But tried more than fifty times but am getting only error.</p>
<p>If I change below property value as <em>amAdmin</em> from <em>webagent</em>,while calling the protected application in tomcat second instance it countinously redirecting to same page again and again but didn't get any exception. amAdmin is my admin user of openam console.</p>
<pre><code>OpenSSOAgentBootstrap.properties/com.sun.identity.agents.app.username =
</code></pre>
<p><strong>Exception in Tomcat log</strong></p>
<pre><code>Apr 16, 2015 5:41:10 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw error
java.lang.ExceptionInInitializerError
at com.sun.identity.agents.arch.AgentConfiguration.bootStrapClientConfiguration(AgentConfiguration.java:727)
at com.sun.identity.agents.arch.AgentConfiguration.initializeConfiguration(AgentConfiguration.java:1140)
at com.sun.identity.agents.arch.AgentConfiguration.<clinit>(AgentConfiguration.java:1579)
at com.sun.identity.agents.arch.Manager.<clinit>(Manager.java:675)
at com.sun.identity.agents.tomcat.v6.AmTomcatRealm.<clinit>(AmTomcatRealm.java:67)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:374)
at org.apache.tomcat.util.digester.ObjectCreateRule.begin(ObjectCreateRule.java:145)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1288)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1342)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2770)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1561)
at org.apache.catalina.startup.Catalina.load(Catalina.java:615)
at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: com.sun.identity.security.AMSecurityPropertiesException: AdminTokenAction: FATAL ERROR: Cannot obtain Application SSO token.
Check AMConfig.properties for the following properties
com.sun.identity.agents.app.username
com.iplanet.am.service.password
at com.sun.identity.security.AdminTokenAction.run(AdminTokenAction.java:272)
at com.sun.identity.security.AdminTokenAction.run(AdminTokenAction.java:76)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.identity.common.configuration.ConfigurationObserver.registerListeners(ConfigurationObserver.java:89)
at com.sun.identity.common.configuration.ConfigurationObserver.getInstance(ConfigurationObserver.java:114)
at com.sun.identity.common.DebugPropertiesObserver.<clinit>(DebugPropertiesObserver.java:49)
... 32 more
</code></pre>
<p><strong>host entry</strong> </p>
<pre><code>127.0.0.1 org.sso.com test.openam.com
</code></pre>
<p><strong>Tomcat two instances from apache-tomcat-7.0.57</strong></p>
<pre><code>**1, One for OpenAM.12.0.war running in port 8080
2, Another one for webagent(openam-Tomcat-v6-7-Agent-3.3.0.zip) with my protected application running in port 7070**
</code></pre>
<p><strong>OpenAM configuration :</strong></p>
<pre><code>1, Default configuration amAdmin with password (password) and policy-agent with password(password1) created.
2, Login as amAdmin -->Access Control -- >OpenAMIDPRealm-->created
3, Access Control -- >OpenAMIDPRealm-->subject-->idpuser-->password(password)-->created
4, Access Control -- >OpenAMIDPRealm-->agent-->J2EE-->name(webagent)-->password(password)-->local-->agenturl(http://org.sso.com:7070/agentapp)-->created
5, Federation -- >Create Circle of Trust -- > OpenAMIDPCOT -->select realm (OpenAMIDPRealm) -->created
6, Common Tasks --> create hosted identity provider --> select realm (OpenAMIDPRealm) --> select Circle of Trust -- > OpenAMIDPCOT -->created
</code></pre>
<p><strong>Web Agent configuration :</strong></p>
<pre><code>D:\Studies\sso\OpenAM-SP2IDP\webagent\j2ee_agents\tomcat_v6_agent\bin>agentadmin --install
Please read the following License Agreement carefully:
[Press <Enter> to continue...] or [Enter n To Finish]
************************************************************************
Welcome to the OpenAM Policy Agent for Apache Tomcat 6.0 Servlet/JSP
Container
************************************************************************
Enter the complete path to the directory which is used by Tomcat Server to
store its configuration Files. This directory uniquely identifies the
Tomcat Server instance that is secured by this Agent.
[ ? : Help, ! : Exit ]
Enter the Tomcat Server Config Directory Path [C:/Program Files/Apache
Software Foundation/Tomcat 6.0/conf]: D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat
-SP\apache-tomcat-7.0.57\conf
Enter the URL where the OpenAM server is running. Please include the
deployment URI also as shown below:
(http://openam.sample.com:58080/openam)
[ ? : Help, < : Back, ! : Exit ]
OpenAM server URL: http://test.openam.com:8080/openam
$CATALINA_HOME environment variable is the root of the tomcat
installation.
[ ? : Help, < : Back, ! : Exit ]
Enter the $CATALINA_HOME environment variable: D:\Studies\sso\OpenAM-SP2IDP\apac
he-tomcat-SP\apache-tomcat-7.0.57
Choose yes to deploy the policy agent in the global web.xml file.
[ ? : Help, < : Back, ! : Exit ]
Install agent filter in global web.xml ? [true]: true
Enter the Agent URL. Please include the deployment URI also as shown below:
(http://agent1.sample.com:1234/agentapp)
[ ? : Help, < : Back, ! : Exit ]
Agent URL: http://org.sso.com:7070/agentapp
Enter the Agent profile name
[ ? : Help, < : Back, ! : Exit ]
Enter the Agent Profile name: webagent
Enter the path to a file that contains the password to be used for identifying
the Agent.
[ ? : Help, < : Back, ! : Exit ]
Enter the path to the password file: D:\Studies\sso\OpenAM-SP2IDP\password.txt
WARNING:
Agent profile/User: webagent does not exist in OpenAM server! Either "Hit
the Back button, and re-enter the correct agent profile name/user name", or
"Create this agent profile when asked(available only in custom-install)",
or "Continue without validating it because agent profile is in sub realm", or
"Continue without validating/creating it, and manually validate/create
it in OpenAM server after installation".
-----------------------------------------------
SUMMARY OF YOUR RESPONSES
-----------------------------------------------
Tomcat Server Config Directory :
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57\conf
OpenAM server URL : http://test.openam.com:8080/openam
$CATALINA_HOME environment variable :
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57
Tomcat global web.xml filter install : true
Agent URL : http://org.sso.com:7070/agentapp
Agent Profile name : webagent
Agent Profile Password file name :
D:\Studies\sso\OpenAM-SP2IDP\password.txt
Verify your settings above and decide from the choices below.
1. Continue with Installation
2. Back to the last interaction
3. Start Over
4. Exit
Please make your selection [1]: 1
Updating the
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57/bin/setenv.ba
t
script with the Agent configuration JVM option ...DONE.
DONE.
Creating directory layout and configuring Agent file for Agent_001
instance ...DONE.
Reading data from file D:\Studies\sso\OpenAM-SP2IDP\password.txt and
encrypting it ...DONE.
Generating audit log file name ...DONE.
Creating tag swapped OpenSSOAgentBootstrap.properties file for instance
Agent_001 ...DONE.
Creating a backup for file
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57\conf/server.x
ml
...DONE.
Creating a backup for file
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57\conf/web.xml
...DONE.
Adding OpenAM Tomcat Agent Realm to Server XML file :
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57\conf/server.x
ml
...DONE.
Adding filter to Global deployment descriptor file :
D:\Studies\sso\OpenAM-SP2IDP\apache-tomcat-SP\apache-tomcat-7.0.57\conf/web.xml
...DONE.
Adding OpenAM Tomcat Agent Filter and Form login authentication to selected
Web applications ...DONE.
SUMMARY OF AGENT INSTALLATION
-----------------------------
Agent instance name: Agent_001
Agent Bootstrap file location:
D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/conf
ig/OpenSSOAgentBootstrap.properties
Agent Configuration file location
D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/conf
ig/OpenSSOAgentConfiguration.properties
Agent Audit directory location:
D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/logs
/audit
Agent Debug directory location:
D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/logs
/debug
Install log file location:
D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/installer-logs
/audit/install.log
Thank you for using OpenAM Policy Agent
</code></pre>
<p><strong>OpenSSOAgentBootstrap.properties</strong></p>
<pre><code>com.iplanet.am.naming.url=http://test.openam.com:8080/openam/namingservice
com.sun.identity.agents.config.service.resolver = com.sun.identity.agents.tomcat.v6.AmTomcatAgentServiceResolver
com.sun.identity.agents.app.username = webagent
com.iplanet.am.service.secret = AQIC91zdxfnLewLIWRJDohP4vdRaQ/7vpmBl
am.encryption.pwd = lZco703977UeM52+kT4ZdyIjLM2PMw3d
com.iplanet.services.debug.level=error
com.iplanet.services.debug.directory=D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/logs/debug
com.sun.services.debug.mergeall=on
com.sun.identity.agents.config.local.logfile = D:/Studies/sso/OpenAM-SP2IDP/webagent/j2ee_agents/tomcat_v6_agent/Agent_001/logs/audit/amAgent_org_sso_com_7070.log
com.sun.identity.agents.config.organization.name = /
com.sun.identity.agents.config.lock.enable = false
com.sun.identity.agents.config.profilename = webagent
com.iplanet.am.services.deploymentDescriptor=/openam
</code></pre>
<p><strong>openam/WEB-INF/classes/AMConfig.properties</strong></p>
<pre><code>com.iplanet.am.server.host=@SERVER_HOST@
com.iplanet.security.SSLSocketFactoryImpl=com.sun.identity.shared.ldap.factory.JSSESocketFactory
com.sun.identity.sm.sms_object_class_name=com.sun.identity.sm.@SMS_OBJECT_CLASS@
com.iplanet.services.configpath=@BASE_DIR@
com.iplanet.am.serverMode=true
com.iplanet.am.ldap.connection.ldap.error.codes.retries=80,81,91
com.iplanet.am.locale=@PLATFORM_LOCALE@
com.sun.identity.urlconnection.useCache=false
opensso.protocol.handler.pkgs=
com.iplanet.am.server.protocol=@SERVER_PROTO@
com.iplanet.am.server.port=@SERVER_PORT@
com.iplanet.services.debug.level=error
com.sun.embedded.replicationport=
com.sun.identity.common.systemtimerpool.size=3
com.sun.identity.overrideAMC=true
com.sun.embedded.sync.servers=on
com.iplanet.am.service.secret=@ENCLDAPUSERPASSWD@
am.encryption.pwd=@AM_ENC_KEY@
com.sun.identity.sm.enableDataStoreNotification=@DATASTORE_NOTIFICATION@
com.sun.services.debug.mergeall=off
com.iplanet.am.services.deploymentDescriptor=/@SERVER_URI@
com.sun.am.event.connection.disable.list=@DISABLE_PERSISTENT_SEARCH@
</code></pre>
<p><strong>Agent_001/conf/OpenSSOAgentConfiguration.properties</strong> </p>
<pre><code>com.sun.identity.agents.config.filter.mode[manager]=J2EE_POLICY
com.sun.identity.agents.config.filter.mode[host-manager]=J2EE_POLICY
com.sun.identity.agents.config.filter.mode = ALL
com.sun.identity.agents.config.user.mapping.mode = USER_ID
com.sun.identity.agents.config.user.attribute.name = employeenumber
com.sun.identity.agents.config.user.principal = false
com.sun.identity.agents.config.user.token = UserToken
com.sun.identity.agents.config.client.ip.header =
com.sun.identity.agents.config.client.hostname.header =
com.sun.identity.agents.config.load.interval = 0
com.sun.identity.agents.config.locale.language = en
com.sun.identity.agents.config.locale.country = US
com.sun.identity.agents.config.audit.accesstype = LOG_NONE
com.sun.identity.agents.config.log.disposition = REMOTE
com.sun.identity.agents.config.remote.logfile = amAgent_org_sso_com_7070.log
com.sun.identity.agents.config.local.log.rotate = false
com.sun.identity.agents.config.local.log.size = 52428800
com.sun.identity.agents.config.webservice.enable = false
com.sun.identity.agents.config.webservice.endpoint[0] =
com.sun.identity.agents.config.webservice.process.get.enable = true
com.sun.identity.agents.config.webservice.authenticator =
com.sun.identity.agents.config.webservice.internalerror.content = WSInternalErrorContent.txt
com.sun.identity.agents.config.webservice.autherror.content = WSAuthErrorContent.txt
com.sun.identity.agents.config.webservice.responseprocessor =
com.sun.identity.agents.config.access.denied.uri[] =
com.sun.identity.agents.config.login.form[0] = /host-manager/AMLogin.html
com.sun.identity.agents.config.login.form[1] = /manager/AMLogin.html
com.sun.identity.agents.config.login.error.uri[0] = /host-manager/AMError.html
com.sun.identity.agents.config.login.error.uri[1] = /manager/AMError.html
com.sun.identity.agents.config.login.use.internal = true
com.sun.identity.agents.config.login.content.file = FormLoginContent.txt
com.sun.identity.agents.config.auth.handler[] =
com.sun.identity.agents.config.logout.handler[] =
com.sun.identity.agents.config.verification.handler[] =
com.sun.identity.agents.config.httpsession.binding = true
com.sun.identity.agents.config.redirect.param = goto
com.sun.identity.agents.config.login.url[0] = http://test.openam.com:8080/openam/UI/Login
com.sun.identity.agents.config.logout.url[0] = http://test.openam.com:8080/openam/UI/Logout
com.sun.identity.agents.config.login.url.prioritized = true
com.sun.identity.agents.config.login.url.probe.enabled = true
com.sun.identity.agents.config.login.url.probe.timeout = 2000
com.sun.identity.agents.config.logout.url.prioritized = true
com.sun.identity.agents.config.logout.url.probe.enabled = true
com.sun.identity.agents.config.logout.url.probe.timeout = 2000
com.sun.identity.agents.config.agent.host =
com.sun.identity.agents.config.agent.port =
com.sun.identity.agents.config.agent.protocol =
com.sun.identity.agents.config.login.attempt.limit = 0
com.sun.identity.agents.config.amsso.cache.enable = true
com.sun.identity.agents.config.cookie.reset.enable = false
com.sun.identity.agents.config.cookie.reset.name[0] =
com.sun.identity.agents.config.cookie.reset.domain[] =
com.sun.identity.agents.config.cookie.reset.path[] =
com.sun.identity.agents.config.cdsso.enable = false
com.sun.identity.agents.config.cdsso.redirect.uri = /agentapp/sunwCDSSORedirectURI
com.sun.identity.agents.config.cdsso.cdcservlet.url[0] = http://test.openam.com:8080/openam/cdcservlet
com.sun.identity.agents.config.cdsso.clock.skew = 0
com.sun.identity.agents.config.cdsso.trusted.id.provider[0] = http://test.openam.com:8080/openam/cdcservlet
com.sun.identity.agents.config.cdsso.secure.enable = false
com.sun.identity.agents.config.logout.application.handler[] =
com.sun.identity.agents.config.logout.uri[] =
com.sun.identity.agents.config.logout.request.param[] =
com.sun.identity.agents.config.logout.introspect.enabled = false
com.sun.identity.agents.config.logout.entry.uri[] =
com.sun.identity.agents.config.fqdn.check.enable = true
com.sun.identity.agents.config.fqdn.default = org.sso.com
com.sun.identity.agents.config.fqdn.mapping[] =
com.sun.identity.agents.config.legacy.support.enable = false
com.sun.identity.agents.config.legacy.user.agent[0] = Mozilla/4.7*
com.sun.identity.agents.config.legacy.redirect.uri = /agentapp/sunwLegacySupportURI
com.sun.identity.agents.config.response.header[] =
com.sun.identity.agents.config.redirect.attempt.limit = 0
com.sun.identity.agents.config.port.check.enable = false
com.sun.identity.agents.config.port.check.file = PortCheckContent.txt
com.sun.identity.agents.config.port.check.setting[7070] = http
com.sun.identity.agents.config.notenforced.uri[0] =
com.sun.identity.agents.config.notenforced.uri.invert = false
com.sun.identity.agents.config.notenforced.uri.cache.enable = true
com.sun.identity.agents.config.notenforced.uri.cache.size = 1000
com.sun.identity.agents.config.notenforced.refresh.session.idletime = false
com.sun.identity.agents.config.notenforced.ip[0] =
com.sun.identity.agents.config.notenforced.ip.invert = false
com.sun.identity.agents.config.notenforced.ip.cache.enable = true
com.sun.identity.agents.config.notenforced.ip.cache.size = 1000
com.sun.identity.agents.config.attribute.cookie.separator = |
com.sun.identity.agents.config.attribute.date.format = EEE, d MMM yyyy hh:mm:ss z
com.sun.identity.agents.config.attribute.cookie.encode = true
com.sun.identity.agents.config.profile.attribute.fetch.mode = NONE
com.sun.identity.agents.config.profile.attribute.mapping[] =
com.sun.identity.agents.config.session.attribute.fetch.mode = NONE
com.sun.identity.agents.config.session.attribute.mapping[] =
com.sun.identity.agents.config.response.attribute.fetch.mode = NONE
com.sun.identity.agents.config.response.attribute.mapping[] =
com.sun.identity.agents.config.bypass.principal[0] =
com.sun.identity.agents.config.default.privileged.attribute[0] = AUTHENTICATED_USERS
com.sun.identity.agents.config.privileged.attribute.type[0] = Group
com.sun.identity.agents.config.privileged.attribute.type[1] = Role
com.sun.identity.agents.config.privileged.attribute.tolowercase[Group] = false
com.sun.identity.agents.config.privileged.attribute.tolowercase[Role] = false
com.sun.identity.agents.config.privileged.session.attribute[0] =
com.sun.identity.agents.config.privileged.attribute.mapping.enable = true
com.sun.identity.agents.config.privileged.attribute.mapping[] =
com.iplanet.am.cookie.name=iPlanetDirectoryPro
com.iplanet.am.session.client.polling.enable=false
com.iplanet.am.session.client.polling.period=180
com.iplanet.security.encryptor=com.iplanet.services.util.JCEEncryption
com.sun.identity.idm.remote.notification.enabled=true
com.iplanet.am.sdk.remote.pollingTime=1
com.sun.identity.sm.notification.enabled=true
com.sun.identity.sm.cacheTime=1
com.iplanet.am.server.protocol=http
com.iplanet.am.server.host=test.openam.com
com.iplanet.am.server.port=8080
com.sun.identity.agents.notification.enabled=true
com.sun.identity.agents.polling.interval=3
com.sun.identity.policy.client.cacheMode=subtree
com.sun.identity.policy.client.booleanActionValues=iPlanetAMWebAgentService|GET|allow|deny:iPlanetAMWebAgentService|POST|allow|deny
com.sun.identity.policy.client.resourceComparators=serviceType=iPlanetAMWebAgentService|class=com.sun.identity.policy.plugins.HttpURLResourceName|wildcard=*|delimiter=/|caseSensitive=false
com.sun.identity.policy.client.clockSkew=10
com.sun.identity.agents.config.policy.env.get.param[0]=
com.sun.identity.agents.config.policy.env.post.param[0]=
com.sun.identity.agents.config.policy.env.jsession.param[0]=
com.sun.identity.client.notification.url=http://org.sso.com:7070/agentapp/notification
com.iplanet.services.debug.level=error
com.sun.identity.agents.config.ignore.path.info = false
</code></pre>
<p>Please help me to solve this issue.Thanks in advance.</p> | 33,112,800 | 3 | 1 | null | 2015-04-16 13:26:37.343 UTC | 1 | 2017-03-28 18:12:15.697 UTC | 2015-07-24 05:52:15.967 UTC | null | 2,714,702 | null | 1,755,242 | null | 1 | 69 | java|single-sign-on|openam | 8,118 | <p>I've had a similar issue in the past where after the user logs in using the OpenAM login it sits redirecting to itself.</p>
<p>The problem was the cookie domain. When OpenAM authenticates it will set a cookie withe the session token. If tomcat is on a separate domain then it won't be able to look up the cookie. </p>
<p>You might want to check your domain in OpenAM console -> configuration -> system -> platform</p>
<p>My app was Drupal but I think the tomcat config is:</p>
<pre><code><Context sessionCookiePath="/something" sessionCookieDomain=".domain.tld" />
</code></pre> |
25,011,061 | Why can enum implementations not access private fields in the enum class | <p>I just answered this question by saying how to solve the compilation problem:</p>
<p><a href="https://stackoverflow.com/questions/25010763/how-to-use-fields-in-java-enum-by-overriding-the-method">How to use fields in java enum by overriding the method?</a></p>
<p>But what I don't understand is why the error is happening in the first place.</p>
<p>Here is the example written as an enum:</p>
<pre><code>public enum MyEnum {
FIRST {
@Override
public String doIt() {
return "1: " + someField; //error
}
},
SECOND {
@Override
public String doIt() {
return "2: " + super.someField; //no error
}
};
private String someField;
public abstract String doIt();
}
</code></pre>
<p>Here is the exact same thing as abstract classes</p>
<pre><code>abstract class MyClass {
class FIRST extends MyClass {
@Override
public String doIt() {
return "1: " + someField; //no error
}
};
class SECOND extends MyClass {
@Override
public String doIt() {
return "2: " + super.someField; //no error
}
};
private String someField;
public abstract String doIt();
}
</code></pre>
<p>In the case of <code>FIRST</code> within the <code>enum</code> implementation it cannot access <code>someField</code>. However in the abstract class case it can.</p>
<p>Additionally adding <code>super</code> fixes the problem, as does removing the <code>private</code> modifier on the field.</p>
<p>Does anyone know why this slight quirk in the behaviour is happening?</p> | 25,011,208 | 4 | 3 | null | 2014-07-29 08:25:09.47 UTC | 4 | 2017-02-11 03:55:10.713 UTC | 2017-05-23 12:17:00.147 UTC | null | -1 | null | 3,049,628 | null | 1 | 28 | java|enums | 3,739 | <p>Your abstract class is not equivalent to your enum, since enums are implicitly public static final. Thus, you'll observe the same behavior if you use:</p>
<pre class="lang-java prettyprint-override"><code>abstract class MyClass {
static class FIRST extends MyClass {
@Override
public String doIt() {
return "1: " + someField; // error
}
};
static class SECOND extends MyClass {
@Override
public String doIt() {
return "2: " + super.someField; // no error
}
};
private String someField;
public abstract String doIt();
}
</code></pre>
<p>As explained in <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html</a>, chapter "Static Nested Classes":</p>
<blockquote>
<p>A static nested class cannot refer directly to instance variables or
methods defined in its enclosing class: it can use them only through
an object reference.</p>
</blockquote>
<p>Thus the need of <code>super</code>. You could also use <code>this</code> if the field were <code>protected</code> rather than <code>private</code>.</p> |
39,386,458 | How to read data in Python dataframe without concatenating? | <p>I want to read the file f (file size:85GB) in chunks to a dataframe. Following code is suggested.</p>
<pre><code>chunksize = 5
TextFileReader = pd.read_csv(f, chunksize=chunksize)
</code></pre>
<p>However, this code gives me TextFileReader, not dataframe. Also, I don't want to concatenate these chunks to convert TextFileReader to dataframe because of the memory limit. Please advise.</p> | 39,386,767 | 3 | 4 | null | 2016-09-08 08:47:44.147 UTC | 9 | 2021-12-20 07:09:17.163 UTC | 2016-09-08 16:53:38.73 UTC | null | 6,633,975 | null | 6,762,788 | null | 1 | 10 | python|csv|pandas|dataframe|chunks | 24,261 | <p>As you are trying to process 85GB CSV file, if you will try to read all the data by breaking it into chunks and converting it into dataframe then it will hit memory limit for sure. You can try to solve this problem by using different approach. In this case, you can use filtering operations on your data. For example, if there are 600 columns in your dataset and you are interested only in 50 columns. Try to read only 50 columns from the file. This way you will save lot of memory. Process your rows as you read them. If you need to filter the data first, use a generator function. <code>yield</code> makes a function a generator function, which means it won't do any work until you start looping over it.</p>
<p>For more information regarding generator function:
<a href="https://stackoverflow.com/questions/17444679/reading-a-huge-csv-in-python">Reading a huge .csv file</a></p>
<p>For efficient filtering refer: <a href="https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3">https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3</a></p>
<p>For processing smaller dataset:</p>
<p><strong>Approach 1: To convert reader object to dataframe directly:</strong></p>
<pre><code>full_data = pd.concat(TextFileReader, ignore_index=True)
</code></pre>
<p>It is necessary to add parameter <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#ignoring-indexes-on-the-concatenation-axis" rel="nofollow noreferrer">ignore index</a> to function concat, because avoiding duplicity of indexes.</p>
<p><strong>Approach 2:</strong> <strong>Use Iterator or get_chunk to convert it into dataframe.</strong></p>
<p>By specifying a chunksize to read_csv,return value will be an iterable object of type TextFileReader.</p>
<pre><code>df=TextFileReader.get_chunk(3)
for chunk in TextFileReader:
print(chunk)
</code></pre>
<p>Source : <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking</a></p>
<p><code>df= pd.DataFrame(TextFileReader.get_chunk(1))</code></p>
<p>This will convert one chunk to dataframe.</p>
<p><strong>Checking total number of chunks in TextFileReader</strong></p>
<pre class="lang-py prettyprint-override"><code>for chunk_number, chunk in enumerate(TextFileReader):
# some code here, if needed
pass
print("Total number of chunks is", chunk_number+1)
</code></pre>
<p>If file size is bigger,I won't recommend second approach. For example, if csv file consist of 100000 records then chunksize=5 will create 20,000 chunks.</p> |
6,397,716 | Where are my H2 database files? | <p>I'm just evaluating the H2 database... I downloaded and unpacked the installation and connect to a database at <code>jdbc:h2:file:/home/konrad/test</code>. <code>/home/konrad</code> is my home dir, <code>test</code> does not exist (I expect H2 to create it).</p>
<p>The console seems to work OK. I created a table and inserted a row to it. Even if I disconnect and reconnect the console, I can see and query the table.</p>
<p>However, I don't see the file I expected. Where is it?</p> | 6,397,846 | 2 | 0 | null | 2011-06-18 17:35:13.96 UTC | 10 | 2019-12-14 15:53:42.44 UTC | 2011-06-18 17:56:49.347 UTC | null | 605,744 | null | 277,683 | null | 1 | 27 | java|h2 | 39,372 | <p>Are you sure there is no:</p>
<pre><code>/home/konrad/test.h2.db
</code></pre>
<p>file? If not, try this:</p>
<pre><code>$ lsof -p `jps -ml | grep h2 | cut -d' ' -f1` | grep \.h2\.db$
</code></pre>
<p>What it does is it look for Java process of H2 console, grabs its PID and lists all open files of that process, filtering by H2 database extension. Of course you can use PID of any other Java process accessing this DB. If it is persisted on the disk, you can't miss it.</p> |
6,846,898 | Determine operating system in .vimrc | <p>I develop on Linux at home and on Windows at work. I'd like to use the same vimrc file in both environments. The problem I have with this is that on Windows, I want to have the editor use the Consolas font, and on linux, a different font. How can I check the environment so I can conditionally set the editor font? (I am familiar with the actual command to change font; it's the conditional I don't get)</p> | 6,846,949 | 2 | 1 | null | 2011-07-27 15:23:03.767 UTC | 7 | 2011-07-27 15:29:21.63 UTC | null | null | null | null | 566,179 | null | 1 | 43 | vim | 7,639 | <p>Exception from my .vimrc</p>
<pre><code>" adjust configuration for such hostile environment as Windows {{{
if has("win32") || has("win16")
lang C
set viminfo='20,\"512,nc:/tmp/_viminfo
set iskeyword=48-57,65-90,97-122,_,161,163,166,172,177,179,182,188,191,198,202,209,211,230,234,241,243,143,156,159,165,175,185
else
set shell=/bin/sh
endif
" }}}
</code></pre> |
7,501,494 | What is JAXB generated package-info.java | <p>I'm trying to find some information on what the <code>package-info.java</code> file generated by the JAXB <strong>xjc</strong> commandline app actually does. All that is in the file is</p>
<pre><code>@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package the.generated.package.path;
</code></pre>
<p>What is this <code>package-info.java</code> file used for?</p> | 7,501,568 | 3 | 1 | null | 2011-09-21 14:25:30.003 UTC | 9 | 2016-08-15 04:32:35.14 UTC | null | null | null | null | 561,624 | null | 1 | 28 | java|jaxb|xjc | 34,960 | <p>package-info.java is a way to apply java annotations at the package level. In this case Jaxb is using package-level annotations to indicate the namespace, and to specify namespace qualification for attributes <a href="https://jaxb.java.net/nonav/jaxb20-fcs/docs/api/javax/xml/bind/annotation/XmlSchema.html" rel="noreferrer">(source)</a>.</p> |
7,662,471 | Ruby unless && statement | <p>I have the following in my application_controller.rb</p>
<pre><code>def layout
unless request.subdomain.empty? && current_user.nil?
self.class.layout 'admin'
end
end
</code></pre>
<p>It seems the code above it's not working. But when I do the following, it does work.</p>
<pre><code>def layout
unless request.subdomain.empty?
unless current_user.nil?
self.class.layout 'admin'
end
end
end
</code></pre>
<p>I would like to simplify the code by removing one unless statement. How could I do that?</p> | 7,662,517 | 3 | 0 | null | 2011-10-05 13:58:02.09 UTC | 12 | 2011-10-05 14:09:38.973 UTC | null | null | null | null | 912,895 | null | 1 | 28 | ruby-on-rails|ruby | 15,828 | <p><code>unless something</code> is equivalent to <code>if !something</code>. In your case, that would be </p>
<pre><code>if !(request.subdomain.empty? && current_user.nil?)
</code></pre>
<p>However, you want</p>
<pre><code>if (!request.subdomain.empty? && !current_user.nil?)
</code></pre>
<p>Using boolean algebra (De Morgan rule), you can rewrite that to</p>
<pre><code>if !(request.subdomain.empty? || current_user.nil?)
</code></pre>
<p>Using <code>unless</code></p>
<pre><code>unless request.subdomain.empty? || current_user.nil?
</code></pre> |
7,685,246 | Should I store git repository in Home or Eclipse Workspace? | <p>I'm just moving from svn to git, and am keen to lay some good foundations.</p>
<p>By default Eclipse wants to store my local clone repository in ~/git. I'm more comfortable keeping all data for a task in the same workspace - so I'm inclined to keep it in my workspace.</p>
<p>Are there any significant pros/cons I should consider?</p>
<p>I don't intend doing a lot of branching - I'm really going down the dvcs route mostly to overcome some unreliable internet comms issues.</p> | 7,694,318 | 3 | 2 | null | 2011-10-07 09:18:35.443 UTC | 25 | 2014-12-17 12:07:03.693 UTC | 2013-08-05 10:46:59.34 UTC | null | 1,584,286 | null | 92,441 | null | 1 | 46 | java|eclipse|git | 26,860 | <p>I'm too switching to Git in Eclipse, and reading about this issue. It seems that <a href="http://wiki.eclipse.org/EGit/User_Guide#Considerations_for_Git_Repositories_to_be_used_in_Eclipse">current wisdom</a> (though not everyone agrees) is:</p>
<ul>
<li><p>Get used to NOT having your projects below the workspace directory.</p></li>
<li><p>Have one git repository for each group of related eclipse projects (and perhaps more files, of course). The concept of "related projects" is up to your convenience [*]</p></li>
<li><p>For each repository, one first level directory for each Java project. This implies that you'll have a <code>.git/</code> directory, and, at the same level, the project directories.</p></li>
</ul>
<p>Example: suppose that, "before GIT", you had one eclipse workspace with several projects:</p>
<pre><code>/wk/workspace/.metadata/
/wk/workspace/projXXX/
/wk/workspace/projXXXtest/ (related with the previous)
/wk/workspace/projYYY1/ |
/wk/workspace/projYYY2/ > three related projects
/wk/workspace/projYYY3/ |
/wk/workspace/projZ/ (a project you are not going to version in git)
</code></pre>
<p>Then you'll create two empty directories, one for each repository, say:</p>
<pre><code>~/repositories/XXX/
~/repositories/YYY/
</code></pre>
<p>and afterwards, with the new GIT layout, you'll have:</p>
<pre><code>/wk/workspace/.metadata/
/wk/workspace/projZ/
~/repositories/XXX/.git/ (XXX related repository - non-bare)
~/repositories/XXX/projXXX/
~/repositories/XXX/projXXXtest/
~/repositories/YYY/.git/ (YYY related repository - non-bare)
~/repositories/YYY/projYYY1/
~/repositories/YYY/projYYY2/
~/repositories/YYY/projYYY3/
</code></pre>
<p>Eclipse (EGit) does all this for you when you click <em>Team->Share</em> over an existing project and specify (in the example) <code>~/repositories/XXX/.git/</code> as repository, (<code>~/repositories/XXX/</code> as <em>"Working directory"</em>, leave <em>"Path within repository"</em> blank).</p>
<p>[*] Bear in mind that here each group of projects is, from the Git point-of-view, just a set of directories inside a repository. Some relevant implications: in the above example, you'll never have in the Eclipse workspace two different branches/versions of projects <code>projYYY1</code> -<code>projYYY2</code> simultaneously; and, say, when you tag a project commit, you are actually tagging the full repository (group of projects) commit.</p> |
1,383,999 | DDD Infrastructure services | <p>I am learning DDD and I am a little bit lost in the Infrastructure layer.</p>
<p>As I understand, "all good DDD applications" should have 4 layers: Presentation, Application, Domain, and Infrastructure. The database should be accessed using Repositories. Repository interfaces should be in Domain layer and repository implementation - in Infrastructure (reference <a href="https://stackoverflow.com/questions/693221/ddd-where-to-keep-domain-interfaces-the-infrastructure">DDD: Where to keep domain Interfaces, the Infrastructure?</a>).</p>
<p>Application, Domain, and Infrastructure layer should/may have services (reference <a href="https://lostechies.com/jimmybogard/2008/08/21/services-in-domain-driven-design/" rel="noreferrer">Services in Domain-Driven Design</a>), for example, EmailService in Infrastructure layer which sends e-mail messages.</p>
<p>BUT, inside the Infrastructure layer, we have repository implementations, which are used to access the database. So, in this case, repositories are database services? What is the difference between Infrastructure service and repository?</p>
<p>Thanks in advance!</p> | 1,385,912 | 4 | 0 | null | 2009-09-05 18:42:39.607 UTC | 23 | 2021-03-15 13:46:43.68 UTC | 2021-03-15 13:46:43.68 UTC | null | 4,981,637 | null | 106,715 | null | 1 | 31 | c#|asp.net-mvc|domain-driven-design | 25,666 | <p>Sticking with DDD definitions, a Repository is different than a Service. A Repository directly correlates to an Entity, often an Aggregate Root. A Service defines behaviors that don't really belong to a single Entity in your domain. You can absolutely find Services in every layer, though the types of problems they address differ from layer to layer and may be different from DDD's conceptual Service.</p>
<p>When working at the conceptual level, a DDD Repository differs from a DDD service in that it is specifically tied to Entity persistence. A Service can address any Domain, Application, or Infrastructure problem you may have.</p>
<p>You run into terminology clashes with DDD all over the place. For instance, a DDD Repository is NOT the same thing as the <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">Repository pattern</a> found in Martin Fowler's PoEAA book, though it may employ such a pattern. This is often a source of confusion for many people.</p>
<p>It helps with DDD if you always keep the Domain Model at the very center of everything you do. When it comes to layering DDD apps, I often choose <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/" rel="noreferrer">Jeffrey Palermo's Onion Architecture</a>. Check it out. Download <a href="http://codecampserver.codeplex.com/" rel="noreferrer">CodeCampServer</a>, an example app using this architecture. I think it's a perfect fit for DDD programming.</p>
<p>Good luck!</p> |
42,764,166 | VS 2017 - Very slow (laggy) when debugging | <p>When I debug my solution, vs 2017 is very laggy and slow it's like it has to operate something heavy in the background.</p>
<p>So it stops "responding" every 5 seconds for 2 seconds, which is very annoying.
Any suggestions?</p>
<p>EDIT (tried suggestions):</p>
<ul>
<li>Browser Link is turned off</li>
<li>Stopped customer feedback</li>
</ul> | 42,767,603 | 16 | 8 | null | 2017-03-13 12:54:07.067 UTC | 14 | 2020-09-04 14:04:04.43 UTC | 2017-03-13 13:28:15.433 UTC | null | 3,416,443 | null | 3,416,443 | null | 1 | 82 | visual-studio|visual-studio-2017 | 47,045 | <p>After some additional investigation I found this <a href="https://developercommunity.visualstudio.com/content/problem/26064/slow-debug-in-vs-2017.html" rel="noreferrer">thread</a>
Unchecking <strong>Enable Diagnostic Tools while debugging</strong> in Tools → Options → Debugging → General did the trick!</p>
<p>Unchecking <b>Enable JavaScript debugging for ASP.NET </b> in<br>
Tools → Options → Debugging → General<br>
makes a huge difference in performance.</p> |
49,370,747 | Network error with axios and react native | <p>I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (<code>mydomain.com/endpoint/</code>) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (<code>localhost:8000/endpoint/</code>). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:</p>
<pre><code>Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)
</code></pre>
<p>This is my axios call in my react native component:</p>
<pre><code> componentDidMount() {
axios.get('mydomain.com/get/').then(response => { // localhost:8000/get works
this.setState({foo:response.data});
}).catch(error => {
console.log(error);
});
}
</code></pre> | 49,374,981 | 9 | 7 | null | 2018-03-19 19:18:17.79 UTC | 6 | 2022-05-26 14:56:11.59 UTC | null | null | null | null | 1,447,867 | null | 1 | 26 | react-native|axios | 102,508 | <p>It seems that unencrypted network requests are blocked by default in iOS, i.e. <code>https</code> will work, <code>http</code> will not.</p>
<p><a href="https://facebook.github.io/react-native/docs/network.html" rel="noreferrer">From the docs</a>:</p>
<blockquote>
<p>By default, iOS will block any request that's not encrypted using SSL.
If you need to fetch from a cleartext URL (one that begins with http)
you will first need to add an App Transport Security exception.</p>
</blockquote> |
10,652,000 | psexec not recognized | <p>I am working on a Microsoft Server 2008 machine. For some reason, the command "psexec" is not working from powershell on this 1 machine.</p>
<p>When I try to run it I get this:</p>
<pre><code>PS C:\> psexec
The term 'psexec' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:7
+ psexec <<<<
+ CategoryInfo : ObjectNotFound: (psexec:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS C:\>
</code></pre>
<p>It is running powershell 2.0. I found this out by doing:</p>
<pre><code>PS C:\> $Host.Version
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
PS C:\>
</code></pre>
<p>Any thoughts? I need this command and I'd really prefer not to use a "work around".</p> | 10,669,990 | 1 | 2 | null | 2012-05-18 11:42:37.587 UTC | null | 2012-05-20 01:01:13.67 UTC | null | null | null | null | 952,342 | null | 1 | 5 | powershell|psexec | 50,819 | <p>Completing the Answer: </p>
<p>You must need to download PSEXEC from the link below and keep in path the launch from Powershell or any Command prompt:
<a href="http://technet.microsoft.com/en-us/sysinternals/bb897553" rel="noreferrer">http://technet.microsoft.com/en-us/sysinternals/bb897553</a></p> |
28,836,893 | How to send requests with JSON in unit tests | <p>I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so:</p>
<pre><code>Request = request.get_json()
</code></pre>
<p>This has been working fine, however I am trying to create unit tests using Python's unittest module and I'm having difficulty finding a way to send a JSON with the request.</p>
<pre><code>response=self.app.post('/test_function',
data=json.dumps(dict(foo = 'bar')))
</code></pre>
<p>This gives me:</p>
<pre><code>>>> request.get_data()
'{"foo": "bar"}'
>>> request.get_json()
None
</code></pre>
<p>Flask seems to have a JSON argument where you can set json=dict(foo='bar') within the post request, but I don't know how to do that with the unittest module.</p> | 28,840,457 | 2 | 3 | null | 2015-03-03 16:29:51.583 UTC | 11 | 2021-06-09 22:00:57.277 UTC | 2021-06-09 22:00:57.277 UTC | null | 6,083,378 | null | 4,260,951 | null | 1 | 113 | python|json|flask|python-unittest | 48,864 | <p>Changing the post to</p>
<pre><code>response=self.app.post('/test_function',
data=json.dumps(dict(foo='bar')),
content_type='application/json')
</code></pre>
<p>fixed it.</p>
<p>Thanks to user3012759.</p> |
49,033,016 | plm or lme4 for Random and Fixed Effects model on Panel Data | <p>Can I specify a Random and a Fixed Effects model on Panel Data using <a href="/questions/tagged/lme4" class="post-tag" title="show questions tagged 'lme4'" rel="tag">lme4</a>? </p>
<p>I am redoing Example 14.4 from Wooldridge (2013, p. 494-5) in <a href="/questions/tagged/r" class="post-tag" title="show questions tagged 'r'" rel="tag">r</a>. Thanks to <a href="http://www.urfie.net/downloads14.html" rel="noreferrer">this site</a> and <a href="https://econometricswithr.wordpress.com/wooldridge-2013/chapter-14/" rel="noreferrer">this blog post</a> I've manged to do it in the <a href="/questions/tagged/plm" class="post-tag" title="show questions tagged 'plm'" rel="tag">plm</a> package, but I'm curious if I can do the same in the <a href="/questions/tagged/lme4" class="post-tag" title="show questions tagged 'lme4'" rel="tag">lme4</a> package?</p>
<p>Here's what I've done in the <a href="/questions/tagged/plm" class="post-tag" title="show questions tagged 'plm'" rel="tag">plm</a> package. Would be grateful for any pointers as to how I can do the same using <a href="/questions/tagged/lme4" class="post-tag" title="show questions tagged 'lme4'" rel="tag">lme4</a>. First, packages needed and loading of data,</p>
<pre><code># install.packages(c("wooldridge", "plm", "stargazer"), dependencies = TRUE)
library(wooldridge)
data(wagepan)
</code></pre>
<p>Second, I estimate the three models estimated in Example 14.4 (Wooldridge 2013) using the <a href="/questions/tagged/plm" class="post-tag" title="show questions tagged 'plm'" rel="tag">plm</a> package,</p>
<pre><code>library(plm)
Pooled.ols <- plm(lwage ~ educ + black + hisp + exper+I(exper^2)+ married + union +
factor(year), data = wagepan, index=c("nr","year") , model="pooling")
random.effects <- plm(lwage ~ educ + black + hisp + exper + I(exper^2) + married + union +
factor(year), data = wagepan, index = c("nr","year") , model = "random")
fixed.effects <- plm(lwage ~ I(exper^2) + married + union + factor(year),
data = wagepan, index = c("nr","year"), model="within")
</code></pre>
<p>Third, I output the resultants using <a href="/questions/tagged/stargazer" class="post-tag" title="show questions tagged 'stargazer'" rel="tag">stargazer</a> to emulate Table 14.2 in Wooldridge (2013),</p>
<pre><code>stargazer::stargazer(Pooled.ols,random.effects,fixed.effects, type="text",
column.labels=c("OLS (pooled)","Random Effects","Fixed Effects"),
dep.var.labels = c("log(wage)"), keep.stat=c("n"),
keep=c("edu","bla","his","exp","marr","union"), align = TRUE, digits = 4)
#> ======================================================
#> Dependent variable:
#> -----------------------------------------
#> log(wage)
#> OLS (pooled) Random Effects Fixed Effects
#> (1) (2) (3)
#> ------------------------------------------------------
#> educ 0.0913*** 0.0919***
#> (0.0052) (0.0107)
#>
#> black -0.1392*** -0.1394***
#> (0.0236) (0.0477)
#>
#> hisp 0.0160 0.0217
#> (0.0208) (0.0426)
#>
#> exper 0.0672*** 0.1058***
#> (0.0137) (0.0154)
#>
#> I(exper2) -0.0024*** -0.0047*** -0.0052***
#> (0.0008) (0.0007) (0.0007)
#>
#> married 0.1083*** 0.0640*** 0.0467**
#> (0.0157) (0.0168) (0.0183)
#>
#> union 0.1825*** 0.1061*** 0.0800***
#> (0.0172) (0.0179) (0.0193)
#>
#> ------------------------------------------------------
#> Observations 4,360 4,360 4,360
#> ======================================================
#> Note: *p<0.1; **p<0.05; ***p<0.01
</code></pre>
<p>is there an equally simple way to do this in <a href="/questions/tagged/lme4" class="post-tag" title="show questions tagged 'lme4'" rel="tag">lme4</a>? Should I stick to <a href="/questions/tagged/plm" class="post-tag" title="show questions tagged 'plm'" rel="tag">plm</a>? Why/Why not?</p> | 49,168,979 | 1 | 4 | null | 2018-02-28 15:24:49.413 UTC | 11 | 2018-03-12 12:24:39.84 UTC | 2018-03-12 12:24:39.84 UTC | null | 1,305,688 | null | 1,305,688 | null | 1 | 13 | r|lme4|panel-data|plm | 6,605 | <p>
Excepted for the difference in estimation method it seems indeed to be mainly a question
of vocabulary and syntax</p>
<pre class="lang-r prettyprint-override"><code># install.packages(c("wooldridge", "plm", "stargazer", "lme4"), dependencies = TRUE)
library(wooldridge)
library(plm)
#> Le chargement a nécessité le package : Formula
library(lme4)
#> Le chargement a nécessité le package : Matrix
data(wagepan)
</code></pre>
<p>Your first example is a simple linear model ignoring the groups <code>nr</code>.<br>
You can't do that with lme4 because there is no "random effect" (in the <code>lme4</code> sense).<br>
This is what Gelman & Hill call a complete pooling approach.</p>
<pre class="lang-r prettyprint-override"><code>Pooled.ols <- plm(lwage ~ educ + black + hisp + exper+I(exper^2)+ married +
union + factor(year), data = wagepan,
index=c("nr","year"), model="pooling")
Pooled.ols.lm <- lm(lwage ~ educ + black + hisp + exper+I(exper^2)+ married + union +
factor(year), data = wagepan)
</code></pre>
<p>Your second example seems to be equivalent to a random intercept mixed model with <code>nr</code>
as random effect (but the slopes of all predictors are fixed).<br>
This is what Gelman & Hill call a partial pooling approach.</p>
<pre class="lang-r prettyprint-override"><code>random.effects <- plm(lwage ~ educ + black + hisp + exper + I(exper^2) + married +
union + factor(year), data = wagepan,
index = c("nr","year") , model = "random")
random.effects.lme4 <- lmer(lwage ~ educ + black + hisp + exper + I(exper^2) + married +
union + factor(year) + (1|nr), data = wagepan)
</code></pre>
<p>Your third example seems to correspond to a case were <code>nr</code> is a fixed effect and you
compute a different <code>nr</code> intercept for each group.<br>
Again : you can't do that with <code>lme4</code> because there is no "random effect" (in the <code>lme4</code> sense).<br>
This is what Gelman & Hill call a "no pooling" approach.</p>
<pre class="lang-r prettyprint-override"><code>fixed.effects <- plm(lwage ~ I(exper^2) + married + union + factor(year),
data = wagepan, index = c("nr","year"), model="within")
wagepan$nr <- factor(wagepan$nr)
fixed.effects.lm <- lm(lwage ~ I(exper^2) + married + union + factor(year) + nr,
data = wagepan)
</code></pre>
<p>Compare the results :</p>
<pre class="lang-r prettyprint-override"><code>stargazer::stargazer(Pooled.ols, Pooled.ols.lm,
random.effects, random.effects.lme4 ,
fixed.effects, fixed.effects.lm,
type="text",
column.labels=c("OLS (pooled)", "lm no pool.",
"Random Effects", "lme4 partial pool.",
"Fixed Effects", "lm compl. pool."),
dep.var.labels = c("log(wage)"),
keep.stat=c("n"),
keep=c("edu","bla","his","exp","marr","union"),
align = TRUE, digits = 4)
#>
#> =====================================================================================================
#> Dependent variable:
#> ----------------------------------------------------------------------------------------
#> log(wage)
#> panel OLS panel linear panel OLS
#> linear linear mixed-effects linear
#> OLS (pooled) lm no pool. Random Effects lme4 partial pool. Fixed Effects lm compl. pool.
#> (1) (2) (3) (4) (5) (6)
#> -----------------------------------------------------------------------------------------------------
#> educ 0.0913*** 0.0913*** 0.0919*** 0.0919***
#> (0.0052) (0.0052) (0.0107) (0.0108)
#>
#> black -0.1392*** -0.1392*** -0.1394*** -0.1394***
#> (0.0236) (0.0236) (0.0477) (0.0485)
#>
#> hisp 0.0160 0.0160 0.0217 0.0218
#> (0.0208) (0.0208) (0.0426) (0.0433)
#>
#> exper 0.0672*** 0.0672*** 0.1058*** 0.1060***
#> (0.0137) (0.0137) (0.0154) (0.0155)
#>
#> I(exper2) -0.0024*** -0.0024*** -0.0047*** -0.0047*** -0.0052*** -0.0052***
#> (0.0008) (0.0008) (0.0007) (0.0007) (0.0007) (0.0007)
#>
#> married 0.1083*** 0.1083*** 0.0640*** 0.0635*** 0.0467** 0.0467**
#> (0.0157) (0.0157) (0.0168) (0.0168) (0.0183) (0.0183)
#>
#> union 0.1825*** 0.1825*** 0.1061*** 0.1053*** 0.0800*** 0.0800***
#> (0.0172) (0.0172) (0.0179) (0.0179) (0.0193) (0.0193)
#>
#> -----------------------------------------------------------------------------------------------------
#> Observations 4,360 4,360 4,360 4,360 4,360 4,360
#> =====================================================================================================
#> Note: *p<0.1; **p<0.05; ***p<0.01
</code></pre>
<p>Gelman A, Hill J (2007) Data analysis using regression and multilevel/hierarchical models. Cambridge University Press
(a very very good book !)</p>
<p>Created on 2018-03-08 by the <a href="http://reprex.tidyverse.org" rel="noreferrer">reprex package</a> (v0.2.0).</p> |
7,051,735 | How do I put a hyperlink to "two levels above in the directory tree"? | <p>I am trying to code my Home button. Is there a way to just climb back up the file structure, instead of using the absolute path like I have below.</p>
<p>I have a file index.html that I have at <code>C:\Users\Randy\Documents\XML\</code></p>
<p>Heres my code:</p>
<pre><code><a id="my-family" href="C:\Users\Randy\Documents\XML\index.html">Home</a>
</code></pre>
<p>Heres where I am trying to come from: <code>C:\Users\Randy\Documents\XML\project\xml</code></p> | 7,051,775 | 6 | 0 | null | 2011-08-13 16:23:43.107 UTC | 6 | 2021-03-10 12:08:57.887 UTC | 2011-08-13 19:50:43.463 UTC | null | 600,500 | null | 770,022 | null | 1 | 17 | html|hyperlink|relative-path | 72,431 | <p>You can use <code>../index.html</code> to refer to <code>index.html</code> in the parent directory.</p> |
7,223,717 | Differentiating +0 and -0 | <p>It turns out <code>+0 === -0</code> evaluates to <code>true</code> despite <code>+0</code> and <code>-0</code> being <em>different</em> entities. So, how do you differentiate <code>+0</code> from <code>-0</code>?</p>
<p>There is a hack:</p>
<pre><code>if (1 / myZero > 0) {
// myZero is +0
} else {
// myZero is -0
}
</code></pre>
<p>Can I do better?</p> | 13,539,727 | 9 | 6 | null | 2011-08-28 20:31:55.543 UTC | 11 | 2021-10-22 07:34:44.777 UTC | 2012-11-09 14:16:14.197 UTC | null | 707,381 | null | 707,381 | null | 1 | 42 | javascript | 3,838 | <p>In ECMAScript 6 <code>Object.is</code> behaves like <code>===</code> except that it distinguishes positive and negative zeroes, and <code>Object.is(NaN, NaN)</code> evaluates to <code>true</code>. (See <a href="http://addyosmani.com/blog/a-few-new-things-coming-to-javascript/" rel="noreferrer">here</a> for a writeup.)</p>
<p>Chrome 24 supports <code>Object.is</code>.</p> |
7,161,821 | How to 'grep' a continuous stream? | <p>Is that possible to use <code>grep</code> on a continuous stream?</p>
<p>What I mean is sort of a <code>tail -f <file></code> command, but with <code>grep</code> on the output in order to keep only the lines that interest me.</p>
<p>I've tried <code>tail -f <file> | grep pattern</code> but it seems that <code>grep</code> can only be executed once <code>tail</code> finishes, that is to say never.</p> | 7,162,898 | 13 | 9 | null | 2011-08-23 13:34:31.173 UTC | 244 | 2021-12-30 07:17:09.93 UTC | 2015-03-13 11:00:29.587 UTC | null | 273,344 | null | 245,552 | null | 1 | 837 | linux|bash|shell|grep|tail | 406,292 | <p>Turn on <code>grep</code>'s line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)</p>
<pre><code>tail -f file | grep --line-buffered my_pattern
</code></pre>
<p>It looks like a while ago <code>--line-buffered</code> didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, <code>--line-buffered</code> is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).</p> |
7,438,059 | Fatal error: Call to undefined function pg_connect() | <p>I am trying to connect to my database (remote server) which has PostgreSQL installed in it. My PHP code is trying to connect to the database using pg_connect(), but I get the error saying:- "Fatal error: Call to undefined function pg_connect() in /var/www/website/functions.php on line 82".</p>
<p>The line 82 simply is:</p>
<pre><code>$db = pg_connect($conn_string);
where $conn_string = "host=".$hostname." port=5432 dbname=".$dbname." user=".$db_user." password=".$db_password.""
</code></pre>
<p>(all variables defined earlier)</p>
<p>I checked many forums and the only solution suggested was locating the php.ini file which contains a line:- extension = pgsql.so (for UNIX) and extension = php_pgsql.dll (for Windows). </p>
<p>This statement is supposed to be commented and the solution is to uncomment it. I have tried it but still does not change the situation. The remote server has a version later than PostgreSQL v9.0.4 installed.
I then installed PostgreSQL v8.4.8 on to my laptop and ran the website locally using MAMP. At first, Apache crashed for some odd reason, I fixed that problem but again I ended up with the same error as before i.e. Fatal error: Call to undefined function pg_connect()....</p>
<p>I also ran the <code>phpinfo()</code> and it showed that the php version does support the PostgreSQL module.I have spent an entire day searching for the solution but have been unsuccessful. This is my first project developing a website and I am out of wits. Any kinda help will be highly appreciated.</p>
<p>phpinfo() gives me a huge list of things at the terminal but the listings relevant to PostgreSQL are as follows:-</p>
<pre><code>pdo_pgsql
PDO Driver for PostgreSQL => enabled
PostgreSQL(libpq) Version => 9.0.4
Module version => 1.0.2
Revision => $Id: pdo_pgsql.c 306939 2011-01-01 02:19:59Z felipe $
pgsql
PostgreSQL Support => enabled
PostgreSQL(libpq) Version => 9.0.4
Multibyte character support => enabled
SSL support => enabled
Active Persistent Links => 0
Active Links => 0
Directive => Local Value => Master Value
pgsql.allow_persistent => On => On
pgsql.auto_reset_persistent => Off => Off
pgsql.ignore_notice => Off => Off
pgsql.log_notice => Off => Off
pgsql.max_links => Unlimited => Unlimited
pgsql.max_persistent => Unlimited => Unlimited
</code></pre>
<p>I had restarted MAMP after every edit I made since it was mentioned in every post I have read so far. I believe that resets both Apache and php.</p>
<p>'pqsql.so' (which is the UNIX equivalent of 'php_pqsql.dll' in Windows) is present in the 'extension' directory. I also copy-pasted the 'pqsql.so' file on to the Apache/bin directory but it did not give me any change.</p>
<p>I am not running php in the command line primarily. I just was curious to see what phpinfo() would give me relevant to pgsql which I have mentioned in my reply above.</p>
<p>I am still working on the tools you have mentioned and will respond as soon as I get any results.</p>
<p>Thanks,
H</p> | 7,460,079 | 17 | 2 | null | 2011-09-15 22:15:59.567 UTC | 9 | 2021-04-05 05:50:10.773 UTC | 2011-09-16 13:33:35.99 UTC | null | 947,778 | null | 947,778 | null | 1 | 41 | php|apache|postgresql | 236,653 | <p>You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.</p>
<p>On Ubuntu and Debian:</p>
<pre><code>sudo apt-get install php5-pgsql
</code></pre> |
9,444,992 | TypeError: __init__() takes exactly 3 arguments (2 given) | <p>I've seen a few of the answers on here regarding my error but its not helped me. I am an absolute noob at classes on python and just started doing this code back in September. Anyway have a look at my code</p>
<pre><code>class SimpleCounter():
def __init__(self, startValue, firstValue):
firstValue = startValue
self.count = startValue
def click(self):
self.count += 1
def getCount(self):
return self.count
def __str__(self):
return 'The count is %d ' % (self.count)
def reset(self):
self.count += firstValue
a = SimpleCounter(5)
</code></pre>
<p>and this is the error I get</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Bilal\Downloads\simplecounter.py", line 26, in <module>
a = SimpleCounter(5)
TypeError: __init__() takes exactly 3 arguments (2 given
</code></pre> | 9,445,059 | 2 | 1 | null | 2012-02-25 14:48:20.377 UTC | 2 | 2012-02-25 14:55:56.427 UTC | 2012-02-25 14:52:27.507 UTC | null | 577,088 | null | 1,232,626 | null | 1 | 5 | python|class|arguments | 40,067 | <p>Your <code>__init__()</code> definition requires <em>both</em> a <code>startValue</code> <em>and</em> a <code>firstValue</code>. So you'd have to pass both (i.e. <code>a = SimpleCounter(5, 5)</code>) to make this code work. </p>
<p>However, I get the impression that there's some deeper confusion at work here: </p>
<pre><code>class SimpleCounter():
def __init__(self, startValue, firstValue):
firstValue = startValue
self.count = startValue
</code></pre>
<p>Why do you store <code>startValue</code> to <code>firstValue</code> and then throw it away? It seems to me that you mistakenly think that the parameters to <code>__init__</code> automatically become attributes of the class. That's not so. You have to assign them explicitly. And since both values are equal to <code>startValue</code>, you don't need to pass it to the constructor. You can just assign it to <code>self.firstValue</code> like so:</p>
<pre><code>class SimpleCounter():
def __init__(self, startValue):
self.firstValue = startValue
self.count = startValue
</code></pre> |
9,411,557 | SQLite database scheme as Entity Relationship Model | <p>Is there a tool to display the database scheme for SQLite 3 database like with MySQL Workbench and Reverse Engineering? I mean a graphical representation like <img src="https://i.stack.imgur.com/Usrhr.png" alt="Database scheme"></p> | 9,411,709 | 1 | 1 | null | 2012-02-23 10:51:20.05 UTC | 4 | 2014-01-07 12:44:17.973 UTC | 2012-02-23 11:53:45.9 UTC | null | 128,595 | null | 426,227 | null | 1 | 34 | database|sqlite|entity-relationship | 37,001 | <p>Try <a href="http://www.dbvis.com/" rel="noreferrer">DbVisualizer</a>, it works for any database and I particularly like the way it arranges large diagrams. Check the Personal evaluation license.</p> |
52,376,855 | ASPNETCORE_ENVIRONMENT in Docker | <p>i have problems setting the <strong>ASPNETCORE_ENVIRONMENT</strong> variable running my project in a <strong>docker container</strong>. The problem is that the value is always <strong>set/overwritten to "Development"</strong>.</p>
<p>I have tried setting the environment variable in my <strong>Dockerfile</strong> using </p>
<pre><code>ENV ASPNETCORE_ENVIRONMENT test
</code></pre>
<p>also tried setting the environment variable in my <strong>docker-compose</strong> file using </p>
<pre><code>environment:
- ASPNETCORE_ENVIRONMENT=test
</code></pre>
<p>When I set any other environment variable <strong>it works</strong>, for example:</p>
<pre><code>environment:
- OTHER_TEST_VARIABLE=test
</code></pre>
<p>I assume that the value for <strong>ASPNETCORE_ENVIRONMENT</strong> variable is overwritten somewhere but I have difficulties finding out where.</p>
<p>I have added Docker support to an existing project and am running the project directly via Visual Studio's Docker/Docker compose option </p>
<p>The project runs on Asp Net Core 2.1</p>
<p>Thanks in advance</p>
<p>My launchSettings.json:</p>
<pre><code>{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:53183/",
"sslPort": 0
}
},
"profiles": {
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://localhost:{ServicePort}/api/values"
}
}
}
</code></pre>
<p>I also tried adding the environment variable configuration to the launchSettings.json</p>
<pre><code>"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://localhost:{ServicePort}/api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "test"
}
}
</code></pre>
<p>My Webhost:</p>
<pre><code> public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((builderContext,config) =>
{
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
}
</code></pre>
<p>My docker-compose.yml</p>
<pre><code>version: '3.4'
services:
api:
image: ${DOCKER_REGISTRY}api
build:
context: .
dockerfile: API/Dockerfile
environment:
- ASPNETCORE_ENVIRONMENT=test
</code></pre>
<p>My Dockerfile:</p>
<pre><code>FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY API/API.csproj API/
RUN dotnet restore API/API.csproj
COPY . .
WORKDIR /src/API
RUN dotnet build API.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish API.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "API.dll"]
</code></pre>
<p>Here is a list of the environment variables in the container</p>
<pre><code>C:\Users\Administrator>docker exec -ti d6 /bin/bash
root@d6f26d2ed2c3:/app# printenv
HOSTNAME=d6f26d2ed2c3
ASPNETCORE_URLS=http://+:80
test1=asdasd
test2=dasdasd
test3=dasdasd
PWD=/app
HOME=/root
NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages
DOTNET_USE_POLLING_FILE_WATCHER=1
ASPNETCORE_VERSION=2.1.3
DOTNET_RUNNING_IN_CONTAINER=true
TERM=xterm
SHLVL=1
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ASPNETCORE_ENVIRONMENT=Development
_=/usr/bin/printenv
root@d6f26d2ed2c3:/app#
</code></pre> | 52,383,707 | 8 | 3 | null | 2018-09-17 23:18:04.77 UTC | 2 | 2022-03-15 23:45:35.733 UTC | null | null | null | null | 10,376,568 | null | 1 | 46 | asp.net|docker|asp.net-core|.net-core|docker-compose | 37,078 | <p>It works for me by configuring <code>ASPNETCORE_ENVIRONMENT</code> with command <code>dotnet CoreDocker.dll --environment="X"</code> </p>
<p>Try to change <code>dockerfile</code> like below: </p>
<p><code>ENTRYPOINT ["dotnet", "CoreDocker.dll", "--environment=X"]
</code></p> |
44,967,759 | What are the pros and cons of Dash by Plotly vs Jupyter Dashboards? | <p><a href="https://github.com/plotly/dash" rel="noreferrer">Dash by Plotly</a> looks like a great way for a Python developer to create interactive web apps without having to learn Javascript and Front End Web development. Another great project with similar aims and scope is <a href="https://github.com/jupyter/dashboards" rel="noreferrer">Jupyter Dashboards</a>.</p>
<p>What are the pros and cons of each?</p>
<p>In particular in a multi-user deployment? I also found the Plotly documentation quite unclear on what exactly is Open Source and whether the data gets uploaded to them or if the plotting can be done offline? There are clearly two modes for the underlying Plotly library but what mode does Dash operate in?</p> | 45,015,594 | 2 | 1 | null | 2017-07-07 09:49:52.42 UTC | 16 | 2020-02-26 00:38:36.577 UTC | 2017-07-07 17:26:28.453 UTC | null | 34,772 | null | 34,772 | null | 1 | 52 | python|jupyter-notebook|plotly|jupyter|plotly-dash | 42,631 | <p>Disclaimer: I wrote Dash :)</p>
<p>I'd recommend just trying both of them. Dash takes about 30 minutes to run through the <a href="https://plot.ly/dash/getting-started" rel="noreferrer">tutorial</a>.</p>
<p>I'd also recommend checking out:</p>
<ul>
<li>The <a href="https://medium.com/@plotlygraphs/introducing-dash-5ecf7191b503" rel="noreferrer">Dash announcement letter</a>. This is a comprehensive introduction to Dash including examples, architecture, and a discussion about licensing (MIT).</li>
<li>Live examples of Dash Apps in the <a href="https://plot.ly/dash/gallery" rel="noreferrer">Dash App Gallery</a></li>
</ul>
<p>There are some high-level features of Dash (these are covered in the <a href="https://medium.com/@plotlygraphs/introducing-dash-5ecf7191b503" rel="noreferrer">announcement letter</a> in more detail)</p>
<ul>
<li>Dash Apps require very little boilerplate to get started - a simple "hello world" Dash app that dynamically displays a graph based off of a dropdown's value weighs in under 50 lines of code.</li>
<li>Dash Apps are generated entirely from Python, even the HTML and JS</li>
<li>Dash Apps bind interactive components (dropdowns, graphs, sliders, text inputs) with your own Python code through reactive Dash "<code>callbacks</code>".</li>
<li>Dash Apps are "reactive" which means that it's easy to reason about complicated UIs with multiple inputs, multiple outputs, and inputs that depend on other inputs.</li>
<li>Dash Apps are inherently multi-user apps as the "state" of the app is entirely in the client: multiple users can view apps and have independent sessions. </li>
<li>Since Dash has a traditional stateless backend, it's easy to scale apps to serve hundreds or thousands of users by scaling up the number of worker processes. Requests are sent to whichever worker is available, enabling a small number of workers to service a larger number of sessions.</li>
<li>Dash uses <a href="https://facebook.github.io/react/" rel="noreferrer">React.js</a> to render components and includes a <a href="http://plot.ly/dash/plugins" rel="noreferrer">plugin system</a> for creating your own Dash components with React.</li>
<li>Dash's <code>Graph</code> component is interactive, allowing Dash app authors to write applications that respond to hovering, clicking, or selecting points on the graph.</li>
</ul>
<blockquote>
<p>I also found the Plotly documentation quite unclear on what exactly is Open Source and whether the data gets uploaded to them or if the plotting can be done offline?</p>
</blockquote>
<p>It sounds like this is referring to the <a href="https://github.com/plotly/plotly.py" rel="noreferrer"><code>plotly.py</code></a> graphing library. This is a separate library than Dash. Both libraries use the MIT licensed <a href="https://github.com/plotly/plotly.js" rel="noreferrer"><code>plotly.js</code></a> library for creating charts. <code>plotly.js</code> doesn't send any data to the plotly server - it's completely client-side. </p>
<p>The <code>plotly.py</code> library includes methods to send the data to your online plotly account for hosting, sharing, and editing the charts but it's completely opt-in. Again, <code>plotly.py</code> is a separate library than <code>Dash</code>. <code>plotly.py</code> is for interactive graphing, <code>Dash</code> is for creating interactive applications (which can include charts).</p>
<blockquote>
<p>In particular in a multi-user deployment? There are clearly two modes for the underlying Plotly library but what mode does Dash operate in?</p>
</blockquote>
<ul>
<li>Dash is MIT licensed. You can run Dash on your own servers or on your machine. </li>
<li>Dash uses a Flask server, so you can deploy Dash apps in the same way that you would deploy Flask apps</li>
<li>Plotly licenses <a href="https://plot.ly/dash/pricing" rel="noreferrer">Dash Enterprise</a>, a platform that can be installed on your own infrastructure. Dash Enterprise is a "PaaS" that makes it easy to deploy apps on your own servers, SSO/LDAP authentication, additional design capabilities, additional app capabilities, and more.</li>
</ul> |
35,041,291 | Remove ios, windows8, and wp8 from Xamarin Forms PCL - nuget 3.0 opt-into error? | <p>I'm working on a Xamarin Forms project. I want to target Android and Windows 10 UWP. </p>
<p>When I try to clean up the PCL by removing "Windows 8", "Windows Phone Silverlight 8", "Windows Phone 8.1", "Xamarin.ios", and "Xamarin.ios (classic)" from the PCL targets, I get the following nasty...</p>
<p>I'm really just trying to remove WP8 as I don't care about targeting it.</p>
<blockquote>
<p>The project's targets cannot be changed. The selected targets require
the project to opt-into NuGet 3.0 support, however, Visual Studio
cannot automatically do this for you. Please uninstall all NuGet
packages and try again.</p>
</blockquote>
<p>How do you get a project to opt-into NuGet 3.0?
Something else I should try?</p>
<p>environ: Xamarin Forms, VS2015</p>
<p><a href="https://i.stack.imgur.com/wBfST.png"><img src="https://i.stack.imgur.com/wBfST.png" alt="enter image description here"></a></p>
<p>Thanks....</p> | 37,714,888 | 8 | 4 | null | 2016-01-27 15:23:26.173 UTC | 5 | 2017-09-02 18:23:44.66 UTC | 2016-01-27 15:49:12.953 UTC | null | 1,564,317 | null | 1,564,317 | null | 1 | 52 | visual-studio-2015|nuget|xamarin.forms|windows-10-universal | 14,088 | <p>The solution that worked for me:</p>
<p>Uninstall Xamarin.Forms:</p>
<pre><code>Right Click Solution -> Manage NuGet Packages -> Uninstall Xamarin.Forms -> Restart VS
</code></pre>
<p>Then remove build platforms:</p>
<pre><code>Right Click Solution -> Properties -> Build -> under Targeting select Change -> Remove platform(s) -> Restart VS
</code></pre>
<p>Reinstall Xamarin.Forms:</p>
<pre><code>Manage NuGet packages -> Search for Xamarin.Forms -> Install -> Restart VS
</code></pre> |
35,166,214 | Running individual XCTest (UI, Unit) test cases for iOS apps from the command line | <p>Is it possible to run individual test cases, or individual test suites, from an iOS app test target, instead of all the test cases, from a command line interface?</p>
<p>You can run tests from command line with <a href="https://krausefx.com/blog/run-xcode-7-ui-tests-from-the-command-line" rel="noreferrer">xcodebuild</a>, out of the box. When you do so, you run all of the test cases contained in the test target you've selected.</p>
<p>You can also do so with <a href="https://github.com/fastlane/scan" rel="noreferrer">scan</a> from Fastlane, though I believe you're restricted to running all of the tests of the build scheme you select (as above), so it's not different from xcodebuild.</p>
<p>You can run specific tests with <a href="https://github.com/facebook/xctool" rel="noreferrer">xctool</a> from Facebook, but it doesn't use xcodebuild, and is restricted to running on simulators only, not actual iOS test devices.</p>
<p>I found a reference to running the <a href="https://stackoverflow.com/questions/19988723/how-do-i-run-xctest-from-the-command-line-with-xcode-5">xctest</a> command line utility directly, but it seems to be an undocumented feature and targets DerivedData. This is complicated by the fact that UI Tests, <a href="https://github.com/facebook/xctool/issues/534#issuecomment-154790245" rel="noreferrer">have their *xctest files in a separate XCTRunner bundle</a>.</p> | 37,971,495 | 6 | 4 | null | 2016-02-03 00:09:15.057 UTC | 11 | 2022-08-23 20:13:34.78 UTC | 2017-05-23 12:34:38.62 UTC | null | -1 | null | 223,327 | null | 1 | 36 | ios|unit-testing|xctest|xcode-ui-testing | 22,697 | <p>It is now possible with Xcode 8 using the <code>-only-testing</code> parameter with <code>xcodebuild</code>:</p>
<pre><code>xcodebuild test -workspace <path>
-scheme <name>
-destination <specifier>
-only-testing:TestBundle/TestSuite/TestCase
</code></pre>
<p><a href="https://i.stack.imgur.com/and0s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/and0s.png" alt="enter image description here" /></a></p> |
796,490 | python method to extract content (excluding navigation) from an HTML page | <p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p>
<p>I'm guessing it's something like collecting DIV and P elements and then checking them for a minimum amount of text content, but I'm sure a solid implementation would include plenty of things that I haven't thought of.</p> | 796,810 | 5 | 4 | null | 2009-04-28 06:40:28.507 UTC | 10 | 2014-07-22 23:39:26.557 UTC | 2010-01-02 21:07:55.267 UTC | null | 222,815 | null | 9,106 | null | 1 | 8 | python|html|parsing|semantics|html-content-extraction | 3,595 | <p>Try the <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">Beautiful Soup</a> library for Python. It has very simple methods to extract information from an html file.</p>
<p>Trying to generically extract data from webpages would require people to write their pages in a similar way... but there's an almost infinite number of ways to convey a page that looks identical let alone all the conbinations you can have to convey the same information.</p>
<p>Was there a particular type of information you were trying to extract or some other end goal?</p>
<p>You could try extracting any content in 'div' and 'p' markers and compare the relative sizes of all the information in the page. The problem then is that people probably group information into collections of 'div's and 'p's (or at least they do if they're writing well formed html!).</p>
<p>Maybe if you formed a tree of how the information is related (nodes would be the 'p' or 'div or whatever and each node would contain the associated text) you could do some sort of analysis to identify the smallest 'p' or 'div' that encompases what appears to be the majority of the information.. ?</p>
<p><strong>[EDIT]</strong> Maybe if you can get it into the tree structure I suggested, you could then use a similar points system to spam assassin. Define some rules that attempt to classify the information. Some examples:</p>
<pre><code>+1 points for every 100 words
+1 points for every child element that has > 100 words
-1 points if the section name contains the word 'nav'
-2 points if the section name contains the word 'advert'
</code></pre>
<p>If you have a lots of low scoring rules which add up when you find more relevent looking sections, I think that could evolve into a fairly powerful and robust technique.</p>
<p><strong>[EDIT2]</strong> Looking at the readability, it seems to be doing pretty much exactly what I just suggested! Maybe it could be improved to try and understand tables better?</p> |
763,942 | Calculate System.Decimal Precision and Scale | <p>Suppose that we have a System.Decimal number.</p>
<p>For illustration, let's take one whose ToString() representation is as follows:</p>
<pre><code>d.ToString() = "123.4500"
</code></pre>
<p>The following can be said about this Decimal. For our purposes here, scale is defined as the number of digits to the right of the decimal point. Effective scale is similar but ignores any trailing zeros that occur in the fractional part. (In other words, these parameters are defined like SQL decimals plus some additional parameters to account for the System.Decimal concept of trailing zeros in the fractional part.)</p>
<ul>
<li>Precision: 7</li>
<li>Scale: 4</li>
<li>EffectivePrecision: 5</li>
<li>EffectiveScale: 2</li>
</ul>
<p>Given an arbitrary System.Decimal, how can I compute all four of these parameters efficiently and without converting to a String and examining the String? The solution probably requires Decimal.GetBits.</p>
<p>Some more examples:</p>
<pre><code>Examples Precision Scale EffectivePrecision EffectiveScale
0 1 (?) 0 1 (?) 0
0.0 2 (?) 1 1 (?) 0
12.45 4 2 4 2
12.4500 6 4 4 2
770 3 0 3 0
</code></pre>
<p>(?) Alternatively interpreting these precisions as zero would be fine.</p> | 764,102 | 5 | 0 | null | 2009-04-18 18:52:20.34 UTC | 17 | 2016-08-15 10:56:26.047 UTC | null | null | null | null | 14,280 | null | 1 | 26 | .net|decimal | 29,211 | <p>Yes, you'd need to use <code>Decimal.GetBits</code>. Unfortunately, you then have to work with a 96-bit integer, and there are no simple integer type in .NET which copes with 96 bits. On the other hand, it's possible that you could use <code>Decimal</code> itself...</p>
<p>Here's some code which produces the same numbers as your examples. Hope you find it useful :)</p>
<pre><code>using System;
public class Test
{
static public void Main(string[] x)
{
ShowInfo(123.4500m);
ShowInfo(0m);
ShowInfo(0.0m);
ShowInfo(12.45m);
ShowInfo(12.4500m);
ShowInfo(770m);
}
static void ShowInfo(decimal dec)
{
// We want the integer parts as uint
// C# doesn't permit int[] to uint[] conversion,
// but .NET does. This is somewhat evil...
uint[] bits = (uint[])(object)decimal.GetBits(dec);
decimal mantissa =
(bits[2] * 4294967296m * 4294967296m) +
(bits[1] * 4294967296m) +
bits[0];
uint scale = (bits[3] >> 16) & 31;
// Precision: number of times we can divide
// by 10 before we get to 0
uint precision = 0;
if (dec != 0m)
{
for (decimal tmp = mantissa; tmp >= 1; tmp /= 10)
{
precision++;
}
}
else
{
// Handle zero differently. It's odd.
precision = scale + 1;
}
uint trailingZeros = 0;
for (decimal tmp = mantissa;
tmp % 10m == 0 && trailingZeros < scale;
tmp /= 10)
{
trailingZeros++;
}
Console.WriteLine("Example: {0}", dec);
Console.WriteLine("Precision: {0}", precision);
Console.WriteLine("Scale: {0}", scale);
Console.WriteLine("EffectivePrecision: {0}",
precision - trailingZeros);
Console.WriteLine("EffectiveScale: {0}", scale - trailingZeros);
Console.WriteLine();
}
}
</code></pre> |
168,455 | How do you post to an iframe? | <p>How do you post data to an iframe?</p> | 168,488 | 5 | 0 | null | 2008-10-03 19:18:53.7 UTC | 82 | 2022-01-05 06:05:32.783 UTC | 2015-09-17 16:16:45.51 UTC | null | 1,505,120 | Sean Ibne | 24,958 | null | 1 | 302 | post|iframe | 440,830 | <p>Depends what you mean by "post data". You can use the HTML <code>target=""</code> attribute on a <code><form /></code> tag, so it could be as simple as:</p>
<pre><code><form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!">
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
</code></pre>
<p>If that's not it, or you're after something more complex, please edit your question to include more detail.</p>
<p>There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a <a href="https://stackoverflow.com/questions/2181385/ie-issue-submitting-form-to-an-iframe-using-javascript">work-around here</a>), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.</p>
<p>I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.</p>
<p><strong>default.asp</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<form action="do_stuff.asp" method="post" target="my_frame">
<input type="text" name="someText" value="Some Text">
<input type="submit">
</form>
<iframe name="my_frame" src="do_stuff.asp">
</iframe>
</body>
</html>
</code></pre>
<p><strong>do_stuff.asp</strong></p>
<pre><code><%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<% if (Request.Form.Count) { %>
You typed: <%=Request.Form("someText").Item%>
<% } else { %>
(not submitted)
<% } %>
</body>
</html>
</code></pre>
<p>I would be very interested to hear of any browser that doesn't run these examples correctly.</p> |
245,192 | What are "first-class" objects? | <p>When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not?</p>
<p>When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?</p> | 245,208 | 5 | 0 | null | 2008-10-28 22:58:47.733 UTC | 115 | 2021-11-10 16:01:18.767 UTC | 2021-11-10 16:01:18.767 UTC | Brian R. Bondy | 11,573,842 | Federico Ramponi | 18,770 | null | 1 | 242 | python|language-agnostic | 74,938 | <p>In short, it means there are no restrictions on the object's use. It's the same as
any other object.</p>
<p>A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. </p>
<blockquote>
<p>Depending on the language, this can
imply:</p>
<ul>
<li>being expressible as an anonymous literal value</li>
<li>being storable in variables</li>
<li>being storable in data structures</li>
<li>having an intrinsic identity (independent of any given name)</li>
<li>being comparable for equality with other entities</li>
<li>being passable as a parameter to a procedure/function</li>
<li>being returnable as the result of a procedure/function</li>
<li>being constructible at runtime</li>
<li>being printable</li>
<li>being readable</li>
<li>being transmissible among distributed processes</li>
<li>being storable outside running processes</li>
</ul>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/First-class_object" rel="noreferrer">Source</a>.</p>
<p>In C++ functions themselves are not first class objects, however:</p>
<ul>
<li>You can override the '()' operator making it possible to have an object function, which is first class.</li>
<li>Function pointers are first class. </li>
<li>boost bind, lambda and function do offer first class functions</li>
</ul>
<p>In C++, classes are not first class objects but instances of those classes are. In Python both the classes <em>and</em> the objects are first class objects. (See <a href="https://stackoverflow.com/a/6581949/1612701">this answer</a> for more details about classes as objects).</p>
<p>Here is an example of Javascript first class functions:</p>
<pre><code>// f: function that takes a number and returns a number
// deltaX: small positive number
// returns a function that is an approximate derivative of f
function makeDerivative( f, deltaX )
{
var deriv = function(x)
{
return ( f(x + deltaX) - f(x) )/ deltaX;
}
return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0) ~> 1
// cos(pi/2) ~> 0
</code></pre>
<p><a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">Source</a>.</p>
<p>Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. </p>
<p><strong>Regarding the edit:</strong></p>
<blockquote>
<p>EDIT. When one says "everything is
an object" (like in Python), does he
indeed mean that "everything is
first-class"?</p>
</blockquote>
<p>The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class. </p> |
251,403 | how do you make a heterogeneous boost::map? | <p>I want to have a map that has a homogeneous key type but heterogeneous data types.</p>
<p>I want to be able to do something like (pseudo-code):</p>
<pre><code>boost::map<std::string, magic_goes_here> m;
m.add<int>("a", 2);
m.add<std::string>("b", "black sheep");
int i = m.get<int>("a");
int j = m.get<int>("b"); // error!
</code></pre>
<p>I could have a pointer to a base class as the data type but would rather not.</p>
<p>I've never used boost before but have looked at the fusion library but can't figure out what I need to do.</p>
<p>Thanks for your help.</p> | 252,106 | 6 | 1 | null | 2008-10-30 19:23:10.537 UTC | 16 | 2017-05-14 14:00:23.86 UTC | 2009-07-11 19:37:40.14 UTC | null | 95,735 | null | 32,794 | null | 1 | 32 | c++|boost|map | 22,454 | <pre><code>#include <map>
#include <string>
#include <iostream>
#include <boost/any.hpp>
int main()
{
try
{
std::map<std::string, boost::any> m;
m["a"] = 2;
m["b"] = static_cast<char const *>("black sheep");
int i = boost::any_cast<int>(m["a"]);
std::cout << "I(" << i << ")\n";
int j = boost::any_cast<int>(m["b"]); // throws exception
std::cout << "J(" << j << ")\n";
}
catch(...)
{
std::cout << "Exception\n";
}
}
</code></pre> |
514,833 | How to delete a workspace in Eclipse? | <p>How to delete a workspace in Eclipse?</p> | 514,840 | 6 | 2 | null | 2009-02-05 06:43:42.493 UTC | 75 | 2018-03-21 05:13:36.907 UTC | 2014-10-25 22:05:00.873 UTC | null | 3,885,376 | Rahul | 24,424 | null | 1 | 320 | eclipse|workspace | 256,097 | <p>Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the <code>.metadata</code> folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are <em>outside</em> the workspace folder as well, so you may want to verify the location of each of the projects. </p>
<p>You can remove the workspace from the suggested workspaces by going into the <em>General/Startup and Shutdown/Workspaces</em> section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the <code>org.eclipse.ui.ide.prefs</code> file in the <code>configuration/.settings</code> directory under your installation directory (or in <code>~/.eclipse</code> on Unix, IIRC). </p> |
17,648,010 | Alert box shows form data when clicking button | <p>I am looking to create a button at the bottom of a form that will create an alert box that will show the form data entered. Form includes:
First Name
Last Name
Address 1
Address 2
City
State
Zip
Phone
Fax</p>
<p>Once the form is completed, the button is clicked and an alert box pops up showing the form data entered.</p>
<p>Does anyone know how to accomplish without the form actually being submitted or validated? There is no database for the form data to be submitted to, so there is no database to pull the information from.</p>
<p>Any help would be greatly appreciated.</p>
<p>I have not included the form code due to its length, but the current code I am working with for the Alert Box looks like this:</p>
<pre><code> <script>
function display_alert()
{
alert("");
}
</script>
<body>
<input type="button" onclick="display_alert()" value="Display alert box">
</body>
</code></pre> | 17,648,063 | 5 | 3 | null | 2013-07-15 06:31:44.677 UTC | null | 2022-01-06 14:13:10.443 UTC | 2013-07-15 06:38:24.997 UTC | null | 2,537,332 | null | 2,537,332 | null | 1 | 2 | javascript|onclick|alert | 79,416 | <p>If I get it right you need something like this:</p>
<pre><code><html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('send').onclick = function(e){
alert(document.getElementById("name").value);
return false;
}
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="name" id="name" />
<input type="submit" name="send" id="send" value="send" />
</form>
</body>
</html>
</code></pre>
<p>I don't really get what you mean with a database to pull the information from, but the example uses a click event to get the data from the form field and shows it in an alert without a submit.</p> |
46,694,794 | Error: could not find function "read_excel" using R on Mac | <p>I am trying to link up my excel data set to R for statistical analysis. I am running on OSX Sierra (10.12.6) with R studio (1.0.153) and Java 8 (update 144). </p>
<p>The function "read_excel" was able to open my excel document a week ago. When I moved the excel and the R document together to another folder, it no longer worked. Reloading the libraries has had no effect. After multiple attempts (and restarting R studio and computer), something finally worked but function "lmer" was no longer found. After reloading library "lme4", "read_excel" no longer worked!</p>
<p>I have also tried using "read.xlsx" and "readWorksheet(loadWorkbook(...))", which didn't work. "read.csv" also did not work properly since the commas were creating disorganized columns and I am dealing with a larger excel workbook with ongoing changes.</p>
<p>Reading on Stack, question <a href="https://stackoverflow.com/questions/7049272/importing-xlsx-file-into-r">Importing .xlsx file into R</a> has not resolved my issue! Please help!</p>
<p>Libraries loaded:</p>
<pre><code>library(multcomp)
library(nlme)
library(XLConnect)
library(XLConnectJars)
library(lme4)
library(car)
library(rJava)
library(xlsx)
library(readxl)
</code></pre>
<p>R data file:</p>
<pre><code>Dataset <- read_excel("Example.xlsx",sheet="testing")
#alternative line: Dataset <- read.xlsx("~/Desktop/My Stuff/Sample/Example.xlsx", sheet=7)
Dataset$AAA <- as.factor(Dataset$AAA)
Dataset$BBB <- as.factor(Dataset$BBB)
Dataset$CCC <- as.numeric(Dataset$CCC)
Dataset$DDD <- as.numeric(Dataset$DDD)
Dataset_lme = lmer(CCC ~ AAA + BBB + (1|DDD), data=Dataset)
</code></pre> | 46,695,124 | 3 | 5 | null | 2017-10-11 18:04:12.51 UTC | null | 2020-04-23 05:48:33.6 UTC | 2017-11-03 14:53:23.927 UTC | null | 2,461,552 | null | 8,760,612 | null | 1 | 7 | r|macos|readxl | 53,481 | <p>While you called the library, try and see if adding readxl::read_excel(path = "yourPath",sheet=1), or even remove the sheet reference. It will automatically take the first sheet.</p> |
33,370,134 | When to generate a new Application Key in Laravel? | <p>Since it automatically sets it for me in my <code>.env</code> file when I create the app, I'm not sure when I should run it.</p>
<p>In addition to that, if a second developer comes in, and <strong>clones</strong> the app, does he/she need to run <code>php artisan key:generate</code> ? </p>
<p>How do we know exactly when to run <code>php artisan key:generate</code> ?</p> | 33,370,272 | 2 | 3 | null | 2015-10-27 14:04:25.883 UTC | 13 | 2021-03-25 07:19:16.72 UTC | 2017-03-20 08:53:12.2 UTC | null | 7,702,001 | null | 4,480,164 | null | 1 | 81 | php|laravel|laravel-5|console|laravel-5.1 | 191,465 | <p><code>php artisan key:generate</code> is a command that sets the <code>APP_KEY</code> value in your <code>.env</code> file. By default, this command is run following a <code>composer create-project laravel/laravel</code> command. If you use a version control system like <code>git</code> to manage your project for development, calling <code>git push ...</code> will push a copy of your Laravel project to wherever it is going, but will not include your <code>.env</code> file. Therefore, if someone clones your project using <code>git clone ...</code> they will have to manually enter <code>php artisan key:generate</code> for their app to function correctly.</p>
<p>So, TL:DR the only time you <em>need</em> to call <code>php artisan key:generate</code> is following a <code>clone</code> of a pre-created Laravel project.</p>
<p>Side note: If you try to run a Laravel project with your <code>APP_KEY</code> set to <code>SomeRandomString</code> (which is the default in your <code>.env.example</code> file, you will actually get an error: </p>
<blockquote>
<p>No supported encrypter found. The cipher and / or key length are invalid.</p>
</blockquote> |
22,945,651 | Remove space between plotted data and the axes | <p>I have the following dataframe:</p>
<pre><code>uniq <- structure(list(year = c(1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2014L), uniq.loc = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("u.1", "u.2", "u.3"), class = "factor"), uniq.n = c(1, 1, 1, 2, 5, 4, 2, 16, 16, 10, 15, 14, 8, 12, 20, 11, 17, 30, 17, 21, 22, 19, 34, 44, 56, 11, 0, 0, 3, 3, 7, 17, 12, 21, 18, 10, 12, 9, 7, 11, 25, 14, 11, 17, 12, 24, 59, 17, 36, 50, 59, 12, 0, 0, 0, 1, 4, 6, 3, 3, 9, 3, 4, 2, 5, 2, 12, 6, 8, 8, 3, 2, 9, 5, 20, 7, 10, 8), uniq.p = c(100, 100, 25, 33.3, 31.2, 14.8, 11.8, 40, 37.2, 43.5, 48.4, 56, 40, 48, 35.1, 35.5, 47.2, 54.5, 53.1, 44.7, 24.4, 46.3, 37.8, 43.6, 44.8, 35.5, 0, 0, 75, 50, 43.8, 63, 70.6, 52.5, 41.9, 43.5, 38.7, 36, 35, 44, 43.9, 45.2, 30.6, 30.9, 37.5, 51.1, 65.6, 41.5, 40, 49.5, 47.2, 38.7, 0, 0, 0, 16.7, 25, 22.2, 17.6, 7.5, 20.9, 13, 12.9, 8, 25, 8, 21.1, 19.4, 22.2, 14.5, 9.4, 4.3, 10, 12.2, 22.2, 6.9, 8, 25.8)), .Names = c("year", "uniq.loc", "uniq.n", "uniq.p"), class = "data.frame", row.names = c(NA, -78L))
</code></pre>
<p>When I make an area-plot with:</p>
<pre><code>ggplot(data = uniq) +
geom_area(aes(x = year, y = uniq.p, fill = uniq.loc), stat = "identity", position = "stack") +
scale_x_continuous(limits=c(1986,2014)) +
scale_y_continuous(limits=c(0,101)) +
theme_bw()
</code></pre>
<p>I get this result:</p>
<p><img src="https://i.stack.imgur.com/ndT43.png" alt="enter image description here"></p>
<p>However, I want to remove the space between the axis and the actual plot. When I add <code>theme(panel.grid = element_blank(), panel.margin = unit(-0.8, "lines"))</code> I get the following error message:</p>
<blockquote>
<pre><code>Error in theme(panel.grid = element_blank(), panel.margin = unit(-0.8, :
could not find function "unit"
</code></pre>
</blockquote>
<p>Any suggestions on how to solve this problem?</p> | 22,945,857 | 3 | 3 | null | 2014-04-08 18:44:39.49 UTC | 65 | 2021-08-03 16:59:39.567 UTC | 2021-08-03 16:59:39.567 UTC | null | 1,851,712 | null | 2,204,410 | null | 1 | 152 | r|plot|ggplot2 | 128,840 | <p><strong>Update:</strong> See <a href="https://stackoverflow.com/a/52318834/2204410">@divibisan's answer</a> for further possibilities in the latest versions of <a href="/questions/tagged/ggplot2" class="post-tag" title="show questions tagged 'ggplot2'" rel="tag">ggplot2</a>.</p>
<hr>
<p>From <code>?scale_x_continuous</code> about the <code>expand</code>-argument:</p>
<blockquote>
<p>Vector of range expansion constants used to add some padding around
the data, to ensure that they are placed some distance away from the
axes. The defaults are to expand the scale by 5% on each side for
continuous variables, and by 0.6 units on each side for discrete
variables.</p>
</blockquote>
<p>The problem is thus solved by adding <code>expand = c(0,0)</code> to <code>scale_x_continuous</code> and <code>scale_y_continuous</code>. This also removes the need for adding the <code>panel.margin</code> parameter.</p>
<p>The code:</p>
<pre><code>ggplot(data = uniq) +
geom_area(aes(x = year, y = uniq.p, fill = uniq.loc), stat = "identity", position = "stack") +
scale_x_continuous(limits = c(1986,2014), expand = c(0, 0)) +
scale_y_continuous(limits = c(0,101), expand = c(0, 0)) +
theme_bw() +
theme(panel.grid = element_blank(),
panel.border = element_blank())
</code></pre>
<p>The result:
<img src="https://i.stack.imgur.com/mc1yv.png" alt="plot area chart with no gaps"></p> |
2,180,255 | Matching SRC attribute of IMG tag using preg_match | <p>I'm attempting to run preg_match to extract the SRC attribute from the first IMG tag in an article (in this case, stored in $row->introtext).</p>
<pre><code>preg_match('/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\']*)/i', $row->introtext, $matches);
</code></pre>
<p>Instead of getting something like</p>
<pre><code>images/stories/otakuzoku1.jpg
</code></pre>
<p>from</p>
<pre><code><img src="images/stories/otakuzoku1.jpg" border="0" alt="Inside Otakuzoku's store" />
</code></pre>
<p>I get just</p>
<pre><code>0
</code></pre>
<p>The regex should be right, but I can't tell why it appears to be matching the border attribute and not the src attribute.</p>
<p>Alternatively, if you've had the patience to read this far without skipping straight to the reply field and typing 'use a HTML/XML parser', can a good tutorial for one be recommended as I'm having trouble finding one at all that's applicable to PHP 4.</p>
<p>PHP 4.4.7</p> | 2,180,298 | 6 | 0 | null | 2010-02-01 21:36:22.213 UTC | 6 | 2019-05-16 04:36:41.84 UTC | null | null | null | null | 217,311 | null | 1 | 15 | php|regex|parsing|preg-match|src | 62,342 | <p>Your expression is incorrect. Try:</p>
<pre><code>preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $row->introtext, $matches);
</code></pre>
<p>Note the removal of brackets around img and src and some other cleanups.</p> |
1,766,535 | Bit Hack - Round off to multiple of 8 | <p>can anyone please explain how this works (asz + 7) & ~7; It rounds off asz to the next higher multiple of 8.</p>
<p>It is easy to see that ~7 produces 11111000 (8bit representation) and hence switches off the last 3 bits ,thus any number which is produced is a multiple of 8.</p>
<p>My question is how does adding asz to 7 before masking [edit] produce the next higher[end edit] multiple of 8 ? I tried writing it down on paper </p>
<p>like :</p>
<pre><code>1 + 7 = 8 = 1|000 (& ~7) -> 1000
2 + 7 = 9 = 1|001 (& ~7) -> 1000
3 + 7 = 10 = 1|010 (& ~7) -> 1000
4 + 7 = 11 = 1|011 (& ~7) -> 1000
5 + 7 = 12 = 1|100 (& ~7) -> 1000
6 + 7 = 13 = 1|101 (& ~7) -> 1000
7 + 7 = 14 = 1|110 (& ~7) -> 1000
8 + 7 = 15 = 1|111 (& ~7) -> 1000
</code></pre>
<p>A pattern clearly seems to emerge which has been exploited .Can anyone please help me it out ?</p>
<p>Thank You all for the answers.It helped confirm what I was thinking. I continued the writing the pattern above and when I crossed 10 , i could clearly see that the nos are promoted to the next "block of 8" if I can say so.</p>
<p>Thanks again.</p> | 1,766,566 | 7 | 0 | null | 2009-11-19 21:05:18.283 UTC | 12 | 2009-11-19 21:23:02.663 UTC | 2009-11-19 21:22:03.01 UTC | null | 212,721 | null | 212,721 | null | 1 | 12 | c|bit-manipulation | 10,018 | <p>Well, if you were trying to round <em>down</em>, you wouldn't need the addition. Just doing the masking step would clear out the bottom bits and you'd get rounded to the next lower multiple. </p>
<p>If you want to round <em>up</em>, first you have to add enough to "get past" the next multiple of 8. Then the same masking step takes you back down to the multiple of 8. The reason you choose 7 is that it's the only number guaranteed to be "big enough" to get you from any number up past the next multiple of 8 without going up an extra multiple if your original number were already a multiple of 8.</p>
<p>In general, to round up to a power of two:</p>
<pre><code>unsigned int roundTo(unsigned int value, unsigned int roundTo)
{
return (value + (roundTo - 1)) & ~(roundTo - 1);
}
</code></pre> |
2,216,893 | PHP - To echo or not to echo? | <p>What is more efficient and/or what is better practice, to echo the HTML or have many open and close <code>php</code> tags?</p>
<p>Obviously for big areas of HTML it is sensible to open and close the <code>php</code> tags. What about when dealing with something like generating XML? Should you open and close the <code>php</code> tags with a single echo for each piece of data or use a single echo with the XML tags included in quotations?</p> | 2,216,908 | 7 | 0 | null | 2010-02-07 13:28:33.58 UTC | 12 | 2011-07-19 05:49:58.907 UTC | 2011-02-19 22:44:59.063 UTC | null | 63,550 | null | 187,227 | null | 1 | 16 | php|performance | 3,801 | <p>From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person. </p>
<p>The more a homogeneous block the markup is, the cleaner the work.</p>
<p>One way to achieve this is to prepare as much as possible in variables, and using the <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc" rel="noreferrer">heredoc syntax</a>:</p>
<pre><code>// Preparation
$var1 = get_value("yxyz");
$var2 = get_url ("abc");
$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
$var4 = htmlentities(get_value("def"));
// Output
echo <<<EOT
<fieldset title="$var4">
<ul class="$var1">
<li>
$var2
</li>
</ul>
</fieldset>
EOT;
</code></pre>
<p>You will want to use more sensible variable names, of course.</p>
<p><strong>Edit:</strong> The link pointed out by @stesch in the comments provides some good arguments towards using a <strong>serializer</strong> when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in <em>every</em> situation, especially from a maintenance standpoint where templates are <em>so</em> much more easy to edit, but the link is well worth a read. <a href="http://hsivonen.iki.fi/producing-xml/#noescaping" rel="noreferrer"><strong>HOWTO Avoid Being Called a Bozo When Producing XML</strong></a></p>
<p>Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.</p> |
2,041,051 | Could not load file or assembly 'MySql.Data, Version=6.2.2.0 | <p>I am working on Desktop application with c# and Data base MySQL. When I install its installer on my machine it works fine but when I install it on other machine its give following exception when try to access DB. I am using <code>MySQL.Data.dll</code> to communicate with MySQL.</p>
<blockquote>
<p>Could not load file or assembly 'MySql.Data, Version=6.2.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The system cannot find the file specified.</p>
</blockquote>
<p>and <code>MySql.Data.dll</code> file in present in Project's folder in Program files folder</p>
<p>Actually when I run it from its folder in Program file it run fine with no error but When i try to run it from its shortcut in Start Menu it gives that error.</p> | 2,041,203 | 8 | 0 | null | 2010-01-11 10:06:39.403 UTC | 7 | 2021-06-06 22:12:28.287 UTC | 2012-10-04 10:06:30.067 UTC | null | 162,671 | null | 228,755 | null | 1 | 17 | c#|.net|mysql|database | 75,069 | <ol>
<li><p>Does the shortcut in the Start Menu set the working directory correctly? (I suspect that this is the most likely answer)</p></li>
<li><p>Is there a different/incorrect version of MySql.Data.dll installed in the GAC (Global Assembly Cache)? I've seen this give similar error messages before.</p></li>
</ol> |
2,030,064 | How to run eclipse in clean mode? what happens if we do so? | <p>If something is not working properly or some plug-ins are not loaded properly in my Eclipse I often get suggestion to open Eclipse in clean mode.</p>
<p>So, how to run in clean mode? And what happens if I do so?</p> | 2,030,092 | 10 | 0 | null | 2010-01-08 19:17:36.89 UTC | 46 | 2020-02-06 15:37:19.63 UTC | 2020-01-30 09:22:10.53 UTC | null | 452,775 | null | 241,717 | null | 1 | 209 | java|eclipse | 379,417 | <p>What it does:</p>
<blockquote>
<p>if set to "true", any cached data used
by the OSGi framework and eclipse
runtime will be wiped clean. This will
clean the caches used to store bundle
dependency resolution and eclipse
extension registry data. Using this
option will force eclipse to
reinitialize these caches.</p>
</blockquote>
<p>How to use it:</p>
<ul>
<li>Edit the <code>eclipse.ini</code> file located in your Eclipse install directory and insert <code>-clean</code> as the first line. </li>
<li>Or edit the shortcut you use to start Eclipse and add <code>-clean</code> as the first argument. </li>
<li>Or create a batch or shell script that calls the Eclipse executable with the <code>-clean</code> argument. The advantage to this step is you can keep the script around and use it each time you want to clean out the workspace. You can name it something like <code>eclipse-clean.bat</code> (or <code>eclipse-clean.sh</code>). </li>
</ul>
<p>(From: <a href="http://www.eclipsezone.com/eclipse/forums/t61566.html" rel="noreferrer">http://www.eclipsezone.com/eclipse/forums/t61566.html</a>)</p>
<p>Other eclipse command line options: <a href="http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html" rel="noreferrer">http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html</a></p> |
2,220,301 | How to evaluate http response codes from bash/shell script? | <p>I have the feeling that I'm missing the obvious, but have not succeeded with <code>man [curl|wget]</code> or google ("http" makes such a bad search term). I'm looking for a quick&dirty fix to one of our webservers that frequently fails, returning status code 500 with an error message. Once this happens, it needs to be restarted.</p>
<p>As the root cause seems to be hard to find, we're aiming for a quick fix, hoping that it will be enough to bridge the time until we can really fix it (the service doesn't need high availability)</p>
<p>The proposed solution is to create a cron job that runs every 5 minutes, checking <a href="http://localhost:8080/" rel="noreferrer">http://localhost:8080/</a>. If this returns with status code 500, the webserver will be restarted. The server will restart in under a minute, so there's no need to check for restarts already running.</p>
<p>The server in question is a ubuntu 8.04 minimal installation with just enough packages installed to run what it currently needs. There is no hard requirement to do the task in bash, but I'd like it to run in such a minimal environment without installing any more interpreters. </p>
<p>(I'm sufficiently familiar with scripting that the command/options to assign the http status code to an environment variable would be enough - this is what I've looked for and could not find.)</p> | 2,220,646 | 13 | 0 | null | 2010-02-08 08:25:33.427 UTC | 67 | 2022-05-23 10:21:49.407 UTC | null | null | null | null | 13,447 | null | 1 | 250 | http|bash|shell|http-headers | 311,623 | <p>I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.</p>
<pre><code>response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)
</code></pre>
<p>Note, format provided for --write-out should be quoted.
As suggested by @ibai, add <code>--head</code> to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.</p> |
1,801,549 | How to reverse a singly linked list using only two pointers? | <p>I wonder if there exists some logic to reverse a singly-linked list using only two pointers.</p>
<p>The following is used to reverse the single linked list using three pointers namely <code>p</code>, <code>q</code>, <code>r</code>:</p>
<pre><code>struct node {
int data;
struct node *link;
};
void reverse() {
struct node *p = first,
*q = NULL,
*r;
while (p != NULL) {
r = q;
q = p;
p = p->link;
q->link = r;
}
first = q;
}
</code></pre>
<p>Is there any other alternate to reverse the linked list? What would be the best logic to reverse a singly linked list, in terms of time complexity?</p> | 1,801,703 | 36 | 7 | null | 2009-11-26 04:34:25.527 UTC | 75 | 2022-06-13 17:13:31.14 UTC | 2019-10-01 20:48:32.66 UTC | Roger Pate | 15,168 | null | 2,714,770 | null | 1 | 114 | c|algorithm|data-structures|linked-list|singly-linked-list | 266,445 | <p>Any alternative? No, this is as simple as it gets, and there's no fundamentally-different way of doing it. This algorithm is already O(n) time, and you can't get any faster than that, as you must modify every node.</p>
<p>It looks like your code is on the right track, but it's not quite working in the form above. Here's a working version:</p>
<pre><code>#include <stdio.h>
typedef struct Node {
char data;
struct Node* next;
} Node;
void print_list(Node* root) {
while (root) {
printf("%c ", root->data);
root = root->next;
}
printf("\n");
}
Node* reverse(Node* root) {
Node* new_root = 0;
while (root) {
Node* next = root->next;
root->next = new_root;
new_root = root;
root = next;
}
return new_root;
}
int main() {
Node d = { 'd', 0 };
Node c = { 'c', &d };
Node b = { 'b', &c };
Node a = { 'a', &b };
Node* root = &a;
print_list(root);
root = reverse(root);
print_list(root);
return 0;
}
</code></pre> |
33,537,950 | How to Delete a topic in apache kafka | <p>I need to delete a topic in kafka-0.8.2.2.3. I have used the below command for deleting the topic:</p>
<pre><code>bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic DummyTopic
</code></pre>
<p>The command executed successfully but when I run a command to list the topics, I could see that the topic is still there and it shows <strong>marked for deletion</strong>.</p>
<pre><code>bin/kafka-topics.sh --list --zookeeper localhost:2181
DummyTopic - marked for deletion
</code></pre>
<p>And when I create the topic DummyTopic it outputs the exception, The topic already exists, below is the stack trace:</p>
<pre><code>Error while executing topic command Topic "DummyTopic" already exists.
kafka.common.TopicExistsException: Topic "DummyTopic" already exists.
at kafka.admin.AdminUtils$.createOrUpdateTopicPartitionAssignmentPathInZK(AdminUtils.scala:248)
at kafka.admin.AdminUtils$.createTopic(AdminUtils.scala:233)
at kafka.admin.TopicCommand$.createTopic(TopicCommand.scala:92)
at kafka.admin.TopicCommand$.main(TopicCommand.scala:54)
at kafka.admin.TopicCommand.main(TopicCommand.scala)
</code></pre>
<p>Please let me know how can I delete this topic.</p> | 33,538,299 | 1 | 3 | null | 2015-11-05 06:25:20.483 UTC | 35 | 2019-12-01 04:35:13.98 UTC | 2019-12-01 04:35:13.98 UTC | null | 2,308,683 | null | 4,787,205 | null | 1 | 108 | java|apache-kafka | 237,310 | <p>Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting <code>delete.topic.enable</code> to true) on all brokers first. </p>
<p>Note: Ever since 1.0.x, the functionality being stable, <code>delete.topic.enable</code> is by default <code>true</code>.</p>
<p>Follow this step by step process for manual deletion of topics</p>
<ol>
<li>Stop <em>Kafka</em> server</li>
<li>Delete the topic directory, on each <em>broker</em> (as defined in the <code>logs.dirs</code> and <code>log.dir</code> properties) with <code>rm -rf</code> command</li>
<li>Connect to <em>Zookeeper</em> instance: <code>zookeeper-shell.sh host:port</code></li>
<li>From within the <em>Zookeeper</em> instance:
<ol>
<li>List the topics using: <code>ls /brokers/topics</code></li>
<li>Remove the topic folder from <em>ZooKeeper</em> using: <code>rmr /brokers/topics/yourtopic</code></li>
<li>Exit the Zookeeper instance (Ctrl+C)</li>
</ol></li>
<li>Restart <em>Kafka</em> server</li>
<li>Confirm if it was deleted or not by using this command
<code>kafka-topics.sh --list --zookeeper host:port</code></li>
</ol> |
17,684,610 | Python convert csv to xlsx | <p>In <a href="https://superuser.com/questions/301431/how-to-batch-convert-csv-to-xls-xlsx">this post</a> there is a Python example to convert from csv to xls.</p>
<p>However, my file has more than 65536 rows so xls does not work. If I name the file xlsx it doesnt make a difference. Is there a Python package to convert to xlsx?</p> | 17,684,679 | 8 | 0 | null | 2013-07-15 10:21:28.677 UTC | 42 | 2020-04-08 20:16:44.08 UTC | 2017-03-20 10:18:14.173 UTC | null | -1 | user670186 | 670,186 | null | 1 | 54 | python|excel|file|csv|xlsx | 191,948 | <p>Here's an example using <a href="https://xlsxwriter.readthedocs.io/" rel="noreferrer">xlsxwriter</a>:</p>
<pre><code>import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
</code></pre>
<p>FYI, there is also a package called <a href="http://pythonhosted.org/openpyxl/" rel="noreferrer">openpyxl</a>, that can read/write Excel 2007 xlsx/xlsm files.</p>
<p>Hope that helps.</p> |
41,773,667 | Android recyclerview adapter with multiple viewtype using databinding | <p>Is it possible to create a multiple view type in my adapter.. like adding a view for my header then below the header is a list.</p>
<p>code snippet of my adapter :</p>
<pre><code> public class StoreAdapter extends RecyclerView.Adapter<StoreAdapter.BindingHolder> {
List<Store> mStoreList;
public class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(View v) {
super(v);
binding = DataBindingUtil.bind(v);
}
public ViewDataBinding getBinding() {
return binding;
}
}
public StoreAdapter(List<Store> storeList) {
this.mStoreList = storeList;
}
@Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_store, parent, false);
BindingHolder holder = new BindingHolder(v);
return holder;
}
@Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Store store = mStoreList.get(position);
holder.getBinding().setVariable(BR.store, store);
holder.getBinding().executePendingBindings();
}
@Override
public int getItemCount() {
return mStoreList.size();
}
}
</code></pre>
<p>more details:</p>
<p>currently my adapter only supports 1 view type. Will it be possible to add another view type that can support databinding as well?</p> | 46,213,102 | 1 | 3 | null | 2017-01-20 22:54:02.8 UTC | 9 | 2020-06-27 01:53:12.32 UTC | 2020-06-27 01:53:12.32 UTC | null | 3,897,544 | null | 3,897,544 | null | 1 | 12 | android|android-studio|android-recyclerview|android-adapter|android-databinding | 9,300 | <p>It is possible to use several bindings in one ViewHolder.
Here is an example of the adapter with 2 types of items:</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private static final int CELL_TYPE_HEADER = 0;
private static final int CELL_TYPE_REGULAR_ITEM = 1;
class MyViewHolder extends RecyclerView.ViewHolder {
private HeaderBinding headerBinding;
private RegularItemBinding regularItemBinding;
MyViewHolder(HeaderBinding binding) {
super(binding.getRoot());
headerBinding = binding;
}
MyViewHolder(RegularItemBinding binding) {
super(binding.getRoot());
regularItemBinding = binding;
}
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
ViewDataBinding binding;
switch (viewType) {
case CELL_TYPE_HEADER:
binding = DataBindingUtil.inflate(inflater, R.layout.header, parent, false);
return new MyViewHolder((HeaderBinding) binding);
case CELL_TYPE_REGULAR_ITEM:
binding = DataBindingUtil.inflate(inflater, R.layout.regular_item, parent, false);
return new MyViewHolder((RegularItemBinding) binding);
}
return null;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MyViewModel viewModel = new MyViewModel(getItem(position));
switch (holder.getItemViewType()) {
case CELL_TYPE_HEADER:
HeaderBinding headerBinding = holder.headerBinding;
viewModel.setSomething(...);
headerBinding.setViewModel(viewModel);
break;
case CELL_TYPE_REGULAR_ITEM:
RegularItemBinding regularItemBinding = holder.regularItemBinding;
viewModel.setSomething(...);
regularItemBinding.setViewModel(viewModel);
break;
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return CELL_TYPE_HEADER;
} else {
return CELL_TYPE_REGULAR_ITEM;
}
}
}
</code></pre> |
35,992,681 | Android Fingerprint API Encryption and Decryption | <p>I am using the Android M Fingerprint API to allow users to login to the application. To do this I would need to store the username and password on the device. Currently I have the login working, as well as the Fingerprint API, but the username and password are both stored as plaintext. I would like to encrypt the password before I store it, and be able to retrieve it after the user authenticates with their fingerprint.</p>
<p>I am having a great amount of difficulty getting this to work. I have been trying to apply what I can from the <a href="http://developer.android.com/samples/security.html" rel="noreferrer">Android Security samples</a>, but each example seems to only handle encryption or signing, and never decryption.</p>
<p>What I have so far is that I have to obtain an instance of the <code>AndroidKeyStore</code>, a <code>KeyPairGenerator</code> and a <code>Cipher</code>, using asymmetric cryptography to allow the use of the Android <a href="http://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.Builder.html#setUserAuthenticationRequired(boolean)" rel="noreferrer"><code>KeyGenParameterSpec.Builder().setUserAuthenticationRequired(true)</code></a>. The reason for asymmetric cryptography is because the <code>setUserAuthenticationRequired</code> method will block <em>any</em> use of the key if the user is not authenticated, but:</p>
<blockquote>
<p>This authorization applies only to secret key and private key operations. Public key operations are not restricted.</p>
</blockquote>
<p>This should allow me to encrypt the password using the public key before the user authenticates with their fingerprint, then decrypt using the private key only after the user is authenticated.</p>
<pre><code>public KeyStore getKeyStore() {
try {
return KeyStore.getInstance("AndroidKeyStore");
} catch (KeyStoreException exception) {
throw new RuntimeException("Failed to get an instance of KeyStore", exception);
}
}
public KeyPairGenerator getKeyPairGenerator() {
try {
return KeyPairGenerator.getInstance("EC", "AndroidKeyStore");
} catch(NoSuchAlgorithmException | NoSuchProviderException exception) {
throw new RuntimeException("Failed to get an instance of KeyPairGenerator", exception);
}
}
public Cipher getCipher() {
try {
return Cipher.getInstance("EC");
} catch(NoSuchAlgorithmException | NoSuchPaddingException exception) {
throw new RuntimeException("Failed to get an instance of Cipher", exception);
}
}
private void createKey() {
try {
mKeyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")
.setUserAuthenticationRequired(true)
.build());
mKeyPairGenerator.generateKeyPair();
} catch(InvalidAlgorithmParameterException exception) {
throw new RuntimeException(exception);
}
}
private boolean initCipher(int opmode) {
try {
mKeyStore.load(null);
if(opmode == Cipher.ENCRYPT_MODE) {
PublicKey key = mKeyStore.getCertificate(KEY_ALIAS).getPublicKey();
mCipher.init(opmode, key);
} else {
PrivateKey key = (PrivateKey) mKeyStore.getKey(KEY_ALIAS, null);
mCipher.init(opmode, key);
}
return true;
} catch (KeyPermanentlyInvalidatedException exception) {
return false;
} catch(KeyStoreException | CertificateException | UnrecoverableKeyException
| IOException | NoSuchAlgorithmException | InvalidKeyException
| InvalidAlgorithmParameterException exception) {
throw new RuntimeException("Failed to initialize Cipher", exception);
}
}
private void encrypt(String password) {
try {
initCipher(Cipher.ENCRYPT_MODE);
byte[] bytes = mCipher.doFinal(password.getBytes());
String encryptedPassword = Base64.encodeToString(bytes, Base64.NO_WRAP);
mPreferences.getString("password").set(encryptedPassword);
} catch(IllegalBlockSizeException | BadPaddingException exception) {
throw new RuntimeException("Failed to encrypt password", exception);
}
}
private String decryptPassword(Cipher cipher) {
try {
String encryptedPassword = mPreferences.getString("password").get();
byte[] bytes = Base64.decode(encryptedPassword, Base64.NO_WRAP);
return new String(cipher.doFinal(bytes));
} catch (IllegalBlockSizeException | BadPaddingException exception) {
throw new RuntimeException("Failed to decrypt password", exception);
}
}
</code></pre>
<p>To be honest, I am not sure if any of this is right, it is bits and pieces from anything I could find on the subject. Everything I change throws a different exception, and this particular build does not run because I cannot instantiate the <code>Cipher</code>, it throws a <code>NoSuchAlgorithmException: No provider found for EC</code>. I have tried switch to <code>RSA</code> as well, but I get similar errors.</p>
<p>So my question is basically this; how can I encrypt plaintext on Android, and make it available for decryption after the user is authenticated by the Fingerprint API? </p>
<hr>
<p>I have made some progress, mostly due to the discovery of the information on the <a href="http://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html" rel="noreferrer"><code>KeyGenParameterSpec</code></a> documentation page.</p>
<p>I have kept <code>getKeyStore</code>, <code>encryptePassword</code>, <code>decryptPassword</code>, <code>getKeyPairGenerator</code> and <code>getCipher</code> mostly the same, but I changed the <code>KeyPairGenerator.getInstance</code> and <code>Cipher.getInstance</code> to <code>"RSA"</code> and <code>"RSA/ECB/OAEPWithSHA-256AndMGF1Padding"</code> respectively. </p>
<p>I also changed the rest of the code to RSA instead of Elliptic Curve, because from what I understand, Java 1.7 (and therefore Android) does not support encryption and decryption with EC. I changed my <code>createKeyPair</code> method based on the "RSA key pair for encryption/decryption using RSA OAEP" example on the documentation page:</p>
<pre><code>private void createKeyPair() {
try {
mKeyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setUserAuthenticationRequired(true)
.build());
mKeyPairGenerator.generateKeyPair();
} catch(InvalidAlgorithmParameterException exception) {
throw new RuntimeException(exception);
}
}
</code></pre>
<p>I also altered my <code>initCipher</code> method based on the <strong>known issue</strong> in the <code>KeyGenParameterSpec</code> documentation:</p>
<blockquote>
<p>A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be enforced even for public keys. To work around this issue extract the public key material to use outside of Android Keystore.</p>
</blockquote>
<pre><code>private boolean initCipher(int opmode) {
try {
mKeyStore.load(null);
if(opmode == Cipher.ENCRYPT_MODE) {
PublicKey key = mKeyStore.getCertificate(KEY_ALIAS).getPublicKey();
PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm())
.generatePublic(new X509EncodedKeySpec(key.getEncoded()));
mCipher.init(opmode, unrestricted);
} else {
PrivateKey key = (PrivateKey) mKeyStore.getKey(KEY_ALIAS, null);
mCipher.init(opmode, key);
}
return true;
} catch (KeyPermanentlyInvalidatedException exception) {
return false;
} catch(KeyStoreException | CertificateException | UnrecoverableKeyException
| IOException | NoSuchAlgorithmException | InvalidKeyException
| InvalidAlgorithmParameterException exception) {
throw new RuntimeException("Failed to initialize Cipher", exception);
}
}
</code></pre>
<p>Now I can encrypt the password, and save the encrypted password. But when I obtain the encrypted password and attempt to decrypt, I get a <code>KeyStoreException</code> <strong>Unknown error</strong>...</p>
<pre><code>03-15 10:06:58.074 14702-14702/com.example.app E/LoginFragment: Failed to decrypt password
javax.crypto.IllegalBlockSizeException
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:486)
at javax.crypto.Cipher.doFinal(Cipher.java:1502)
at com.example.app.ui.fragment.util.LoginFragment.onAuthenticationSucceeded(LoginFragment.java:251)
at com.example.app.ui.controller.FingerprintCallback.onAuthenticationSucceeded(FingerprintCallback.java:21)
at android.support.v4.hardware.fingerprint.FingerprintManagerCompat$Api23FingerprintManagerCompatImpl$1.onAuthenticationSucceeded(FingerprintManagerCompat.java:301)
at android.support.v4.hardware.fingerprint.FingerprintManagerCompatApi23$1.onAuthenticationSucceeded(FingerprintManagerCompatApi23.java:96)
at android.hardware.fingerprint.FingerprintManager$MyHandler.sendAuthenticatedSucceeded(FingerprintManager.java:805)
at android.hardware.fingerprint.FingerprintManager$MyHandler.handleMessage(FingerprintManager.java:757)
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.security.KeyStoreException: Unknown error
at android.security.KeyStore.getKeyStoreException(KeyStore.java:632)
at android.security.keystore.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:224)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:473)
at javax.crypto.Cipher.doFinal(Cipher.java:1502)
at com.example.app.ui.fragment.util.LoginFragment.onAuthenticationSucceeded(LoginFragment.java:251)
at com.example.app.ui.controller.FingerprintCallback.onAuthenticationSucceeded(FingerprintCallback.java:21)
at android.support.v4.hardware.fingerprint.FingerprintManagerCompat$Api23FingerprintManagerCompatImpl$1.onAuthenticationSucceeded(FingerprintManagerCompat.java:301)
at android.support.v4.hardware.fingerprint.FingerprintManagerCompatApi23$1.onAuthenticationSucceeded(FingerprintManagerCompatApi23.java:96)
at android.hardware.fingerprint.FingerprintManager$MyHandler.sendAuthenticatedSucceeded(FingerprintManager.java:805)
at android.hardware.fingerprint.FingerprintManager$MyHandler.handleMessage(FingerprintManager.java:757)
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> | 36,021,145 | 1 | 3 | null | 2016-03-14 16:17:45.027 UTC | 19 | 2017-06-13 11:55:10.747 UTC | 2016-03-15 14:35:18.727 UTC | null | 5,115,932 | null | 5,115,932 | null | 1 | 42 | android|encryption|android-keystore|android-fingerprint-api | 16,161 | <p>I found the final piece of the puzzle on the <a href="https://code.google.com/p/android/issues/detail?id=197719">Android Issue Tracker</a>, another known bug causes the unrestricted <code>PublicKey</code> to be incompatible with the <code>Cipher</code> when using OAEP. The work around is to add a new <code>OAEPParameterSpec</code> to the <code>Cipher</code> upon initialization:</p>
<pre><code>OAEPParameterSpec spec = new OAEPParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
mCipher.init(opmode, unrestricted, spec);
</code></pre>
<p>Below is the final code:</p>
<pre><code>public KeyStore getKeyStore() {
try {
return KeyStore.getInstance("AndroidKeyStore");
} catch (KeyStoreException exception) {
throw new RuntimeException("Failed to get an instance of KeyStore", exception);
}
}
public KeyPairGenerator getKeyPairGenerator() {
try {
return KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
} catch(NoSuchAlgorithmException | NoSuchProviderException exception) {
throw new RuntimeException("Failed to get an instance of KeyPairGenerator", exception);
}
}
public Cipher getCipher() {
try {
return Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
} catch(NoSuchAlgorithmException | NoSuchPaddingException exception) {
throw new RuntimeException("Failed to get an instance of Cipher", exception);
}
}
private void createKeyPair() {
try {
mKeyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setUserAuthenticationRequired(true)
.build());
mKeyPairGenerator.generateKeyPair();
} catch(InvalidAlgorithmParameterException exception) {
throw new RuntimeException("Failed to generate key pair", exception);
}
}
private boolean initCipher(int opmode) {
try {
mKeyStore.load(null);
if(opmode == Cipher.ENCRYPT_MODE) {
PublicKey key = mKeyStore.getCertificate(KEY_ALIAS).getPublicKey();
PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm())
.generatePublic(new X509EncodedKeySpec(key.getEncoded()));
OAEPParameterSpec spec = new OAEPParameterSpec(
"SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
mCipher.init(opmode, unrestricted, spec);
} else {
PrivateKey key = (PrivateKey) mKeyStore.getKey(KEY_ALIAS, null);
mCipher.init(opmode, key);
}
return true;
} catch (KeyPermanentlyInvalidatedException exception) {
return false;
} catch(KeyStoreException | CertificateException | UnrecoverableKeyException
| IOException | NoSuchAlgorithmException | InvalidKeyException
| InvalidAlgorithmParameterException exception) {
throw new RuntimeException("Failed to initialize Cipher", exception);
}
}
private void encrypt(String password) {
try {
initCipher(Cipher.ENCRYPT_MODE);
byte[] bytes = mCipher.doFinal(password.getBytes());
String encrypted = Base64.encodeToString(bytes, Base64.NO_WRAP);
mPreferences.getString("password").set(encrypted);
} catch(IllegalBlockSizeException | BadPaddingException exception) {
throw new RuntimeException("Failed to encrypt password", exception);
}
}
private String decrypt(Cipher cipher) {
try {
String encoded = mPreferences.getString("password").get();
byte[] bytes = Base64.decode(encoded, Base64.NO_WRAP);
return new String(cipher.doFinal(bytes));
} catch (IllegalBlockSizeException | BadPaddingException exception) {
throw new RuntimeException("Failed to decrypt password", exception);
}
}
</code></pre> |
19,189,132 | SSRS Expression Divide by Zero Error | <p>I have a tablix box that has a division expression. When dividing by zero or nulls I get <code>#Error</code> displayed in my report. I tried to create an <code>IIF</code> statement and tested with static values. This verified my syntax was correct but I still see the error on my reports. </p>
<p><img src="https://i.stack.imgur.com/bAl3d.jpg" alt="Report Preview"></p>
<p><code>=IIF(Sum(Fields!CY_Dollars.Value)=0, 0, (Sum(Fields!CY_Dollars.Value) - Sum(Fields!PY_Dollars.Value))/(Sum(Fields!PY_Dollars.Value)))</code></p>
<p>So I'm taking Current year dollars, subtracting Previous year dollars, and dividing that total by previous year dollars to get the percentage change. Is there a trick to this that I'm not getting?!</p> | 19,216,804 | 4 | 2 | null | 2013-10-04 19:19:07.047 UTC | 10 | 2022-08-25 15:10:55.12 UTC | 2015-12-03 05:16:17.82 UTC | null | 1,156,018 | null | 2,769,128 | null | 1 | 19 | reporting-services|ssrs-tablix|ssrs-expression | 60,962 | <p>You can add a function to your report code that handles the divide by zero condition, this makes it a bit easier to implement in multiple cells, e.g.</p>
<pre><code>Public Function Divider (ByVal Dividend As Double, ByVal Divisor As Double)
If IsNothing(Divisor) Or Divisor = 0
Return 0
Else
Return Dividend/Divisor
End If
End Function
</code></pre>
<p>You can then call this in a cell like so:</p>
<pre><code>=Code.Divider(Fields!FieldA.Value, Fields!FieldB.Value)
</code></pre> |
40,149,983 | move the position of bootstrap datepicker | <p><a href="https://i.stack.imgur.com/a9qAT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a9qAT.png" alt="enter image description here"></a>Can I able to move the datepicker near the calender icon ??? Any fix for this would be appreciated. datepicker is generated dynamically. </p>
<blockquote>
<p>I have given id to div</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/dMwrJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dMwrJ.png" alt="enter image description here"></a></p>
<pre><code><div class="datepick col-sm-6">
<div class='input-group date' id='datetimepicker1' >
<input type='text' class="form-control" placeholder="Select Start Date"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<script>
$('#datetimepicker1').datepicker({
autoclose: true,
startDate: '-0m',
todayHighlight: true
}).on('changeDate', function(ev){
$('#sDate1').text($('#datetimepicker1').data('date'));
$('#datetimepicker1').datepicker('hide');
});
</script>
</code></pre>
<p><a href="https://i.stack.imgur.com/P9bav.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P9bav.png" alt="enter image description here"></a></p> | 40,150,775 | 5 | 3 | null | 2016-10-20 09:04:48.19 UTC | 1 | 2018-04-19 11:39:06.34 UTC | 2016-10-20 09:29:59.947 UTC | null | 4,469,398 | null | 4,469,398 | null | 1 | 8 | html|css|bootstrap-modal | 52,279 | <p>What you need is little bit of jquery</p>
<p>see <a href="https://jsfiddle.net/3L4gc6fy/1/" rel="noreferrer">here</a></p>
<p>JQuery</p>
<pre><code>$('#datetimepicker1').click(function(){
var popup =$(this).offset();
var popupTop = popup.top - 40;
$('.ui-datepicker').css({
'top' : popupTop
});
});
</code></pre>
<p>About positioning of datepicker read <a href="https://stackoverflow.com/questions/662220/how-to-change-the-pop-up-position-of-the-jquery-datepicker-control">here</a></p> |
27,464,287 | What is the difference between await Task<T> and Task<T>.Result? | <pre><code>public async Task<string> GetName(int id)
{
Task<string> nameTask = Task.Factory.StartNew(() => string.Format("Name matching id {0} = Developer", id));
return nameTask.Result;
}
</code></pre>
<p>In above method return statement I am using the <code>Task<T>.Result</code> property.</p>
<pre><code>public async Task<string> GetName(int id)
{
Task<string> nameTask = Task.Factory.StartNew(() => string.Format("Name matching id {0} = Developer", id));
return await nameTask;
}
</code></pre>
<p>Here I am using <code>await Task<T></code>. I wont be wrong if I think that await will release the calling thread but <code>Task<T>.Result</code> will block it, would it be right?</p> | 27,466,042 | 2 | 4 | null | 2014-12-13 22:26:33.4 UTC | 29 | 2021-01-29 16:14:41.887 UTC | 2021-01-29 16:14:41.887 UTC | null | 141,397 | null | 1,039,644 | null | 1 | 75 | c#|multithreading|async-await | 14,464 | <blockquote>
<p>I wont be wrong if I think that await will release the calling thread but Task.Result will block it, would it be right?</p>
</blockquote>
<p>Generally, yes. <code>await task;</code> will "yield" the current thread. <code>task.Result</code> will block the current thread. <code>await</code> is an asynchronous wait; <code>Result</code> is a blocking wait.</p>
<p>There's another more minor difference: if the task completes in a faulted state (i.e., with an exception), then <code>await</code> will (re-)raise that exception as-is, but <code>Result</code> will wrap the exception in an <code>AggregateException</code>.</p>
<p>As a side note, avoid <code>Task.Factory.StartNew</code>. It's almost never the correct method to use. If you need to execute work on a background thread, prefer <code>Task.Run</code>.</p>
<p>Both <code>Result</code> and <code>StartNew</code> are appropriate if you are doing <a href="http://msdn.microsoft.com/en-us/library/ff963551.aspx">dynamic task parallelism</a>; otherwise, they should be avoided. Neither is appropriate if you are doing <a href="http://msdn.microsoft.com/en-us/library/hh873175.aspx">asynchronous programming</a>.</p> |
5,102,847 | How to call a method of super.super? | <p>I want to call a method of super class of a super class, without breaking the inheritance chain. Something like this:</p>
<pre><code>+(id) alloc
{
return [super.super alloc];
}
</code></pre>
<p>Is there a way to achieve this ?</p>
<p>Do not confuse with behavior offering by <code>superclass</code> method, discussed <a href="https://stackoverflow.com/questions/5085349/aclass-superclass-superclass-construction">here</a>.</p>
<hr>
<p><strong>UPD:</strong></p>
<p>A few words about <code>super</code> and <code>superclass</code> differences.</p>
<p>Lets say, we have <code>AClass</code> and <code>SuperAClass</code>. As follows from their names <code>AClass</code> inherits <code>SuperAClass</code>. Each of them has an implementation of a method <code>-(void) foo;</code></p>
<p><code>AClass</code> implements <strong>one of</strong> the following class methods:</p>
<p><strong>1. superclass:</strong></p>
<pre><code>+(id) alloc {
return [[self superclass] alloc];
}
</code></pre>
<p><strong>2. super:</strong></p>
<pre><code>+(id) alloc {
return [super alloc];
}
</code></pre>
<p>Now, suppose these 2 lines of code:</p>
<pre><code>AClass *AClassInstance = [AClass alloc];
[AClassInstance foo];
</code></pre>
<p>In first case (using superclass), <code>SuperAClass</code>'s <code>foo</code> method will be called.
For the second case (using super), <code>AClass</code>'s <code>foo</code> method will be called.</p> | 5,103,286 | 2 | 8 | null | 2011-02-24 09:42:34.59 UTC | 8 | 2014-10-01 21:32:30.77 UTC | 2017-05-23 10:29:50.873 UTC | null | -1 | null | 572,416 | null | 1 | 30 | objective-c|cocoa|cocoa-touch|ios | 11,705 | <p>In your particular example, <code>+superclass</code> is actually the way to go:</p>
<pre><code>+ (id)someClassMethod {
return [[[self superclass] superclass] someClassMethod];
}
</code></pre>
<p>since it is a class method, hence <code>self</code> refers to the class object where <code>+someClassMethod</code> is being defined.</p>
<p>On the other hand, things get a tad more complicated in instance methods. One solution is to get a pointer to the method implementation in the supersuper (grandparent) class. For instance:</p>
<pre><code>- (id)someInstanceMethod {
Class granny = [[self superclass] superclass];
IMP grannyImp = class_getMethodImplementation(granny, _cmd);
return grannyImp(self, _cmd);
}
</code></pre>
<p>Similarly to the class method example, <code>+superclass</code> is sent twice to obtain the supersuperclass. <code>IMP</code> is a pointer to a method, and we obtain an IMP to the method whose name is the same as the current one (<code>-someInstaceMethod</code>) but pointing to the implementation in the supersuperclass, and then call it. Note that you’d need to tweak this in case there are method arguments and return values different from <code>id</code>.</p> |
1,147,497 | C# List<T>.ToArray performance is bad? | <p>I'm using .Net 3.5 (C#) and I've heard the performance of C# <code>List<T>.ToArray</code> is "bad", since it memory copies for all elements to form a new array. Is that true?</p> | 1,147,510 | 7 | 1 | null | 2009-07-18 13:06:18.417 UTC | 8 | 2019-08-23 07:33:20.17 UTC | 2015-05-01 12:35:46 UTC | null | 2,246,344 | null | 63,235 | null | 1 | 33 | c#|.net|performance|memory | 40,082 | <p>No that's not true. Performance is good since all it does is memory copy all elements (*) to form a new array.</p>
<p>Of course it depends on what you define as "good" or "bad" performance.</p>
<p>(*) references for reference types, values for value types.</p>
<p><strong>EDIT</strong></p>
<p>In response to your comment, using Reflector is a good way to check the implementation (see below). Or just think for a couple of minutes about how you would implement it, and take it on trust that Microsoft's engineers won't come up with a worse solution.</p>
<pre><code>public T[] ToArray()
{
T[] destinationArray = new T[this._size];
Array.Copy(this._items, 0, destinationArray, 0, this._size);
return destinationArray;
}
</code></pre>
<p>Of course, "good" or "bad" performance only has a meaning relative to some alternative. If in your specific case, there is an alternative technique to achieve your goal that is measurably faster, then you can consider performance to be "bad". If there is no such alternative, then performance is "good" (or "good enough").</p>
<p><strong>EDIT 2</strong></p>
<p>In response to the comment: "No re-construction of objects?" :</p>
<p>No reconstruction for reference types. For value types the values are copied, which could loosely be described as reconstruction.</p> |
89,741 | Can I see the currently checked out revision number in Tortoise SVN? | <p>I'd like to know what the currently checked out revision number is for a file or directory. Is there a way to do this in TortoiseSVN on Windows ?</p> | 89,811 | 7 | 0 | null | 2008-09-18 03:27:50.613 UTC | 3 | 2019-04-17 13:48:13.303 UTC | 2014-06-30 09:37:32.163 UTC | Xenph Yan | 761,095 | Adam Pierce | 5,324 | null | 1 | 79 | svn|version-control|tortoisesvn | 42,962 | <p>Right-click on the working directory in windows explorer, and select "Properties" (Not TortoiseSVN->Properties). You will see the Properties dialog, which will have a tab called "Subversion". Click on it, and you will see the version number, and other info.</p> |
866,061 | conditional unique constraint | <p>I have a situation where i need to enforce a unique constraint on a set of columns, but only for one value of a column.</p>
<p>So for example I have a table like Table(ID, Name, RecordStatus).</p>
<p>RecordStatus can only have a value 1 or 2 (active or deleted), and I want to create a unique constraint on (ID, RecordStatus) only when RecordStatus = 1, since I don't care if there are multiple deleted records with the same ID.</p>
<p>Apart from writing triggers, can I do that?</p>
<p>I am using SQL Server 2005.</p> | 866,100 | 7 | 2 | null | 2009-05-14 21:57:06.52 UTC | 22 | 2021-08-03 03:23:38.083 UTC | 2016-11-23 22:19:06.283 UTC | null | 3,303,195 | null | 64,668 | null | 1 | 105 | sql|sql-server|sql-server-2005 | 67,830 | <p>Add a check constraint like this. The difference is, you'll return false if Status = 1 and Count > 0.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms188258.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms188258.aspx</a></p>
<pre><code>CREATE TABLE CheckConstraint
(
Id TINYINT,
Name VARCHAR(50),
RecordStatus TINYINT
)
GO
CREATE FUNCTION CheckActiveCount(
@Id INT
) RETURNS INT AS BEGIN
DECLARE @ret INT;
SELECT @ret = COUNT(*) FROM CheckConstraint WHERE Id = @Id AND RecordStatus = 1;
RETURN @ret;
END;
GO
ALTER TABLE CheckConstraint
ADD CONSTRAINT CheckActiveCountConstraint CHECK (NOT (dbo.CheckActiveCount(Id) > 1 AND RecordStatus = 1));
INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2);
INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2);
INSERT INTO CheckConstraint VALUES (1, 'No Problems', 2);
INSERT INTO CheckConstraint VALUES (1, 'No Problems', 1);
INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 1);
INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 2);
-- Msg 547, Level 16, State 0, Line 14
-- The INSERT statement conflicted with the CHECK constraint "CheckActiveCountConstraint". The conflict occurred in database "TestSchema", table "dbo.CheckConstraint".
INSERT INTO CheckConstraint VALUES (2, 'Oh no!', 1);
SELECT * FROM CheckConstraint;
-- Id Name RecordStatus
-- ---- ------------ ------------
-- 1 No Problems 2
-- 1 No Problems 2
-- 1 No Problems 2
-- 1 No Problems 1
-- 2 Oh no! 1
-- 2 Oh no! 2
ALTER TABLE CheckConstraint
DROP CONSTRAINT CheckActiveCountConstraint;
DROP FUNCTION CheckActiveCount;
DROP TABLE CheckConstraint;
</code></pre> |
730,621 | Do DDL statements always give you an implicit commit, or can you get an implicit rollback? | <p>If you're halfway through a transaction and perform a DDL statement, such as truncating a table, then the transaction commits.</p>
<p>I was wondering whether this was always the case and by definition, or is there a setting hidden somewhere that would <em>rollback</em> the transaction instead of committing.</p>
<p>Thanks.</p>
<p><strong>Edit to clarify...</strong></p>
<p>I'm not looking to rollback after a truncate. I just want to confirm that statements already carried out are <em>absolutely always</em> going to be committed before a DDL. Just want to make sure there isn't a system property somewhere that someone could set to wreck my code.</p>
<p>I understand the need to commit before and after a DDL, but conceptually I'd have thought the same consistency requirement <em>could</em> be achieved with a rollback before the DDL and a commit after.</p> | 731,229 | 8 | 0 | null | 2009-04-08 15:49:22.327 UTC | 8 | 2018-10-23 15:29:55.557 UTC | 2018-03-13 15:58:00.41 UTC | null | 5,070,879 | null | 4,003 | null | 1 | 20 | sql|oracle|transactions|ddl | 49,383 | <p>No, it will always commit.</p>
<p>If you want to rollback, you'll have to do it before the DDL.</p>
<p>If you want to isolate the DDL from your existing transaction, then you will have to execute it in its' own, separate transaction.</p> |
1,289,061 | Best way to use PHP to encrypt and decrypt passwords? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5089841/php-2-way-encryption-i-need-to-store-passwords-that-can-be-retrieved">PHP 2-way encryption: I need to store passwords that can be retrieved</a> </p>
</blockquote>
<p>I plan to store foreign account information for my users on my website, aka rapidshare username and passwords, etc... I want to keep information secure, but I know that if I hash their information, I can't retrieve it for later use. </p>
<p>Base64 is decrypt-able so there's no point using that just plain off.
My idea is to scramble the user and pass before and after it gets base64ed that way even after you decrypt it, you get some funny looking text if you try to decrypt. Is there a php function that accepts values that will make an unique scramble of a string and de-scramble it later when the value is reinputed?</p>
<p>Any suggestions?</p> | 1,289,114 | 8 | 3 | null | 2009-08-17 16:39:02.723 UTC | 189 | 2016-02-15 08:21:15.293 UTC | 2017-05-23 11:33:17.083 UTC | null | -1 | null | 140,337 | null | 1 | 219 | php|mcrypt|encryption|scramble | 304,906 | <p><strong>You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. <a href="https://stackoverflow.com/a/6337021/2224584">This answer explains how to properly implement password hashing in PHP</a>.</strong> Still, here is how you would encrypt/decrypt:</p>
<pre><code>$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
</code></pre>
<p><strong>To Encrypt:</strong></p>
<pre><code>$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
</code></pre>
<p><strong>To Decrypt:</strong></p>
<pre><code>$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
</code></pre>
<hr>
<p><strong>Warning</strong>: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. <a href="https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly" rel="noreferrer">You should <em>not</em> rely on unauthenticated encryption for security</a>, especially since the code as provided is vulnerable to padding oracle attacks.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/a/30189841/2224584">https://stackoverflow.com/a/30189841/2224584</a></li>
<li><a href="https://stackoverflow.com/a/30166085/2224584">https://stackoverflow.com/a/30166085/2224584</a></li>
<li><a href="https://stackoverflow.com/a/30159120/2224584">https://stackoverflow.com/a/30159120/2224584</a></li>
</ul>
<p>Also, don't just use a "password" for an encryption key. <strong>Encryption keys are random strings.</strong></p>
<hr>
<p><a href="http://3v4l.org/CJfSn" rel="noreferrer">Demo at 3v4l.org</a>:</p>
<pre><code>echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "
</code></pre> |
360,024 | How do I set a connection string config programmatically in .net? | <p>I'd like to set a connection string programmatically, with absolutely no change to any config files / registry keys.</p>
<p>I have this piece of code, but unfortunately it throws an exception with "the configuration is read only".</p>
<pre><code>ConfigurationManager.ConnectionStrings.Clear();
string connectionString = "Server=myserver;Port=8080;Database=my_db;...";
ConnectionStringSettings connectionStringSettings =
new ConnectionStringSettings("MyConnectionStringKey", connectionString);
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);
</code></pre>
<p><strong>Edit:</strong>
The problem is that I have existing code that reads the connection string from the configuration. So setting the config string manually, or through a resource, don't seem like valid options. What I really need is a way to modify the configuration programmatically.</p> | 377,573 | 9 | 1 | null | 2008-12-11 16:44:53.467 UTC | 21 | 2019-04-15 16:57:13.507 UTC | 2017-03-23 15:39:16.727 UTC | ripper234 | 1,033,581 | ripper234 | 11,236 | null | 1 | 61 | .net|configuration|connection-string | 62,497 | <p>I've written about this in a <a href="http://davidgardiner.blogspot.com/2008/09/programmatically-setting.html" rel="noreferrer">post on my blog</a>. The trick is to use reflection to poke values in as a way to get access to the non-public fields (and methods).</p>
<p>eg.</p>
<pre><code>var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";
</code></pre> |
74,162 | How to do INSERT into a table records extracted from another table | <p>I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:</p>
<pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
</code></pre>
<p>I tried but get a syntax error message.</p>
<p>What would you do if you want to do this?</p> | 74,204 | 9 | 0 | null | 2008-09-16 16:19:55.923 UTC | 59 | 2016-04-15 05:08:15.197 UTC | 2008-09-16 16:26:20.977 UTC | Longhorn213 | 2,469 | Martin | 8,203 | null | 1 | 187 | sql|ms-access | 695,699 | <p>No "VALUES", no parenthesis:</p>
<pre><code>INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
</code></pre> |
384,089 | How should I pass an int into stringWithFormat? | <p>I am try to use stringWithFormat to set a numerical value on the text property of a label but the following code is not working. I cannot cast the int to NSString. I was expecting that the method would know how to automatically convert an int to NSString.</p>
<p>What do I need to do here?</p>
<pre><code>- (IBAction) increment: (id) sender
{
int count = 1;
label.text = [NSString stringWithFormat:@"%@", count];
}
</code></pre> | 384,090 | 10 | 0 | null | 2008-12-21 04:20:48.093 UTC | 9 | 2016-01-14 17:17:37.577 UTC | 2008-12-21 06:14:54.54 UTC | Jason Coco | 34,218 | Brennan | 10,366 | null | 1 | 69 | objective-c|cocoa-touch | 134,355 | <p>Do this:</p>
<pre><code>label.text = [NSString stringWithFormat:@"%d", count];
</code></pre> |
448,981 | Which characters are valid in CSS class names/selectors? | <p>What characters/symbols are allowed within the <strong>CSS</strong> class selectors?<br>
I know that the following characters are <em>invalid</em>, but what characters are <em>valid</em>?</p>
<pre><code>~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
</code></pre> | 449,000 | 11 | 6 | null | 2009-01-15 23:37:39.88 UTC | 212 | 2021-11-14 13:42:50.24 UTC | 2020-04-19 11:17:54.447 UTC | null | 806,202 | Darryl Hein | 5,441 | null | 1 | 1,309 | css|css-selectors | 435,972 | <p>You can check directly at the <a href="http://www.w3.org/TR/CSS21/grammar.html#scanner" rel="noreferrer">CSS grammar</a>.</p>
<p><em>Basically</em><sup>1</sup>, a name must begin with an underscore (<code>_</code>), a hyphen (<code>-</code>), or a letter(<code>a</code>–<code>z</code>), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must<sup>2</sup> be a letter or underscore, and the name must be at least 2 characters long.</p>
<pre><code>-?[_a-zA-Z]+[_a-zA-Z0-9-]*
</code></pre>
<p>In short, the previous rule translates to the following, extracted from the <a href="https://www.w3.org/TR/CSS21/syndata.html#characters" rel="noreferrer">W3C spec.</a>:</p>
<blockquote>
<p>In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, or a hyphen followed by a digit.
Identifiers can also contain escaped characters and any ISO 10646
character as a numeric code (see next item). For instance, the
identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".</p>
</blockquote>
<p>Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in <code>-moz-opacity</code>.</p>
<p><sup>1</sup> It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).</p>
<p><sup>2</sup> Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. <code>--indent1</code>, is invalid. However, I'm pretty sure I've seen this in practice.</p> |
584,134 | Should you use pointers (unsafe code) in C#? | <p>Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?</p> | 584,157 | 11 | 2 | null | 2009-02-24 23:35:40.463 UTC | 10 | 2020-04-30 18:35:37.153 UTC | 2020-04-30 18:35:37.153 UTC | null | 56,555 | Lucas Aardvark | 56,555 | null | 1 | 46 | c#|.net|pointers|coding-style|unsafe | 21,006 | <p>From "The Man" himself:</p>
<p>The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases:</p>
<ul>
<li>Dealing with existing structures on disk</li>
<li>Advanced COM or Platform Invoke scenarios that involve structures with pointers in them</li>
<li>Performance-critical code</li>
</ul>
<p>The use of unsafe context in other situations is discouraged. </p>
<p><strong>Specifically, an unsafe context should not be used to attempt to write C code in C#.</strong></p>
<p>Caution:</p>
<p>Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx" rel="noreferrer">Reference</a></p> |
918,792 | Use jQuery to change an HTML tag? | <p>Is this possible?</p>
<p>example:</p>
<pre><code>$('a.change').click(function(){
//code to change p tag to h5 tag
});
<p>Hello!</p>
<a id="change">change</a>
</code></pre>
<p>So clicking the change anchor should cause the <code><p>Hello!</p></code> section to change to (as an example) an h5 tag so you'd end up with <code><h5>Hello!</h5></code> after the click. I realize you can delete the p tag and replace it with an h5, but is there anyway to actually modify an HTML tag?</p> | 918,803 | 11 | 0 | null | 2009-05-28 01:28:18.453 UTC | 25 | 2022-04-10 10:03:26.73 UTC | null | null | null | null | 106,178 | null | 1 | 138 | jquery | 158,160 | <p>Once a dom element is created, the tag is immutable, I believe. You'd have to do something like this:</p>
<pre><code>$(this).replaceWith($('<h5>' + this.innerHTML + '</h5>'));
</code></pre> |
531,707 | What's the best way to write a parser by hand? | <p>We've used ANTLR to create a parser for a SQL-like grammar, and while the results are satisfactory in most cases, there are a few edge cases that we need to fix; and since we didn't write the parser ourselves we don't really understand it well enough to be able to make sensible changes.</p>
<p>So, we'd like to write our own parser. What's the best way to go about writing a parser by hand? What sort of parser should we use - recursive descent has been recommended; is that right? We'll be writing it in C#, so any tutorials for writing parsers in that language would be gratefully received.</p>
<p>UPDATE: I'd also be interested in answers that involve F# - I've been looking for a reason to use that in a project.</p> | 1,254,343 | 16 | 5 | null | 2009-02-10 09:49:19.993 UTC | 15 | 2010-03-11 14:05:12.257 UTC | 2009-08-04 08:23:46.2 UTC | null | 15,371 | Simon | 15,371 | null | 1 | 23 | c#|.net|parsing|f# | 10,896 | <p>I would highly recommend the F# language as your language of choice for parsing on the .NET Platform. It's roots in the ML family of languages means it has excellent support for language-oriented programming.</p>
<p>Discriminated unions and pattern-matching allow for a very succinct and powerful specification of your AST. Higher-order functions allow for definition of parse operations and their composition. First-class support for monadic types allows for state management to be handled implicitly greatly simplifying the composition of parsers. Powerful type-inference greatly aides the definition of these (complex) types. And all of this can be specified and executed interactively allowing you to rapidly prototype.</p>
<p>Stephan Tolksdorf has put this into practice with his parser combinator library <a href="http://www.quanttec.com/fparsec/" rel="noreferrer">FParsec</a></p>
<p>From his examples we see how naturally an AST is specified:</p>
<pre><code>type expr =
| Val of string
| Int of int
| Float of float
| Decr of expr
type stmt =
| Assign of string * expr
| While of expr * stmt
| Seq of stmt list
| IfThen of expr * stmt
| IfThenElse of expr * stmt * stmt
| Print of expr
type prog = Prog of stmt list
</code></pre>
<p>the implementation of the parser (partially elided) is just as succinct:</p>
<pre><code>let stmt, stmtRef = createParserForwardedToRef()
let stmtList = sepBy1 stmt (ch ';')
let assign =
pipe2 id (str ":=" >>. expr) (fun id e -> Assign(id, e))
let print = str "print" >>. expr |>> Print
let pwhile =
pipe2 (str "while" >>. expr) (str "do" >>. stmt) (fun e s -> While(e, s))
let seq =
str "begin" >>. stmtList .>> str "end" |>> Seq
let ifthen =
pipe3 (str "if" >>. expr) (str "then" >>. stmt) (opt (str "else" >>. stmt))
(fun e s1 optS2 ->
match optS2 with
| None -> IfThen(e, s1)
| Some s2 -> IfThenElse(e, s1, s2))
do stmtRef:= choice [ifthen; pwhile; seq; print; assign]
let prog =
ws >>. stmtList .>> eof |>> Prog
</code></pre>
<p>On the second line, as an example, <code>stmt</code> and <code>ch</code> are parsers and <code>sepBy1</code> is a monadic parser combinator that takes two simple parsers and returns a combination parser. In this case <code>sepBy1 p sep</code> returns a parser that parses one or more occurrences of <code>p</code> separated by <code>sep</code>. You can thus see how quickly a powerful parser can be combined from simple parsers. F#'s support for overridden operators also allow for concise infix notation e.g. the sequencing combinator and the choice combinator can be specified as <code>>>.</code> and <code><|></code>.</p>
<p>Best of luck,</p>
<p>Danny</p> |
439,056 | Is a view faster than a simple query? | <p>Is a </p>
<pre><code>select * from myView
</code></pre>
<p>faster than the query itself to create the view (in order to have the same resultSet):</p>
<pre><code>select * from ([query to create same resultSet as myView])
</code></pre>
<p>?</p>
<p>It's not totally clear to me if the view uses some sort of caching making it faster compared to a simple query. </p> | 439,061 | 17 | 1 | null | 2009-01-13 14:09:03.133 UTC | 134 | 2022-08-12 19:32:17.75 UTC | 2012-08-27 18:13:43.073 UTC | JohnIdol | 63,550 | JohnIdol | 1,311,500 | null | 1 | 422 | sql|sql-server|performance | 287,437 | <p><strong>Yes</strong>, views <em>can</em> have a clustered index assigned and, when they do, they'll store temporary results that can speed up resulting queries.</p>
<p>Microsoft's own documentation makes it very clear that Views can improve performance.</p>
<p>First, most views that people create are <em>simple</em> views and do not use this feature, and are therefore no different to querying the base tables directly. Simple views are expanded in place and so <strong>do not directly contribute to performance improvements</strong> - that much is true. <strong>However,</strong> indexed views can <em>dramatically</em> improve performance.</p>
<p>Let me go directly to the documentation:</p>
<blockquote>
<p>After a unique clustered index is created on the view, the view's result set is materialized immediately and persisted in physical storage in the database, saving the overhead of performing this costly operation at execution time.</p>
</blockquote>
<p>Second, these indexed views can work <em>even when they are not directly referenced by another query</em> as the optimizer will use them in place of a table reference when appropriate.</p>
<p>Again, the documentation:</p>
<blockquote>
<p>The indexed view can be used in a query execution in two ways. The query can reference the indexed view directly, or, more importantly, the query optimizer can select the view if it determines that the view can be substituted for some or all of the query in the lowest-cost query plan. In the second case, the indexed view is used instead of the underlying tables and their ordinary indexes. The view does not need to be referenced in the query for the query optimizer to use it during query execution. This allows existing applications to benefit from the newly created indexed views without changing those applications.</p>
</blockquote>
<p>This documentation, as well as charts demonstrating performance improvements, can be found <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx" rel="noreferrer">here</a>.</p>
<p><strong>Update 2:</strong> the answer has been criticized on the basis that it is the "index" that provides the performance advantage, not the "View." However, this is easily refuted.</p>
<p>Let us say that we are a software company in a small country; I'll use Lithuania as an example. We sell software worldwide and keep our records in a SQL Server database. We're very successful and so, in a few years, we have 1,000,000+ records. However, we often need to report sales for tax purposes and we find that we've only sold 100 copies of our software in our home country. By creating an indexed view of just the Lithuanian records, we get to keep the records we need in an indexed cache as described in the MS documentation. When we run our reports for Lithuanian sales in 2008, our query will search through an index with a depth of just 7 (Log2(100) with some unused leaves). If we were to do the same without the VIEW and just relying on an index into the table, we'd have to traverse an index tree with a search depth of 21!</p>
<p>Clearly, the View itself would provide us with a performance advantage (3x) over the simple use of the index alone. I've tried to use a real-world example but you'll note that a simple list of Lithuanian sales would give us an even greater advantage.</p>
<p>Note that I'm just using a straight b-tree for my example. While I'm fairly certain that SQL Server uses some variant of a b-tree, I don't know the details. Nonetheless, the point holds.</p>
<p><strong>Update 3:</strong> The question has come up about whether an Indexed View just uses an index placed on the underlying table. That is, to paraphrase: "an indexed view is just the equivalent of a standard index and it offers nothing new or unique to a view." If this was true, of course, then the above analysis would be incorrect! Let me provide a quote from the Microsoft documentation that demonstrate why I think this criticism is not valid or true:</p>
<blockquote>
<p>Using indexes to improve query performance is not a new concept; however, indexed views provide additional performance benefits that cannot be achieved using standard indexes.</p>
</blockquote>
<p>Together with the above quote regarding the persistence of data in physical storage and other information in the documentation about how indices are created on Views, I think it is safe to say that an Indexed View is <strong>not</strong> just a cached SQL Select that happens to use an index defined on the main table. Thus, I continue to stand by this answer.</p> |
119,506 | Virtual member call in a constructor | <p>I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. </p>
<p>Why would this be something not to do?</p> | 119,543 | 18 | 2 | null | 2008-09-23 07:11:30.337 UTC | 256 | 2020-09-11 00:04:55.577 UTC | 2018-04-27 08:52:19.58 UTC | null | 797,882 | JasonS | 1,865 | null | 1 | 1,431 | c#|constructor|warnings|resharper|virtual-functions | 205,082 | <p>When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (<a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two" rel="noreferrer">see Eric Lippert's blog for details as to why this is</a>).</p>
<p>Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.</p>
<p>When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called. </p>
<p>This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.</p> |
714,471 | How do I hide an element on a click event anywhere outside of the element? | <p>I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page. </p>
<pre><code>$(document).click(function (event) {
$('#myDIV:visible').hide();
});
</code></pre>
<p>The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.</p> | 714,608 | 21 | 0 | null | 2009-04-03 15:31:28.84 UTC | 32 | 2021-06-02 13:03:56.723 UTC | 2019-07-15 14:00:49.26 UTC | null | 2,756,409 | Franek | 86,785 | null | 1 | 124 | jquery|events|event-bubbling | 248,225 | <p>If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:</p>
<pre><code>$(document).click(function() {
alert("me");
});
$(".myDiv").click(function(e) {
e.stopPropagation(); // This is the preferred method.
return false; // This should not be used unless you do not want
// any click events registering inside the div
});
</code></pre>
<p>This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.</p> |
649,789 | What would be C++ limitations compared C language? | <p>Following are the benefits of C++</p>
<ul>
<li>C++ provides the specific features they are asking about</li>
<li>Their C compiler is almost certainly really a C++ compiler, so there are no software cost implications</li>
<li>C++ is just as portable as C</li>
<li>C++ code can be just as efficient as C (or more so, or less so)</li>
</ul>
<p>Are there any concrete reasons and specific scenarios, where one has to use C over C++?</p>
<p>Reference to this question:<a href="https://stackoverflow.com/questions/649649/library-for-generic-datatypes-in-c">Library for generics in C</a></p>
<p>Not a duplicate, because this question is asking about language limitations and not about should/shouldn't learn one language over another. </p>
<p><strong>Peter Kirkham's post was for me the most informative, particularly with regard to C99 issues which I hadn't considered, so I've accepted it. Thanks to all others who took part.</strong></p> | 650,533 | 31 | 11 | 2013-08-06 06:18:56.37 UTC | 2009-03-16 09:54:13.467 UTC | 55 | 2018-07-26 16:20:40.257 UTC | 2018-02-26 23:43:59.887 UTC | anon | 462,923 | anon | null | null | 1 | 120 | c++|c | 20,536 | <blockquote>
<p>This is prompted by a an answer I gave to a current question which asks about a generics library for C - the questioner specifically states that they do not want to use C++.</p>
</blockquote>
<p>C is a complete programming language. C is not an arbitrary subset of C++. C is not a subset of C++ at all. </p>
<p>This is valid C:</p>
<pre><code>foo_t* foo = malloc ( sizeof(foo_t) );
</code></pre>
<p>To make it compile as C++ you have to write:</p>
<pre><code>foo_t* foo = static_cast<foo_t*>( malloc ( sizeof(foo_t) ) );
</code></pre>
<p>which isn't valid C any more. (you could use the C-style cast, it which case it would compile in C, but be shunned by most C++ coding standards, and also by many C programmers; witness the "don't cast malloc" comments all over Stack Overflow).</p>
<hr>
<p>They are not the same language, and if you have an existing project in C you don't want to rewrite it in a different language just to use a library. You would prefer to use libraries which you can interface to in the language you are working in. (In some cases this is possible with a few <code>extern "C"</code> wrapper functions, depending on how template/inline a C++ library is.)</p>
<p>Taking the first C file in a project I'm working on, this is what happens if you just swap <code>gcc std=c99</code> for <code>g++</code>:</p>
<pre><code>sandiego:$ g++ -g -O1 -pedantic -mfpmath=sse -DUSE_SSE2 -DUSE_XMM3 -I src/core -L /usr/lib -DARCH=elf64 -D_BSD_SOURCE -DPOSIX -D_ISOC99_SOURCE -D_POSIX_C_SOURCE=200112L -Wall -Wextra -Wwrite-strings -Wredundant-decls -Werror -Isrc src/core/kin_object.c -c -o obj/kin_object.o | wc -l
In file included from src/core/kin_object.c:22:
src/core/kin_object.h:791:28: error: anonymous variadic macros were introduced in C99
In file included from src/core/kin_object.c:26:
src/core/kin_log.h:42:42: error: anonymous variadic macros were introduced in C99
src/core/kin_log.h:94:29: error: anonymous variadic macros were introduced in C99
...
cc1plus: warnings being treated as errors
src/core/kin_object.c:101: error: ISO C++ does not support the ‘z’ printf length modifier
..
src/core/kin_object.c:160: error: invalid conversion from ‘void*’ to ‘kin_object_t*’
..
src/core/kin_object.c:227: error: unused parameter ‘restrict’
..
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
</code></pre>
<p>In total 69 lines of errors, four of which are invalid conversions, but mostly for features that exist in C99 but not in C++.</p>
<p>It's not like I'm using those features for the fun of it. It would take significant work to port it to a different language.</p>
<p>So it is plain wrong to suggest that </p>
<blockquote>
<p>[a] C compiler is almost certainly really a C++ compiler, so there are no software cost implications </p>
</blockquote>
<p>There are often significant cost implications in porting existing C code to the procedural subset of C++.</p>
<p>So suggesting <em>'use the C++ std::queue class'</em> as an answer to question looking for an library implementation of a queue in C is dafter than suggesting <em>'use objective C'</em> and <em>'call the Java java.util.Queue class using JNI'</em> or <em>'call the CPython library'</em> - Objective C actually is a proper superset of C (including C99), and Java and CPython libraries both are callable directly from C without having to port unrelated code to the C++ language. </p>
<p>Of course you could supply a C façade to the C++ library, but once you're doing that C++ is no different to Java or Python. </p> |
6,758,841 | How can I find if a particular package exists on my Android device? | <p>How can I find whether a particular package or application, say: <code>com.android.abc</code>, exists on my Android device?</p> | 6,758,962 | 9 | 0 | null | 2011-07-20 08:07:34.493 UTC | 24 | 2022-04-18 09:13:39.27 UTC | 2017-08-30 09:39:21.983 UTC | null | 1,887,402 | null | 651,545 | null | 1 | 74 | android|android-applicationinfo | 52,191 | <p>Call any of the below method with the package name.</p>
<pre><code>import android.content.pm.PackageManager;
// ...
public boolean isPackageExisted(String targetPackage){
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if(packageInfo.packageName.equals(targetPackage))
return true;
}
return false;
}
</code></pre>
<hr>
<pre><code> import android.content.pm.PackageManager;
public boolean isPackageExisted(String targetPackage){
PackageManager pm=getPackageManager();
try {
PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}
</code></pre> |
7,008,189 | Calculate average in java | <p><strong>EDIT: I've written code for the average but I don't know how to make it so that it also uses <code>int</code>s from my <code>args.length</code> rather than the array.</strong></p>
<p>I need to write a java program that can calculate:</p>
<ol>
<li>the number of integers read in</li>
<li>the average value – which need not be an integer!</li>
</ol>
<p>NOTE: I don't want to calculate the average from the array but the integers in the <code>args</code>.</p>
<p>Currently I have written this:</p>
<pre><code>int count = 0;
for (int i = 0; i<args.length -1; ++i)
count++;
System.out.println(count);
}
int nums[] = new int[] { 23, 1, 5, 78, 22, 4};
double result = 0; //average will have decimal point
for(int i=0; i < nums.length; i++){
result += nums[i];
}
System.out.println(result/count)
</code></pre>
<p>Can anyone guide me in the right direction? Or give an example that guides me in the right way to shape this code?</p>
<p>Thanks in advance.</p> | 7,008,265 | 10 | 5 | null | 2011-08-10 08:56:42.023 UTC | 1 | 2021-03-06 11:52:35.88 UTC | 2021-03-06 11:52:35.88 UTC | null | 2,164,365 | null | 885,460 | null | 1 | 4 | java|for-loop|count|average | 150,846 | <p>Just some minor modification to your code will do (with some var renaming for clarity) :</p>
<pre><code>double sum = 0; //average will have decimal point
for(int i=0; i < args.length; i++){
//parse string to double, note that this might fail if you encounter a non-numeric string
//Note that we could also do Integer.valueOf( args[i] ) but this is more flexible
sum += Double.valueOf( args[i] );
}
double average = sum/args.length;
System.out.println(average );
</code></pre>
<p>Note that the loop can also be simplified:</p>
<pre><code>for(String arg : args){
sum += Double.valueOf( arg );
}
</code></pre>
<p>Edit: the OP seems to want to use the <code>args</code> array. This seems to be a String array, thus updated the answer accordingly.</p>
<p><strong>Update</strong>:</p>
<p>As zoxqoj correctly pointed out, integer/double overflow is not taken care of in the code above. Although I assume the input values will be small enough to not have that problem, here's a snippet to use for really large input values:</p>
<pre><code>BigDecimal sum = BigDecimal.ZERO;
for(String arg : args){
sum = sum.add( new BigDecimal( arg ) );
}
</code></pre>
<p>This approach has several advantages (despite being somewhat slower, so don't use it for time critical operations):</p>
<ul>
<li>Precision is kept, with double you will gradually loose precision with the number of math operations (or not get exact precision at all, depending on the numbers)</li>
<li>The probability of overflow is practically eliminated. Note however, that a <code>BigDecimal</code> might be bigger than what fits into a <code>double</code> or <code>long</code>.</li>
</ul> |
6,543,174 | How can I parse UTC date/time (String) into something more readable? | <p>I have a String of a date and time like this: <code>2011-04-15T20:08:18Z</code>. I don't know much about date/time formats, but I think, and correct me if I'm wrong, that's its UTC format. </p>
<p>My question: what's the easiest way to parse this to a more normal format, in Java?</p> | 6,543,193 | 10 | 3 | null | 2011-07-01 03:04:02.323 UTC | 14 | 2021-06-30 09:52:02.023 UTC | null | null | null | null | 479,180 | null | 1 | 59 | java | 120,094 | <p>What you have is an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer">ISO-8601</a> date format which means you can just use <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html" rel="nofollow noreferrer">SimpleDateFormat</a></p>
<pre><code>DateFormat m_ISO8601Local = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
m_ISO8601Local.setTimeZone(TimeZone.getTimeZone("UTC"));
</code></pre>
<p>And then you can just use <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html#parse%28java.lang.String,%20java.text.ParsePosition%29" rel="nofollow noreferrer">SimpleDateFormat.parse()</a>. Also, here is a <a href="https://web.archive.org/web/20180711023953/http://developer.marklogic.com:80/learn/2004-09-dates" rel="nofollow noreferrer">blog post</a> with some examples that might help.</p> |
6,459,398 | jQuery get html of container including the container itself | <p>How do i get the html on '#container' including '#container' and not just what's inside it. </p>
<pre><code><div id="container">
<div id="one">test 1 </div>
<div id="two">test 2 </div>
<div id="three">test 3 </div>
<div id="four">test 4 </div>
</div>
</code></pre>
<p>I have this which gets the html inside #container. it does not include the #container element itself. That's what i'm looking to do</p>
<pre><code>var x = $('#container').html();
$('#save').val(x);
</code></pre>
<p>Check <a href="http://jsfiddle.net/rzfPP/58/" rel="noreferrer">http://jsfiddle.net/rzfPP/58/</a></p> | 6,459,969 | 10 | 2 | null | 2011-06-23 19:12:02.28 UTC | 34 | 2019-08-26 12:35:24.24 UTC | 2011-06-23 19:14:48.813 UTC | null | 558,592 | null | 635,300 | null | 1 | 173 | javascript|jquery | 110,088 | <p>If you wrap the container in a dummy <code>P</code> tag you will get the container HTML also.</p>
<p>All you need to do is </p>
<pre><code>var x = $('#container').wrap('<p/>').parent().html();
</code></pre>
<p><strong>Check working example at <a href="http://jsfiddle.net/rzfPP/68/" rel="noreferrer">http://jsfiddle.net/rzfPP/68/</a></strong></p>
<p>To <code>unwrap()</code>the <code><p></code> tag when done, you can add </p>
<pre><code>$('#container').unwrap();
</code></pre> |
6,722,936 | Python argparse: Make at least one argument required | <p>I've been using <code>argparse</code> for a Python program that can <code>-process</code>, <code>-upload</code> or both:</p>
<pre><code>parser = argparse.ArgumentParser(description='Log archiver arguments.')
parser.add_argument('-process', action='store_true')
parser.add_argument('-upload', action='store_true')
args = parser.parse_args()
</code></pre>
<p>The program is meaningless without at least one parameter. How can I configure <code>argparse</code> to force at least one parameter to be chosen?</p>
<p><strong>UPDATE:</strong></p>
<p>Following the comments: What's the Pythonic way to parametrize a program with at least one option?</p> | 6,723,066 | 13 | 3 | null | 2011-07-17 09:24:12.007 UTC | 18 | 2022-06-06 15:22:24.637 UTC | 2019-01-24 22:11:13.273 UTC | null | 9,216,858 | null | 51,197 | null | 1 | 116 | python|argparse | 65,048 | <pre><code>if not (args.process or args.upload):
parser.error('No action requested, add -process or -upload')
</code></pre> |
6,619,377 | How to get whole and decimal part of a number? | <p>Given, say, 1.25 - how do I get "1" and ."25" parts of this number? </p>
<p>I need to check if the decimal part is .0, .25, .5, or .75.</p> | 6,619,392 | 20 | 5 | null | 2011-07-08 02:31:27.65 UTC | 20 | 2021-10-22 00:41:45.937 UTC | 2011-07-08 02:35:26.323 UTC | null | 31,671 | null | 253,976 | null | 1 | 122 | php|math | 177,377 | <pre><code>$n = 1.25;
$whole = floor($n); // 1
$fraction = $n - $whole; // .25
</code></pre>
<p>Then compare against 1/4, 1/2, 3/4, etc.</p>
<hr>
<p>In cases of negative numbers, use this:</p>
<pre><code>function NumberBreakdown($number, $returnUnsigned = false)
{
$negative = 1;
if ($number < 0)
{
$negative = -1;
$number *= -1;
}
if ($returnUnsigned){
return array(
floor($number),
($number - floor($number))
);
}
return array(
floor($number) * $negative,
($number - floor($number)) * $negative
);
}
</code></pre>
<p>The <code>$returnUnsigned</code> stops it from making <strong>-1.25</strong> in to <strong>-1</strong> & <strong>-0.25</strong></p> |
38,240,015 | How to use `setResultTransformer` after Hibernate 5.2? | <p>I wanna use <code>query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)</code> to get a <code>List<Map></code>. But I got a exception: </p>
<pre><code>java.lang.NoSuchMethodError: org.hibernate.query.Query.setResultTransformer(Lorg/hibernate/transform/ResultTransformer;)Lorg/hibernate/Query;
</code></pre>
<p>I can't find the implemented class of <code>org.hibernate.query.Query</code>.
The method <code>setResultTransformer</code> is in <code>org.hibernate.Query</code>.</p>
<p>And why is the org.hibernate.Query deprecated?</p> | 42,980,747 | 4 | 1 | null | 2016-07-07 07:41:50.01 UTC | 6 | 2021-11-17 19:35:44.013 UTC | 2016-07-07 08:00:19.07 UTC | null | 1,634,827 | null | 1,634,827 | null | 1 | 36 | java|hibernate | 33,106 | <blockquote>
<p>The ResultTransformer comes with a legacy definition which is not following the Functional Interface syntax. Hence, we cannot use a lambda in this example. Hibernate 6.0 aims to overcome this issue, so that’s why the Hibernate ORM 5.2 ResultTransformer is deprecated. Nevertheless, an alternative will be provided, so the concept we are discussing in this article is going to stand still even in Hibernate 6.</p>
</blockquote>
<p><a href="https://vladmihalcea.com/why-you-should-use-the-hibernate-resulttransformer-to-customize-result-set-mappings/" rel="noreferrer">https://vladmihalcea.com/why-you-should-use-the-hibernate-resulttransformer-to-customize-result-set-mappings/</a></p> |
45,594,432 | Android Room SQLite_ERROR no such table | <p>I'm trying my hand at using <a href="https://developer.android.com/topic/libraries/architecture/room.html" rel="noreferrer">Android Room</a> and after following <a href="http://www.vogella.com/tutorials/AndroidSQLite/article.html" rel="noreferrer">this tutorial</a> I'm getting the following error when i try to build the app:</p>
<p><code>Error:(23, 27) error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such table: screen_items)</code></p>
<p>The name is fine and should exist. After making my changes I cleaned the project and made sure it was completely uninstalled from the device.</p>
<p>In my <code>Activity</code> I'm initialising the things in <code>onCreate</code> with this line:</p>
<pre><code>db = AppDatabase.getDatabase(getApplicationContext());
</code></pre>
<p>Here is my code:</p>
<p><strong>AppDatabase</strong></p>
<pre><code>@Database(entities = {PermitItem.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
public static String DATABASE_NAME = "my_database";
public final static String TABLE_ITEMS = "screen_items";
private static AppDatabase INSTANCE;
public abstract PermitItemDao permitItemModel();
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context, AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
</code></pre>
<p><strong>PermitItem</strong></p>
<pre><code>@Entity
public class PermitItem {
@PrimaryKey(autoGenerate = true)
public final int id;
private String posX, posY, width, height, content, type;
public PermitItem(int id, String posX, String posY, String width, String height, String content, String type) {
this.id = id;
this.posX = posX;
this.posY = posY;
this.width = width;
this.height = height;
this.content = content;
this.type = type;
}
public static PermitItemBuilder builder(){
return new PermitItemBuilder();
}
public static class PermitItemBuilder{
int id;
String posX, posY, width, height, content, type;
public PermitItemBuilder setId(int id) {
this.id = id;
return this;
}
public PermitItemBuilder setPosX(String posX) {
this.posX = posX;
return this;
}
public PermitItemBuilder setPosY(String posY) {
this.posY = posY;
return this;
}
public PermitItemBuilder setWidth(String width) {
this.width = width;
return this;
}
public PermitItemBuilder setHeight(String height) {
this.height = height;
return this;
}
public PermitItemBuilder setContent(String content) {
this.content = content;
return this;
}
public PermitItemBuilder setType(String type) {
this.type = type;
return this;
}
public PermitItem build() {
return new PermitItem(id, posX, posY, width, height, content, type);
}
}
public long getId() {
return id;
}
public String getPosX() {
return posX;
}
public void setPosX(String posX) {
this.posX = posX;
}
public String getPosY() {
return posY;
}
public void setPosY(String posY) {
this.posY = posY;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "PermitItem{" +
"id=" + id +
", posX='" + posX + '\'' +
", posY='" + posY + '\'' +
", width='" + width + '\'' +
", height='" + height + '\'' +
", content='" + content + '\'' +
", type='" + type + '\'' +
'}';
}
}
</code></pre>
<p><strong>PermitItemDao</strong></p>
<pre><code>@Dao
public interface PermitItemDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long addPermitItem(PermitItem permitItem);
@Query("select * from " + TABLE_ITEMS)
ArrayList<PermitItem> getAllPermitItems();
@Query("select * from " + TABLE_ITEMS + " where id = :id")
PermitItem getPermitItemById(int id);
@Update(onConflict = OnConflictStrategy.REPLACE)
void updatePermitItem(PermitItem permitItem);
@Query("delete from " + TABLE_ITEMS)
void removeAllPermitItems();
}
</code></pre> | 45,595,042 | 6 | 4 | null | 2017-08-09 15:08:53.903 UTC | 5 | 2020-01-29 19:44:10.657 UTC | 2017-08-09 15:14:49.44 UTC | null | 1,636,266 | null | 1,636,266 | null | 1 | 61 | android|sqlite|dao|android-room | 29,365 | <p>Room names tables the same as their associated entities. In your DAO, <code>TABLE_ITEMS</code> needs to be <code>PermitItem</code>, because your entity is <code>PermitItem</code>. Or, add the <code>tableName</code> property to the <code>@Entity</code> annotation, to tell Room some other name to use for the table.</p> |
15,865,024 | Accessing CouchDB Futon on a remote server | <p>I've installed CouchDB on a remote server that I have access to through a terminal telnet/ssh client.</p>
<p>The server is running on CentOS6.</p>
<p>I really want to be able to work with Futon, but I cannot at the moment because I can only open localhost:5984 in the ssh client.</p>
<p>Any suggestions on how to work around this?</p> | 15,865,347 | 1 | 0 | null | 2013-04-07 16:52:20.133 UTC | 10 | 2013-04-09 13:26:48.683 UTC | 2013-04-07 16:59:39.353 UTC | null | 1,163,278 | null | 1,163,278 | null | 1 | 18 | ssh|couchdb|telnet | 6,881 | <p>Just create ssh tunnel to your remote CouchDB instance:</p>
<pre><code>ssh -f -L localhost:15984:127.0.0.1:5984 user@remote_host -N
</code></pre>
<p>And after that your remote CouchDB Futon that still serve on localhost address will be available for you by address: <code>http://localhost:15984/_utils</code>. Replace local port 15984 by your choice. </p>
<p>P.S. There is also <a href="http://library.linode.com/databases/couchdb/ssh-tunnel">awesome guide</a> from Linode wiki with example couchdb-tunnel script. Hope it helps.</p> |
15,920,360 | php code to validate alphanumeric string | <p>I want to validate alphanumeric string in form text box in php. It can contain numbers and special characters like '.' and '-' but the string should not contain only numbers and special characters. Please help with the code.</p> | 15,920,865 | 4 | 6 | null | 2013-04-10 08:10:43.23 UTC | 2 | 2019-02-06 13:15:10.063 UTC | 2013-04-10 13:15:12.42 UTC | null | 1,329,126 | null | 2,247,888 | null | 1 | 19 | php|regex|character | 47,658 | <p>Try this</p>
<pre><code>// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
// Valid
} else {
// Invalid
}
</code></pre> |
15,687,332 | Bluetooth LE RSSI for proximity detection iOS | <p>I'll start with the question. </p>
<p>Is the BTLE RSSI a good way to indicate two devices proximity to each other or not? does it only work with small devices like fobs etc?</p>
<p><strong>The Issue:</strong></p>
<p>I am currently looking at making an app that will use BTLE and allow connections based on proximity. In this regard it is much like the demo app that apple show in the Advanced Core Bluetooth keynote (When two devices are almost touching they then connect).</p>
<p>As I understand it the proximity is determined based on the RSSI value when the central discovers the peripheral. When I try this however with two iPads the signal seems too strong for this it is also too inconsistent to have an accurate stab at the proximity as it doesn't show very much correlation to the devices proximity.</p>
<p>I have tried the Apple sample code and that is similar in that the devices don't have to be close at all for the information to pass from one to another.</p>
<p>If only there was a way to reduce the signal strength of the peripheral devices advertisement....</p>
<p>Thanks in advance for any help.</p> | 17,021,642 | 4 | 0 | null | 2013-03-28 16:35:21.623 UTC | 19 | 2015-10-02 09:39:01.373 UTC | null | null | null | null | 568,741 | null | 1 | 33 | iphone|ios|ipad|core-bluetooth|bluetooth-lowenergy | 21,593 | <p>The experience of Matthew Griffin matches mine. However - when we can measure for a fair period of time two things have helped us calibrate this better.</p>
<p>We did have to wrap a simple (kalman) filter on the antenna orientation and the IMU to get a rough running commentary though - and this is not very CPU or battery light.</p>
<ul>
<li>Using the IMU you get a fair idea of the distance/direction of travel - and if this is over a short period of time - we assume the other 'side' is stationary. This helps a lot to get a value for 'current' orientation and 'callibrate current environment noise.</li>
<li>Likewise - do the same for rotations/position changes.</li>
</ul>
<p>We've found that in general a re-orientation of the device is a better way to get direction; and that distance is only reliable some up to some 30 to 600 seconds after a 'move' calibration' and only if the device is not too much rotated. And in practice once needs some 4-5 'other' devices; ideally not too mobile, to keep oneself dynamically calibrated.</p>
<p>However the converse is quite reliable - i.e. we know when not to measure. And the net result is that one can fairly well ascertain things like 'at the keyboard' and 'relocated'/moved away through a specific door/openning or direction. Likewise measuring a field by randomly dancing through the room; changing orientation a lot - does work well once the receiver antenna lobes got somewhat worked out after a stationary period.</p> |
15,894,182 | Wrong math with Python? | <p>Just starting out with Python, so this is probably my mistake, but...</p>
<p>I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials.</p>
<p>I ran into something weird today. I wanted to find out 2013*2013, but I wrote the wrong thing and wrote 2013*013, and got this:</p>
<pre><code>>>> 2013*013
22143
</code></pre>
<p>I checked with my calculator, and 22143 is the wrong answer! 2013 * 13 is supposed to be 26169.</p>
<p>Why is Python giving me a wrong answer? My old Casio calculator doesn't do this...</p> | 15,894,199 | 4 | 10 | null | 2013-04-09 05:46:40.893 UTC | 5 | 2019-11-16 18:19:17.567 UTC | 2019-11-16 18:19:17.567 UTC | null | 674,039 | null | 2,174,862 | null | 1 | 78 | python|python-2.7|math | 4,998 | <p>Because of octal arithmetic, 013 is actually the integer 11. </p>
<pre><code>>>> 013
11
</code></pre>
<p>With a leading zero, <code>013</code> is interpreted as a base-8 number and 1*8<sup>1</sup> + 3*8<sup>0</sup> = 11. </p>
<p>Note: this behaviour was <a href="http://docs.python.org/release/3.0.1/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax" rel="noreferrer">changed in python 3</a>. Here is a particularly appropriate quote from <a href="http://www.python.org/dev/peps/pep-3127/" rel="noreferrer">PEP 3127</a></p>
<blockquote>
<p>The default octal representation of integers is silently confusing to
people unfamiliar with C-like languages. It is extremely easy to
inadvertently create an integer object with the wrong value, because
'013' means 'decimal 11', not 'decimal 13', to the Python language
itself, which is not the meaning that most humans would assign to this
literal.</p>
</blockquote> |
15,600,499 | How to pass parameters correctly? | <p>I am a C++ beginner but not a programming beginner.
I'm trying to learn C++(c++11) and it's kinda unclear for me the most important thing: passing parameters.</p>
<p>I considered these simple examples:</p>
<ul>
<li><p>A class that has all its members primitive types:<br>
<code>CreditCard(std::string number, int expMonth, int expYear,int pin):number(number), expMonth(expMonth), expYear(expYear), pin(pin)</code></p></li>
<li><p>A class that has as members primitive types + 1 complex type:<br>
<code>Account(std::string number, float amount, CreditCard creditCard) : number(number), amount(amount), creditCard(creditCard)</code></p></li>
<li><p>A class that has as members primitive types + 1 collection of some complex type:
<code>Client(std::string firstName, std::string lastName, std::vector<Account> accounts):firstName(firstName), lastName(lastName), accounts(accounts)</code></p></li>
</ul>
<p>When I create an account, I do this: </p>
<pre><code> CreditCard cc("12345",2,2015,1001);
Account acc("asdasd",345, cc);
</code></pre>
<p>Obviously the credit card will be copied twice in this scenario.
If I rewrite that constructor as</p>
<pre><code>Account(std::string number, float amount, CreditCard& creditCard)
: number(number)
, amount(amount)
, creditCard(creditCard)
</code></pre>
<p>there will be one copy.
If I rewrite it as</p>
<pre><code>Account(std::string number, float amount, CreditCard&& creditCard)
: number(number)
, amount(amount)
, creditCard(std::forward<CreditCard>(creditCard))
</code></pre>
<p>There will be 2 moves and no copy.</p>
<p>I think sometimes you may want to copy some parameter, sometimes you don't want to copy when you create that object.<br>
I come from C# and, being used to references, it's a bit strange to me and I think there should be 2 overloads for each parameter but I know I am wrong.<br>
Are there any best practices of how to send parameters in C++ because I really find it, let's say, not trivial. How would you handle my examples presented above?</p> | 15,600,615 | 5 | 5 | null | 2013-03-24 15:44:06.813 UTC | 85 | 2017-11-03 21:12:04.727 UTC | 2017-11-03 21:12:04.727 UTC | null | 3,885,376 | null | 1,993,683 | null | 1 | 114 | c++|c++11 | 10,718 | <p><strong>THE MOST IMPORTANT QUESTION FIRST:</strong></p>
<blockquote>
<p>Are there any best practices of how to send parameters in C++ because I really find it, let's say, not trivial</p>
</blockquote>
<p>If your function needs to <strong>modify</strong> the original object being passed, so that after the call returns, modifications to that object will be visible to the caller, then you should pass by <strong>lvalue reference</strong>:</p>
<pre><code>void foo(my_class& obj)
{
// Modify obj here...
}
</code></pre>
<p>If your function <strong>does not need to modify the original object, and does not need to create a copy of it</strong> (in other words, it only needs to observe its state), then you should pass by <strong>lvalue reference to <code>const</code></strong>:</p>
<pre><code>void foo(my_class const& obj)
{
// Observe obj here
}
</code></pre>
<p>This will allow you to call the function both with lvalues (lvalues are objects with a stable identity) and with rvalues (rvalues are, for instance <em>temporaries</em>, or objects you're about to move from as the result of calling <code>std::move()</code>).</p>
<p>One could also argue that <strong>for fundamental types or types for which copying is fast</strong>, such as <code>int</code>, <code>bool</code>, or <code>char</code>, there is no need to pass by reference if the function simply needs to observe the value, and <strong>passing by value should be favored</strong>. That is correct if <em>reference semantics</em> is not needed, but what if the function wanted to store a pointer to that very same input object somewhere, so that future reads through that pointer will see the value modifications that have been performed in some other part of the code? In this case, passing by reference is the correct solution.</p>
<p>If your function <strong>does not need to modify the original object, but needs to store a copy of that object</strong> (<em>possibly to return the result of a transformation of the input without altering the input</em>), then you could consider <strong>taking by value</strong>:</p>
<pre><code>void foo(my_class obj) // One copy or one move here, but not working on
// the original object...
{
// Working on obj...
// Possibly move from obj if the result has to be stored somewhere...
}
</code></pre>
<p>Invoking the above function will always result in one copy when passing lvalues, and in one moves when passing rvalues. If your function needs to store this object somewhere, you could perform an additional <em>move</em> from it (for instance, in the case <code>foo()</code> is <a href="https://stackoverflow.com/questions/14197526/should-all-most-setter-functions-in-c11-be-written-as-function-templates-accep">a member function that needs to store the value in a data member</a>). </p>
<p><strong>In case moves are expensive</strong> for objects of type <code>my_class</code>, then you may consider overloading <code>foo()</code> and provide one version for lvalues (accepting an lvalue reference to <code>const</code>) and one version for rvalues (accepting an rvalue reference):</p>
<pre><code>// Overload for lvalues
void foo(my_class const& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = obj; // Copy!
// Working on copyOfObj...
}
// Overload for rvalues
void foo(my_class&& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = std::move(obj); // Move!
// Notice, that invoking std::move() is
// necessary here, because obj is an
// *lvalue*, even though its type is
// "rvalue reference to my_class".
// Working on copyOfObj...
}
</code></pre>
<p>The above functions are so similar, in fact, that you could make one single function out of it: <code>foo()</code> could become a function <em>template</em> and you could use <strong>perfect forwarding</strong> for determining whether a move or a copy of the object being passed will be internally generated:</p>
<pre><code>template<typename C>
void foo(C&& obj) // No copy, no move (just reference binding)
// ^^^
// Beware, this is not always an rvalue reference! This will "magically"
// resolve into my_class& if an lvalue is passed, and my_class&& if an
// rvalue is passed
{
my_class copyOfObj = std::forward<C>(obj); // Copy if lvalue, move if rvalue
// Working on copyOfObj...
}
</code></pre>
<p>You may want to learn more about this design by watching <a href="http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Scott-Meyers-Universal-References-in-Cpp11" rel="noreferrer">this talk by Scott Meyers</a> (just mind the fact that the term "<em>Universal References</em>" that he is using is non-standard).</p>
<p>One thing to keep in mind is that <code>std::forward</code> will usually end up in a <em>move</em> for rvalues, so even though it looks relatively innocent, forwarding the same object multiple times may be a source of troubles - for instance, moving from the same object twice! So be careful not to put this in a loop, and not to forward the same argument multiple times in a function call:</p>
<pre><code>template<typename C>
void foo(C&& obj)
{
bar(std::forward<C>(obj), std::forward<C>(obj)); // Dangerous!
}
</code></pre>
<p>Also notice, that you normally do not resort to the template-based solution unless you have a good reason for it, as it makes your code harder to read. <strong>Normally, you should focus on clarity and simplicity</strong>.</p>
<p>The above are just simple guidelines, but most of the time they will point you towards good design decisions.</p>
<hr>
<p><strong>CONCERNING THE REST OF YOUR POST:</strong></p>
<blockquote>
<p>If i rewrite it as [...] there will be 2 moves and no copy.</p>
</blockquote>
<p>This is not correct. To begin with, an rvalue reference cannot bind to an lvalue, so this will only compile when you are passing an rvalue of type <code>CreditCard</code> to your constructor. For instance:</p>
<pre><code>// Here you are passing a temporary (OK! temporaries are rvalues)
Account acc("asdasd",345, CreditCard("12345",2,2015,1001));
CreditCard cc("12345",2,2015,1001);
// Here you are passing the result of std::move (OK! that's also an rvalue)
Account acc("asdasd",345, std::move(cc));
</code></pre>
<p>But it won't work if you try to do this:</p>
<pre><code>CreditCard cc("12345",2,2015,1001);
Account acc("asdasd",345, cc); // ERROR! cc is an lvalue
</code></pre>
<p>Because <code>cc</code> is an lvalue and rvalue references cannot bind to lvalues. Moreover, <strong>when binding a reference to an object, no move is performed</strong>: it's just a reference binding. Thus, there will only be <em>one</em> move.</p>
<hr>
<p>So based on the guidelines provided in the first part of this answer, if you are concerned with the number of moves being generated when you take a <code>CreditCard</code> by value, you could define two constructor overloads, one taking an lvalue reference to <code>const</code> (<code>CreditCard const&</code>) and one taking an rvalue reference (<code>CreditCard&&</code>).</p>
<p>Overload resolution will select the former when passing an lvalue (in this case, one copy will be performed) and the latter when passing an rvalue (in this case, one move will be performed). </p>
<pre><code>Account(std::string number, float amount, CreditCard const& creditCard)
: number(number), amount(amount), creditCard(creditCard) // copy here
{ }
Account(std::string number, float amount, CreditCard&& creditCard)
: number(number), amount(amount), creditCard(std::move(creditCard)) // move here
{ }
</code></pre>
<hr>
<p>Your usage of <code>std::forward<></code> is normally seen when you want to achieve <em>perfect forwarding</em>. In that case, your constructor would actually be a constructor <em>template</em>, and would look more or less as follows</p>
<pre><code>template<typename C>
Account(std::string number, float amount, C&& creditCard)
: number(number), amount(amount), creditCard(std::forward<C>(creditCard)) { }
</code></pre>
<p>In a sense, this combines both the overloads I've shown previously into one single function: <code>C</code> will be deduced to be <code>CreditCard&</code> in case you are passing an lvalue, and due to the reference collapsing rules, it will cause this function to be instantiated:</p>
<pre><code>Account(std::string number, float amount, CreditCard& creditCard) :
number(num), amount(amount), creditCard(std::forward<CreditCard&>(creditCard))
{ }
</code></pre>
<p>This will cause a <em>copy-construction</em> of <code>creditCard</code>, as you would wish. On the other hand, when an rvalue is passed, <code>C</code> will be deduced to be <code>CreditCard</code>, and this function will be instantiated instead:</p>
<pre><code>Account(std::string number, float amount, CreditCard&& creditCard) :
number(num), amount(amount), creditCard(std::forward<CreditCard>(creditCard))
{ }
</code></pre>
<p>This will cause a <em>move-construction</em> of <code>creditCard</code>, which is what you want (because the value being passed is an rvalue, and that means we are authorized to move from it).</p> |
32,952,051 | MySQL indexing and Using filesort | <p>This related to my <a href="https://stackoverflow.com/questions/32922983/mysql-indexes-what-are-the-best-practices-according-to-this-table-and-queries">last problem</a>. I made a new two columns in the listings table, one for composed views <code>views_point</code> (increment every 100 view) and one for publish on date <code>publishedon_hourly</code> (by year-month-day hour only) to make some unique values.</p>
<p>This is my new table:</p>
<pre><code>CREATE TABLE IF NOT EXISTS `listings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type` tinyint(1) NOT NULL DEFAULT '1',
`hash` char(32) NOT NULL,
`source_id` int(10) unsigned NOT NULL,
`link` varchar(255) NOT NULL,
`short_link` varchar(255) NOT NULL,
`cat_id` mediumint(5) NOT NULL,
`title` mediumtext NOT NULL,
`description` mediumtext,
`content` mediumtext,
`images` mediumtext,
`videos` mediumtext,
`views` int(10) unsigned NOT NULL DEFAULT '0',
`views_point` int(10) unsigned NOT NULL DEFAULT '0',
`comments` int(11) DEFAULT '0',
`comments_update` int(11) NOT NULL DEFAULT '0',
`editor_id` int(11) NOT NULL DEFAULT '0',
`auther_name` varchar(255) DEFAULT NULL,
`createdby_id` int(10) NOT NULL,
`createdon` int(20) NOT NULL,
`editedby_id` int(10) NOT NULL,
`editedon` int(20) NOT NULL,
`deleted` tinyint(1) NOT NULL,
`deletedon` int(20) NOT NULL,
`deletedby_id` int(10) NOT NULL,
`deletedfor` varchar(255) NOT NULL,
`published` tinyint(1) NOT NULL DEFAULT '1',
`publishedon` int(11) unsigned NOT NULL,
`publishedon_hourly` int(10) unsigned NOT NULL DEFAULT '0',
`publishedby_id` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `hash` (`hash`),
KEY `views_point` (`views_point`),
KEY `listings` (`publishedon_hourly`,`published`,`cat_id`,`source_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED AUTO_INCREMENT=365513 ;
</code></pre>
<p>When I run a query like this:</p>
<pre><code>SELECT *
FROM listings
WHERE (`publishedon_hourly` BETWEEN
UNIX_TIMESTAMP( '2015-09-5 00:00:00' )
AND UNIX_TIMESTAMP( '2015-10-5 12:00:00' ))
AND (published =1)
AND cat_id IN ( 1, 2, 3, 4, 5 )
ORDER BY by `views_point` DESC
LIMIT 10
</code></pre>
<p>It is working great and this the explanation:
<a href="https://i.stack.imgur.com/nVSbO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nVSbO.png" alt="enter image description here"></a></p>
<p>But when I change the date range from month to day like this:</p>
<pre><code>SELECT *
FROM listings
WHERE (`publishedon_hourly` BETWEEN
UNIX_TIMESTAMP( '2015-09-5 00:00:00' )
AND UNIX_TIMESTAMP( '2015-09-5 12:00:00' ))
AND (published =1)
AND cat_id IN ( 1, 2, 3, 4, 5 )
ORDER BY `views_point` DESC
LIMIT 10
</code></pre>
<p>Then the query becomes slow and the filesort appears. Any one know the reason and how can I fix it?</p>
<p>the data sample (from the slow query)</p>
<pre><code>INSERT INTO `listings` (`id`, `type`, `hash`, `source_id`, `link`, `short_link`, `cat_id`, `title`, `description`, `content`, `images`, `videos`, `views`, `views_point`, `comments`, `comments_update`, `editor_id`, `auther_name`, `createdby_id`, `createdon`, `editedby_id`, `editedon`, `deleted`, `deletedon`, `deletedby_id`, `deletedfor`, `published`, `publishedon`, `publishedon_hourly`, `publishedby_id`) VALUES
(94189, 1, '44a46d128ce730c72927b19c445ab26e', 8, 'http://Larkin.com/sapiente-laboriosam-omnis-tempore-aliquam-qui-nobis', '', 5, 'And Alice was more and.', 'So they got settled down again very sadly and quietly, and.', 'Dormouse. ''Fourteenth of March, I think it so quickly that the Gryphon only answered ''Come on!'' and ran the faster, while more and more sounds of broken glass, from which she concluded that it was looking down at them, and then a voice sometimes choked with sobs, to sing this:-- ''Beautiful Soup, so rich and green, Waiting in a natural way. ''I thought you did,'' said the Dormouse, without considering at all what had become of it; and as it.', NULL, '', 200, 19700, 0, 0, 0, 'Max', 0, 1441442729, 0, 0, 0, 0, 0, '', 1, 1441442729, 1441440000, 0),
(19030, 1, '3438f6a555f2ce7fdfe03cee7a52882a', 3, 'http://Romaguera.com/voluptatem-rerum-quia-sed', '', 2, 'Dodo said, ''EVERYBODY.', 'I wish I hadn''t to bring but one; Bill''s got the.', 'I wonder what they''ll do well enough; don''t be particular--Here, Bill! catch hold of this remark, and thought to herself. (Alice had no idea what Latitude or Longitude I''ve got to the confused clamour of the other queer noises, would change to dull reality--the grass would be offended again. ''Mine is a long way. So she went on. ''I do,'' Alice said nothing; she had succeeded in curving it down ''important,'' and some were birds,) ''I suppose so,''.', NULL, '', 800, 19400, 0, 0, 0, 'Antonio', 0, 1441447567, 0, 0, 0, 0, 0, '', 1, 1441447567, 1441447200, 0),
(129247, 4, '87d2029a300d8b4314508786eb620a24', 10, 'http://Ledner.com/', '', 4, 'I ever saw one that.', 'The Cat seemed to be a person of authority among them,.', 'I BEG your pardon!'' she exclaimed in a natural way again. ''I wonder what was the same height as herself; and when she looked down at her feet as the question was evidently meant for her. ''I can tell you my history, and you''ll understand why it is I hate cats and dogs.'' It was all dark overhead; before her was another long passage, and the blades of grass, but she had sat down a very little! Besides, SHE''S she, and I''m sure I have dropped them, I wonder?'' As she said to herself; ''his eyes are so VERY tired of being all alone here!'' As she said to itself ''Then I''ll go round a deal.', NULL, '', 1000, 19100, 0, 0, 0, 'Drake', 0, 1441409756, 0, 0, 0, 0, 0, '', 1, 1441409756, 1441407600, 0),
(264582, 2, '5e44fe417f284f42c3b10bccd9c89b14', 8, 'http://www.Dietrich.info/laboriosam-quae-eaque-aut-dolorem', '', 2, 'Alice asked in a very.', 'THINK; or is it directed to?'' said the Mock Turtle,.', 'I can listen all day to such stuff? Be off, or I''ll have you executed.'' The miserable Hatter dropped his teacup and bread-and-butter, and then unrolled the parchment scroll, and read as follows:-- ''The Queen will hear you! You see, she came upon a little of the players to be lost, as she spoke--fancy CURTSEYING as you''re falling through the wood. ''It''s the stupidest tea-party I.', NULL, '', 800, 18700, 0, 0, 0, 'Kevin', 0, 1441441192, 0, 0, 0, 0, 0, '', 1, 1441441192, 1441440000, 0),
(44798, 1, '567cc77ba88c05a4a805dc667816a30c', 14, 'http://www.Hintz.com/distinctio-nulla-quia-incidunt-facere-reprehenderit-sapiente-sint.html', '', 5, 'The Cat seemed to Alice.', 'And the moral of that is--"Be what you mean,'' said Alice..', 'Alice very politely; but she felt very lonely and low-spirited. In a little faster?" said a sleepy voice behind her. ''Collar that Dormouse,'' the Queen said severely ''Who is it directed to?'' said the Footman, and began staring at the Footman''s head: it just at first, but, after watching it a violent blow underneath her chin: it had no pictures or conversations in it, ''and what is the capital of Paris, and Paris is the same thing, you know.'' ''I DON''T.', NULL, '', 300, 17600, 0, 0, 0, 'Rocio', 0, 1441442557, 0, 0, 0, 0, 0, '', 1, 1441442557, 1441440000, 0),
(184472, 1, 'f852e3ed401c7c72c5a9609687385f65', 14, 'https://www.Schumm.biz/voluptatum-iure-qui-dicta-modi-est', '', 4, 'Alice replied, so.', 'I should have liked teaching it tricks very much, if--if.', 'NEVER come to the Dormouse, not choosing to notice this question, but hurriedly went on, ''What''s your name, child?'' ''My name is Alice, so please your Majesty,'' said Two, in a great thistle, to keep back the wandering hair that WOULD always get into her face. ''Wake up, Alice dear!'' said her sister; ''Why, what a dear quiet thing,'' Alice went on, spreading out the answer to shillings and pence. ''Take off your hat,'' the King had said that day. ''No, no!'' said the Gryphon. ''They can''t have anything to say, she simply bowed, and took the watch and looked at it again: but he could.', NULL, '', 900, 17600, 0, 0, 0, 'Billy', 0, 1441407837, 0, 0, 0, 0, 0, '', 1, 1441407837, 1441407600, 0),
(344246, 2, '09dc73287ff642cfa2c97977dc42bc64', 6, 'http://www.Cole.com/sit-maiores-et-quam-vitae-ut-fugiat', '', 1, 'IS the use of a.', 'And when I learn music.'' ''Ah! that accounts for it,'' said.', 'Gryphon answered, very nearly carried it out loud. ''Thinking again?'' the Duchess by this time.) ''You''re nothing but a pack of cards, after all. I needn''t be so stingy about it, you know--'' ''But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"'' said Alice. ''Call it what you mean,'' the March Hare, ''that "I breathe when I breathe"!'' ''It IS the same side of WHAT? The other guests had taken his watch out of it, and talking over its head. ''Very uncomfortable for the first to speak. ''What size do you like to go and get.', NULL, '', 600, 16900, 0, 0, 0, 'Enrico', 0, 1441406107, 0, 0, 0, 0, 0, '', 1, 1441406107, 1441404000, 0),
(19169, 1, '116c443b5709e870248c93358f9a328e', 12, 'http://www.Gleason.com/et-vero-optio-exercitationem-aliquid-optio-consectetur', '', 4, 'Let this be a lesson to.', 'Sir, With no jury or judge, would be very likely to eat.', 'I wonder who will put on your head-- Do you think I can find them.'' As she said this, she was quite out of sight before the end of every line: ''Speak roughly to your little boy, And beat him when he sneezes; For he can EVEN finish, if he had never heard of such a subject! Our family always HATED cats: nasty, low, vulgar things! Don''t let him know she liked them best, For this must ever be A secret, kept from all the creatures wouldn''t be so kind,'' Alice replied, so eagerly that the way I want to get very tired of being upset, and their curls got entangled together. Alice was not a regular rule: you invented it just grazed his nose, you know?'' ''It''s the thing Mock Turtle would be only.', NULL, '', 700, 16800, 0, 0, 0, 'Unique', 0, 1441407961, 0, 0, 0, 0, 0, '', 1, 1441407961, 1441407600, 0),
(192679, 1, '06a33747b5c95799034630e578e53dc5', 10, 'http://www.Pouros.com/qui-id-molestias-non-dolores-non', '', 5, 'Rabbit just under the.', 'KNOW IT TO BE TRUE--" that''s the jury-box,'' thought Alice,.', 'Mock Turtle, who looked at Two. Two began in a hoarse, feeble voice: ''I heard every word you fellows were saying.'' ''Tell us a story.'' ''I''m afraid I can''t tell you how it was too dark to see what I should say "With what porpoise?"'' ''Don''t you mean by that?'' said the King; and as it was indeed: she was now more than Alice could not make out exactly what they WILL do next! As for pulling me out of court! Suppress him! Pinch him! Off with his head!"'' ''How dreadfully savage!'' exclaimed Alice. ''That''s the first witness,'' said the Duchess. ''Everything''s got a moral, if only you can find it.'' And she squeezed herself up and ran the faster, while more and more faintly came, carried on the end of every line:.', NULL, '', 800, 15900, 0, 0, 0, 'Gene', 0, 1441414720, 0, 0, 0, 0, 0, '', 1, 1441414720, 1441411200, 0),
(251878, 4, '3eafacc53f86c8492c309ca2772fbfe9', 5, 'http://www.Schinner.info/tempora-et-est-qui-nulla', '', 2, 'NOT!'' cried the Mouse,.', 'Twinkle, twinkle--"'' Here the Queen till she heard the.', 'Alice and all of them even when they hit her; and the sounds will take care of the gloves, and she dropped it hastily, just in time to begin at HIS time of life. The King''s argument was, that she had forgotten the Duchess to play croquet with the Dormouse. ''Write that down,'' the King added in an undertone to the fifth bend, I think?'' ''I had NOT!'' cried the Mouse, sharply and very neatly and simply arranged; the only difficulty was, that if something wasn''t done about it in less than a pig, my dear,'' said Alice, a little wider. ''Come, it''s pleased so far,'' said the Gryphon. ''Do you play croquet with the glass table and the King hastily said, and went by without noticing her. Then followed the Knave ''Turn them over!'' The Knave of.', NULL, '', 500, 15900, 0, 0, 0, 'Demarcus', 0, 1441414681, 0, 0, 0, 0, 0, '', 1, 1441414681, 1441411200, 0);
</code></pre>
<p><a href="https://i.stack.imgur.com/rsfvt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rsfvt.png" alt="enter image description here"></a></p> | 42,435,919 | 5 | 12 | null | 2015-10-05 15:16:45.837 UTC | 4 | 2017-02-27 00:19:44.113 UTC | 2017-05-23 10:29:51.04 UTC | null | -1 | null | 1,377,781 | null | 1 | 36 | mysql | 1,801 | <p>It seems that some kind of news database, so try to think about make some sort of news archiving every month.</p>
<p>Think about this solution, it's not the best but it may help</p>
<ul>
<li>Add these columns into <strong>listings</strong> table
<ul>
<li><code>publishedmonth</code> tinyint(2) UNSIGNED NOT NULL DEFAULT '0'</li>
<li><code>publishedyear</code> tinyint(2) UNSIGNED NOT NULL DEFAULT '0'</li>
<li><code>publishedminute</code> mediumint(6) UNSIGNED NOT NULL DEFAULT '0'</li>
</ul></li>
<li><p>Add this INDEXING KEY into <strong>listings</strong> table</p>
<ul>
<li><code>ADD KEY published_month (publishedmonth,publishedyear,publishedminute)</code></li>
</ul></li>
<li><p>During inserting use these values from PHP code</p>
<ul>
<li>publishedmonth will has <code>date('n')</code></li>
<li>publishedyear will has <code>date('y')</code></li>
<li>publishedminute will has <code>date('jHi')</code></li>
</ul></li>
</ul>
<p>Dump huge number of records then test this query</p>
<pre><code>SELECT * FROM listings WHERE publishedmonth = 2 AND publishedyear = 17 ORDER BY publishedminute
</code></pre> |
10,624,964 | What's the fastest way to copy a collection within the same database? | <p>I want to copy a collection within the <strong>same</strong> database and give it a
different name - basically take a snapshot.</p>
<p>What's the best way to do this? Is there a command, or do I have to
copy each record in turn? </p>
<p>I'm aware of the <code>cloneCollection</code> command, but it seems to be for
copying to another server only. </p>
<p>I'm also aware of <code>mongoimport</code> and <code>mongoexport</code>, but as I'm doing this via PHP I'd prefer not to make calls out to the shell.</p> | 10,627,056 | 9 | 3 | null | 2012-05-16 19:01:15.353 UTC | 38 | 2022-04-15 15:14:56.993 UTC | 2012-05-16 19:15:29.713 UTC | null | 535,296 | null | 535,296 | null | 1 | 105 | mongodb | 83,230 | <p>You have a few options, but the fastest is:</p>
<pre><code>mongodump -d db -c sourcecollection
mongorestore -d db -c targetcollection --dir=dump/<db>/<sourcecollection.bson>
</code></pre>
<p>or </p>
<pre><code>mongoexport -d db -c sourcecollection | mongoimport -d db -c targetcollection --drop
</code></pre>
<p>or in php:</p>
<pre><code>`mongoexport -d db -c sourcecollection | mongoimport -d db -c targetcollection --drop`;
</code></pre>
<p>after that you have</p>
<pre><code>mongo db < script.js
</code></pre>
<p>where, as shown in the <a href="http://www.mongodb.org/display/DOCS/Developer+FAQ#DeveloperFAQ-HowdoIcopyallobjectsfromonedatabasecollectiontoanother?" rel="noreferrer">mongo docs</a>, script.js contains something like:</p>
<pre><code>db.myoriginal.find().forEach( function(x){db.mycopy.insert(x)} );
</code></pre>
<p>The slowest (by an order of magnitude or more) way to copy a collection will be to use the native php driver - simply because of moving information around. But you could issue the above mongo query if you absolutely want to avoid cli calls using the <a href="http://www.php.net/manual/en/mongodb.execute.php" rel="noreferrer">db execute</a> function.</p> |
31,861,762 | Finding all references to a method with Roslyn | <p>I'm looking to scan a group of .cs files to see which ones call the <code>Value</code> property of a <code>Nullable<T></code> (finding all references). For example, this would match:</p>
<pre><code>class Program
{
static void Main()
{
int? nullable = 123;
int value = nullable.Value;
}
}
</code></pre>
<p>I found out about Roslyn and looked at some of the samples, but many of them are outdated and the API is huge. How would I go about doing this?</p>
<p>I'm stuck after parsing the syntax tree. This is what I have so far:</p>
<pre><code>public static void Analyze(string sourceCode)
{
var tree = CSharpSyntaxTree.ParseText(sourceCode);
tree./* ??? What goes here? */
}
</code></pre> | 31,864,730 | 2 | 3 | null | 2015-08-06 17:06:47.533 UTC | 22 | 2019-03-11 22:49:54.237 UTC | 2015-08-06 17:29:27.79 UTC | null | 4,077,294 | null | 4,077,294 | null | 1 | 29 | c#|code-analysis|roslyn|findall | 19,814 | <p>You're probably looking for the <a href="http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/FindSymbols/SymbolFinder_References.cs,fd299f73032d2f26"><code>SymbolFinder</code></a> class and specifically the <a href="http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/FindSymbols/SymbolFinder_References.cs,56626d323065e104,references"><code>FindAllReferences</code></a> method.</p>
<p>It sounds like you're having some trouble getting familiar with Roslyn. I've got a series of blog posts to help people get introduced to Roslyn called <a href="https://joshvarty.wordpress.com/learn-roslyn-now/">Learn Roslyn Now</a>. </p>
<p>As @SLaks mentions you're going to need access to the semantic model which I cover in <a href="https://joshvarty.wordpress.com/2014/10/30/learn-roslyn-now-part-7-introducing-the-semantic-model/">Part 7: Introduction to the Semantic Model</a></p>
<p>Here's a sample that shows you how the API can be used. If you're able to, I'd use <code>MSBuildWorkspace</code> and load the project from disk instead of creating it in an <code>AdHocWorkspace</code> like this.</p>
<pre><code>var mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var ws = new AdhocWorkspace();
//Create new solution
var solId = SolutionId.CreateNewId();
var solutionInfo = SolutionInfo.Create(solId, VersionStamp.Create());
//Create new project
var project = ws.AddProject("Sample", "C#");
project = project.AddMetadataReference(mscorlib);
//Add project to workspace
ws.TryApplyChanges(project.Solution);
string text = @"
class C
{
void M()
{
M();
M();
}
}";
var sourceText = SourceText.From(text);
//Create new document
var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
//Get the semantic model
var model = doc.GetSemanticModelAsync().Result;
//Get the syntax node for the first invocation to M()
var methodInvocation = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var methodSymbol = model.GetSymbolInfo(methodInvocation).Symbol;
//Finds all references to M()
var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol, doc.Project.Solution).Result;
</code></pre> |
32,119,507 | multiple awaits vs Task.WaitAll - equivalent? | <p>In terms of performance, will these 2 methods run <code>GetAllWidgets()</code> and <code>GetAllFoos()</code> in parallel?</p>
<p>Is there any reason to use one over the other? There seems to be a lot happening behind the scenes with the compiler so I don't find it clear.</p>
<p>============= MethodA: Using multiple awaits ======================</p>
<pre><code>public async Task<IHttpActionResult> MethodA()
{
var customer = new Customer();
customer.Widgets = await _widgetService.GetAllWidgets();
customer.Foos = await _fooService.GetAllFoos();
return Ok(customer);
}
</code></pre>
<p>=============== MethodB: Using Task.WaitAll =====================</p>
<pre><code>public async Task<IHttpActionResult> MethodB()
{
var customer = new Customer();
var getAllWidgetsTask = _widgetService.GetAllWidgets();
var getAllFoosTask = _fooService.GetAllFos();
Task.WaitAll(new List[] {getAllWidgetsTask, getAllFoosTask});
customer.Widgets = getAllWidgetsTask.Result;
customer.Foos = getAllFoosTask.Result;
return Ok(customer);
}
</code></pre>
<p>=====================================</p> | 32,119,616 | 5 | 3 | null | 2015-08-20 13:24:40.51 UTC | 23 | 2020-06-14 10:19:43.93 UTC | 2015-08-20 13:33:34.433 UTC | null | 885,318 | null | 69,092 | null | 1 | 76 | c#|.net|async-await|task-parallel-library | 36,203 | <p>The first option will not execute the two operations concurrently. It will execute the first and await its completion, and only then the second.</p>
<p>The second option will execute both concurrently but will wait for them synchronously (i.e. while blocking a thread).</p>
<p>You shouldn't use both options since the first completes slower than the second and the second blocks a thread without need.</p>
<p>You should wait for both operations asynchronously with <code>Task.WhenAll</code>:</p>
<pre><code>public async Task<IHttpActionResult> MethodB()
{
var customer = new Customer();
var getAllWidgetsTask = _widgetService.GetAllWidgets();
var getAllFoosTask = _fooService.GetAllFos();
await Task.WhenAll(getAllWidgetsTask, getAllFoosTask);
customer.Widgets = await getAllWidgetsTask;
customer.Foos = await getAllFoosTask;
return Ok(customer);
}
</code></pre>
<p>Note that after <code>Task.WhenAll</code> completed both tasks already completed so awaiting them completes immediately.</p> |
40,081,574 | Using Swift 3 Stopping a scheduledTimer, Timer continue firing even if timer is nil | <p>We call startTimer function to start a timer. When we wanted to stop it we call stopTimerTest function but after we called stopTimer function the timerTestAction keeps firing. To check the timer condition we used print and print in timerActionTest returns nil.</p>
<pre><code>var timerTest: Timer? = nil
func startTimer () {
timerTest = Timer.scheduledTimer(
timeInterval: TimeInterval(0.3),
target : self,
selector : #selector(ViewController.timerActionTest),
userInfo : nil,
repeats : true)
}
func timerActionTest() {
print(" timer condition \(timerTest)")
}
func stopTimerTest() {
timerTest.invalidate()
timerTest = nil
}
</code></pre> | 40,148,293 | 4 | 6 | null | 2016-10-17 08:21:39.237 UTC | 8 | 2019-08-16 10:42:13.693 UTC | 2016-10-19 17:48:40.827 UTC | null | 3,301,890 | null | 2,692,027 | null | 1 | 47 | timer|swift3 | 75,440 | <p>Try to make the following changes to your code:</p>
<p>First, you have to change the way you declare <code>timerTest</code></p>
<pre><code>var timerTest : Timer?
</code></pre>
<p>then in <code>startTimer</code> before instantiating check if <code>timerTest</code> is nil </p>
<pre><code>func startTimer () {
guard timerTest == nil else { return }
timerTest = Timer.scheduledTimer(
timeInterval: TimeInterval(0.3),
target : self,
selector : #selector(ViewController.timerActionTest),
userInfo : nil,
repeats : true)
}
</code></pre>
<p>Finally in your <code>stopTimerTest</code> you invalidate <code>timerTest</code> if it isn't nil </p>
<pre><code>func stopTimerTest() {
timerTest?.invalidate()
timerTest = nil
}
</code></pre> |
13,275,812 | How to get, set and select elements with data attributes? | <p>I'm having some trouble with data-attributes, I can't get anything to work for some reason so I must be doing something wrong:</p>
<p>Set:</p>
<pre><code>$('#element').data('data1', '1'); //Actually in my case the data is been added manually
</code></pre>
<p>Does that make a difference?</p>
<p>Get:</p>
<pre><code>$('#element').data('data1');
</code></pre>
<p>Select:</p>
<pre><code>$('#element[data1 = 1]')
</code></pre>
<p>None of this works for me, am I making this up or how is it?</p> | 13,276,132 | 4 | 2 | null | 2012-11-07 18:25:29.503 UTC | 8 | 2019-09-23 07:38:19.873 UTC | 2014-05-21 01:19:20.927 UTC | null | 775,283 | null | 817,908 | null | 1 | 25 | jquery|jquery-selectors|custom-data-attribute | 52,932 | <p>All of the answers are correct, but I want to state something that nobody else did.<br>
The jQuery <code>data</code> method acts like a getter for html5 data attributes, but the setter does not alter the data-* attribute.<br>
So, If you manually added the data (as is stated in your comment), then you can use a css attribute selector to select your element : </p>
<pre><code>$('#element[data-data1=1]')
</code></pre>
<p>but if you have added (altered) the data via jQuery, then the above solution won't work.<br>
Here's an example of this failure : </p>
<pre><code>var div = $('<div />').data('key','value');
alert(div.data('key') == div.attr('data-key'));// it will be false
</code></pre>
<p>So the workaround is to filter the collection by checking the jQuery data value to match the desired one : </p>
<pre><code>// replace key & value with own strings
$('selector').filter(function(i, el){
return $(this).data('key') == 'value';
});
</code></pre>
<p>So, in order to overcome these issues, you need to use the html5 dataset attributes (via jQuery's <code>attr</code> methos) as getters and setters : </p>
<pre><code>$('selector').attr('data-' + key, value);
</code></pre>
<p>or you can use a custom expression that filters jQuery internal <code>data</code> : </p>
<pre><code>$.expr[':'].data = function(elem, index, m) {
// Remove ":data(" and the trailing ")" from the match, as these parts aren't needed:
m[0] = m[0].replace(/:data\(|\)$/g, '');
var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'),
// Retrieve data key:
key = regex.exec( m[0] )[2],
// Retrieve data value to test against:
val = regex.exec( m[0] );
if (val) {
val = val[2];
}
// If a value was passed then we test for it, otherwise we test that the value evaluates to true:
return val ? $(elem).data(key) == val : !!$(elem).data(key);
};
</code></pre>
<p>and use it like : </p>
<pre><code>$('selector:data(key,value)')
</code></pre>
<h2>Update</h2>
<p>I know this thread is a few years old, but since it has some activity, it's worth mentioning that doing this using the <code>querySelector</code> dom API (with no need for jQuery) is quite trivial:</p>
<pre><code>document.querySelectorAll('[attribute=value]')
</code></pre> |
24,268,690 | How can I identify uppercase and lowercase characters in a string with swift? | <p>This is what I have so far (for testing purpose):</p>
<pre><code>let string = "The quick BroWn fOX jumpS Over tHe lazY DOg"
for chr in string {
if isupper(String(chr)) {
print(String(chr).lowercaseString)
continue
}
print(chr)
}
</code></pre>
<p>how can I test for uppercase and lowercase characters?</p>
<p>I know I can call C functions from swift, but this does not seems to be correct for me. How can I do this with swift only?</p> | 55,621,766 | 18 | 3 | null | 2014-06-17 16:13:56.75 UTC | 8 | 2021-09-14 05:48:25.15 UTC | 2014-06-17 16:22:07.113 UTC | null | 1,757,338 | null | 1,757,338 | null | 1 | 39 | swift | 34,635 | <p>In Swift 5, we can now check for <a href="https://unicode.org/reports/tr44/#Property_Index" rel="noreferrer">character properties</a> per Unicode standard.</p>
<p>For your question, <code>chr.isUppercase</code> and <code>chr.isLowercase</code> is the answer.</p> |
3,908,533 | Howto use Rollback/Commit in Oracle SQL | <p>I am trying to utilize transaction functionality in Oracle SQL for the first time and can't seem to find a good explanation. I understand that starting a new session will begin a new transaction. I also understand that commit/rollback is used to end it. What I am trying to do is execute two statements and if I either of them fail, undo any changes they might have made and continue with execution. How can I check for this condition and issue a commit or rollback accordingly?</p> | 3,908,587 | 2 | 0 | null | 2010-10-11 17:27:53.887 UTC | 1 | 2010-10-11 20:21:40.137 UTC | null | null | null | null | 433,807 | null | 1 | 6 | sql|oracle|transactions | 57,196 | <p>Use a PL/SQL block and write something like this:</p>
<pre><code>begin
statement_zero;
savepoint my_savepoint;
begin
-- if either of these fail, then exception section will be executed
statement_one;
statement_two;
exception
when others then
rollback to my_savepoint;
end;
statement_three;
commit;
end;
</code></pre>
<p>See also <a href="http://www.adp-gmbh.ch/ora/concepts/transaction.html" rel="noreferrer">http://www.adp-gmbh.ch/ora/concepts/transaction.html</a></p> |
9,476,662 | How to set android layout to support all screen sizes? | <p>I am developing a program on android version2.2. I have read many documentation on supporting multiple screen sizes but still confused. I designed a layout file, that supports for large and normal screens, when am trying it with small screen it is not adjusting the layout to fit the screen. I used this code in the manifest also. </p>
<pre><code><supports-screens
android:resizeable="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>
</code></pre>
<p>The image for the small screen is <a href="http://dl.dropbox.com/u/58701258/epay-normal.png" rel="noreferrer">here.</a>
How can I set the screen that compatible with small screen? Somewhere I found by using the folder "layout-small" but if I use this, the project size is increasing, I don't want that, so can any one suggest me the best way to do this?</p> | 9,477,150 | 8 | 2 | null | 2012-02-28 05:01:48.3 UTC | 31 | 2020-10-19 20:36:48.61 UTC | 2017-01-17 06:46:02.617 UTC | null | 2,689,986 | null | 1,235,526 | null | 1 | 30 | android|android-layout|android-emulator | 155,081 | <p>Please go through the following links. These might help you:</p>
<p><a href="http://developer.android.com/training/multiscreen/screensizes.html" rel="noreferrer">Supporting Different Screen Sizes</a></p>
<p><a href="http://developer.android.com/guide/practices/screens_support.html" rel="noreferrer">Supporting Multiple Screens</a></p>
<p><a href="http://developer.android.com/training/multiscreen/screendensities.html" rel="noreferrer">Supporting Different Densities</a></p>
<p><a href="http://developer.android.com/guide/practices/tablets-and-handsets.html" rel="noreferrer">Supporting Tablets and Handsets</a></p>
<p>AFAIK, the only way to support all screens is by doing that folder bifurcation. Every XML file goes up to a few kilo bytes. So, size shouldn't be too much of an issue as such. </p> |
16,310,871 | How to find d, given p, q, and e in RSA? | <p>I know I need to use the <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="noreferrer">extended euclidean algorithm</a>, but I'm not sure exactly what calculations I need to do. I have huge numbers. Thanks</p> | 16,310,933 | 7 | 7 | null | 2013-05-01 00:06:02.03 UTC | 6 | 2022-05-07 20:42:06.663 UTC | 2019-09-24 00:26:08.04 UTC | null | 608,639 | user1816690 | null | null | 1 | 22 | encryption|rsa | 94,253 | <p>Well, <code>d</code> is chosen such that <code>d * e == 1 modulo (p-1)(q-1)</code>, so you could use the <a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="noreferrer">Euclidean algorithm</a> for that (<a href="http://en.wikipedia.org/wiki/Modular_multiplicative_inverse" rel="noreferrer">finding the modular multiplicative inverse</a>). </p>
<p>If you are not interested in understanding the algorithm, you can just call <a href="http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html#modInverse%28java.math.BigInteger%29" rel="noreferrer">BigInteger#modInverse</a> directly.</p>
<pre><code> d = e.modInverse(p_1.multiply(q_1))
</code></pre> |
16,565,105 | When creating service method what's the difference between module.service and module.factory | <p>I don't know what is the best practice and what I should use.</p>
<p>What is the difference between below two methods?</p>
<pre><code>module.service(..);
</code></pre>
<p>and </p>
<pre><code>module.factory(..);
</code></pre> | 16,566,144 | 2 | 2 | null | 2013-05-15 12:33:21.52 UTC | 17 | 2015-07-10 04:36:55.243 UTC | 2015-07-10 04:36:55.243 UTC | null | 3,040,096 | null | 2,213,958 | null | 1 | 25 | angularjs | 19,927 | <p>There is a great google group post about this from Pawel Kozlowski: </p>
<p><a href="https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ">https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ</a></p>
<p>Quoted from Powel:</p>
<blockquote>
<p>in fact $provide.provider, $provide.factory and $provide.service are
more or less the same thing in the sense that all of them are
blueprints / instructions for creating object instances (those
instances are then ready to be injected into collaborators). </p>
<p>$provide.provider is the most spohisticated method of registering
blueprints, it allows you to have a complex creation function and
configuration options. </p>
<p>$provide.factory is a simplified version of $provide.provider when you
don't need to support configuration options but still want to have a
more sophisticated creation logic. </p>
<p>$provide.service is for cases where the whole creation logic boils
down to invoking a constructor function. </p>
<p>So, depending on the complexity of your construction logic you would
choose one of $provide.provider, $provide.factory and $provide.service
but in the end what you are going to get is a new instance.</p>
</blockquote>
<p>Here is the accompanying fiddle to demonstrate (from the thread): <a href="http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/">http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/</a></p>
<p>And the code:</p>
<pre><code>var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
</code></pre> |
28,893,710 | Whoops, looks like something went wrong. Laravel 5.0 | <p>I installed Laravel 5.0 properly by cloning in git, and composer install, when I ran it to browser <code>http://localhost/laravel/public/</code>, it says</p>
<blockquote>
<p>"Whoops, looks like something went wrong."</p>
</blockquote>
<p>I did not make any changes after composer install.</p>
<p><strong>Update</strong> after copy the env.example to .env this is result</p>
<blockquote>
<p>RuntimeException in compiled.php line 5599: OpenSSL extension is required.</p>
</blockquote> | 28,893,877 | 19 | 7 | null | 2015-03-06 06:58:53.71 UTC | 16 | 2022-02-14 16:13:35.077 UTC | 2015-08-02 00:25:50.943 UTC | null | 218,152 | null | 589,973 | null | 1 | 69 | php|laravel-5 | 226,319 | <p>The logs are located in <code>storage</code> directory. If you want laravel to display the error for you rather than the cryptic 'Whoops' message, copy the <code>.env.example</code> to <code>.env</code> and make sure <code>APP_ENV=local</code> is in there. It should then show you the detailed error messaging.</p> |
17,520,093 | Read large data from csv file in php | <p>I am reading csv & checking with mysql that records are present in my table or not in php.</p>
<p>csv has near about 25000 records & when i run my code it display "Service Unavailable" error after 2m 10s (onload: 2m 10s)</p>
<p>here i have added code</p>
<pre><code>// for set memory limit & execution time
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');
//function to read csv file
function readCSV($csvFile)
{
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
set_time_limit(60); // you can enable this if you have lot of data
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
// Set path to CSV file
$csvFile = 'my_records.csv';
$csv = readCSV($csvFile);
for($i=1;$i<count($csv);$i++)
{
$user_email= $csv[$i][1];
$qry = "SELECT u.user_id, u.user_email_id FROM tbl_user as u WHERE u.user_email_id = '".$user_email."'";
$result = @mysql_query($qry) or die("Couldn't execute query:".mysql_error().''.mysql_errno());
$rec = @mysql_fetch_row($result);
if($rec)
{
echo "Record exist";
}
else
{
echo "Record not exist";
}
}
</code></pre>
<p>Note: I just want to list out records those are not exist in my table.</p>
<p>Please suggest me solution on this...</p> | 17,521,803 | 3 | 7 | null | 2013-07-08 06:08:13.62 UTC | 6 | 2019-03-29 14:18:36.71 UTC | 2017-09-22 17:44:54.74 UTC | null | -1 | null | 2,559,545 | null | 1 | 12 | php|csv|large-data | 54,558 | <p>An excellent method to deal with large files is located at: <a href="https://stackoverflow.com/a/5249971/797620">https://stackoverflow.com/a/5249971/797620</a></p>
<p>This method is used at <s><a href="http://www.cuddlycactus.com/knownpasswords/" rel="nofollow noreferrer">http://www.cuddlycactus.com/knownpasswords/</a></s> (page has been taken down) to search through 170+ million passwords in just a few milliseconds.</p> |
17,327,668 | Best way to disable button in Twitter's Bootstrap | <p>I am confused when it comes to disabling a <code><button></code>, <code><input></code> or an <code><a></code> element with classes: <code>.btn</code> or <code>.btn-primary</code>, with JavaScript/jQuery.</p>
<p>I have used a following snippet to do that:</p>
<pre><code>$('button').addClass('btn-disabled');
$('button').attr('disabled', 'disabled');
$('button').prop('disabled', true);
</code></pre>
<p>So, if I just provide the <code>$('button').addClass('btn-disabled');</code> to my element, it will appear as disabled, visually, but the functionality will remain the same and it will be clickable nontheless, so that it the reason why I added the <code>attr</code> and <code>prop</code> settings to the element.</p>
<p>Has anyone expirenced this same issue out there? Is this the right way of doing this - while using Twitter's Bootstrap?</p> | 17,327,775 | 6 | 5 | null | 2013-06-26 18:23:25.337 UTC | 41 | 2018-03-06 09:19:17.357 UTC | 2015-09-02 07:52:40.723 UTC | null | 1,828,051 | user1386320 | null | null | 1 | 271 | javascript|jquery|button|twitter-bootstrap | 366,293 | <p>You just need the <code>$('button').prop('disabled', true);</code> part, the button will automatically take the disabled class.</p> |
64,473,908 | "Operation Succeeded" in Android Studio 4.1, with no action | <p>Have anyone faced this issue with the new Android Studio 4.1. When I run the app to the simulator, everything works and builds. Later it also shows a message</p>
<p><a href="https://i.stack.imgur.com/43bQn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/43bQn.png" alt="enter image description here" /></a></p>
<p>In the run, the error message is</p>
<pre><code>Unable to determine application id: com.android.tools.idea.run.ApkProvisionException: Error loading build artifacts from: LOCATION/build/outputs/apk/act/debug/output-metadata.json
</code></pre> | 64,475,260 | 11 | 4 | null | 2020-10-22 01:24:28.637 UTC | 1 | 2022-05-18 07:44:37.967 UTC | null | null | null | null | 1,077,539 | null | 1 | 55 | android|android-studio | 11,067 | <p>I just figured out that, if you upgrade your gradle in one branch and change your branch to something which had the old gradle, you may face this issue.</p>
<p>I just updated the gradle and it fixed the issue.For me I change from</p>
<pre><code>classpath 'com.android.tools.build:gradle:4.0.1'
</code></pre>
<p>to</p>
<pre><code>classpath 'com.android.tools.build:gradle:4.1.2'
</code></pre> |
19,459,197 | java codility Frog-River-One | <p>I have been trying to solve a Java exercise on a Codility web page.</p>
<p>Below is the link to the mentioned exercise and my solution.</p>
<p><a href="https://codility.com/demo/results/demoH5GMV3-PV8" rel="noreferrer">https://codility.com/demo/results/demoH5GMV3-PV8</a></p>
<p>Can anyone tell what can I correct in my code in order to improve the score?</p>
<p><strong>Just in case here is the task description:</strong></p>
<p>A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.</p>
<p>You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.</p>
<p>The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.</p>
<p>For example, you are given integer X = 5 and array A such that:</p>
<pre><code> A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
</code></pre>
<p>In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.</p>
<p>Write a function:</p>
<pre><code>class Solution { public int solution(int X, int[] A); }
</code></pre>
<p>that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.</p>
<p>If the frog is never able to jump to the other side of the river, the function should return −1.</p>
<p>For example, given X = 5 and array A such that:</p>
<pre><code> A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
</code></pre>
<p>the function should return 6, as explained above. Assume that:</p>
<pre><code>N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
</code></pre>
<p>Complexity:</p>
<pre><code>expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).
</code></pre>
<p>Elements of input arrays can be modified.</p>
<p><strong>And here is my solution:</strong></p>
<pre><code>import java.util.ArrayList;
import java.util.List;
class Solution {
public int solution(int X, int[] A) {
int list[] = A;
int sum = 0;
int searchedValue = X;
List<Integer> arrayList = new ArrayList<Integer>();
for (int iii = 0; iii < list.length; iii++) {
if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
sum += list[iii];
arrayList.add(list[iii]);
}
if (list[iii] == searchedValue) {
if (sum == searchedValue * (searchedValue + 1) / 2) {
return iii;
}
}
}
return -1;
}
}
</code></pre> | 19,460,553 | 46 | 4 | null | 2013-10-18 21:17:31.47 UTC | 13 | 2022-07-16 21:08:42.12 UTC | 2017-07-05 12:45:01.563 UTC | null | 1,073,386 | null | 1,466,580 | null | 1 | 14 | java|algorithm | 50,711 | <p>You are using <code>arrayList.contains</code> inside a loop, which will traverse the whole list unnecessarily.</p>
<p>Here is my solution (I wrote it some time ago, but I believe it scores 100/100):</p>
<pre><code> public int frog(int X, int[] A) {
int steps = X;
boolean[] bitmap = new boolean[steps+1];
for(int i = 0; i < A.length; i++){
if(!bitmap[A[i]]){
bitmap[A[i]] = true;
steps--;
if(steps == 0) return i;
}
}
return -1;
}
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.