I have same problem after upgrading to Gradle Wrapper 5.1.rec3. I am back to Gradle 4.6
I found the solution as Its problem with Android Studio 3.1 Canary 6
My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.
Now My build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.2'
defaultConfig {
applicationId "com.example.demo"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
dataBinding {
enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
implementation "com.squareup.retrofit2:retrofit:2.3.0"
implementation "com.google.code.gson:gson:2.8.2"
implementation "com.android.support.constraint:constraint-layout:1.0.2"
implementation "com.squareup.retrofit2:converter-gson:2.3.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
implementation "com.squareup.picasso:picasso:2.5.2"
implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
compile 'com.github.elevenetc:badgeview:v1.0.0'
annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
testImplementation "junit:junit:4.12"
androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
exclude group: "com.android.support", module: "support-annotations"
})
}
and My gradle is:
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
and its working finally.
I think there problem in Android Studio 3.1 Canary 6
Thank you all for your time.
in my case it was unused parameter in room persistence function in DAO class
clear project and then run. it will work
just setting the multiDexEnabled to true worked fine.
defaultConfig
{
multiDexEnabled true
}
I had c++ codes in my project but i didn't have NDK
installed, installing it solved the problem
I made the mistake of defining my test like this
class MyTest {
@Test
fun `test name`() = runBlocking {
// something here that isn't Unit
}
}
That resulted in runBlocking
returning something, which meant that the method wasn't void and junit didn't recognize it as a test. That was pretty lame. I explicitly supply a type parameter now to run blocking. It won't stop the pain or get me my two hours back but it will make sure this doesn't happen again.
class MyTest {
@Test
fun `test name`() = runBlocking<Unit> { // Specify Unit
// something here that isn't Unit
}
}
This could also some extra reasons instead of the mentioned reasons :
you should also check if you are connecting via proxy. If there is a proxy set it up using File > Settings > Appearance and Behavior > System settings > HTTP Proxy
After following Carlos steps I ended up deleting the
C:\Users\MyPath.AndroidStudioPreview Directory
Then re imported the project it seemed to fix my issue completely for the meanwhile, And speedup my AndroidStudio
Hope it helps anyone
Just add these two lines at "gradle.properties":
android.useAndroidX=true
android.enableJetifier=true
There's surprisingly simple way of reading resource by string:
ResourceNamespace.ResxFileName.ResourceManager.GetString("ResourceKey")
It's clean and elegant solution for reading resources by keys where "dot notation" cannot be used (for instance when resource key is persisted in the database).
None: The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Compile: The file is compiled into the build output. This setting is used for code files.
Content: Allows you to retrieve a file (in the same directory as the assembly) as a stream via Application.GetContentStream(URI). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which Visual Studio graciously adds when you mark a file as "Content"
Embedded resource: Embeds the file in an exclusive assembly manifest resource.
Resource (WPF only): Embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources.
Page (WPF only): Used to compile a xaml
file into baml
. The baml
is then embedded with the same technique as Resource
(i.e. available as `AppName.g.resources)
ApplicationDefinition (WPF only): Mark the XAML/class file that defines your application. You specify the code-behind with the x:Class="Namespace.ClassName" and set the startup form/page with StartupUri="Window1.xaml"
SplashScreen (WPF only): An image that is marked as SplashScreen
is shown automatically when an WPF application loads, and then fades
DesignData: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses mock types)
DesignDataWithDesignTimeCreatableTypes: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses actual types)
EntityDeploy: (Entity Framework): used to deploy the Entity Framework artifacts
CodeAnalysisDictionary: An XML file containing custom word dictionary for spelling rules
Follow the steps below:
1- git stash
2- git add .
3- git commit -m "your commit message"
Try to use deep Equal. It will compare nested arrays as well as nested Json.
expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
Please refer to main documentation site.
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);
..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.
To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:
./mysql --version
Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.
After adding the mysql bin dir to your $PATH, verify it's there by executing:
echo $PATH
Thereafter you can check your mysql version from anywhere by running (note no "./"):
mysql --version
Navigate to the folder on your new machine you want to download from git on git bash.
Use below command to download the code from any branch you like
git clone 'git ssh url' -b 'Branch Name'
It will download the respective branch code.
print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => í )
It's more than likely because you've used Console in the namespace. For example like this:
namespace XYZApplication.Console
{
class Program
{
static void Main(string[] args)
{
//Some code;
}
}
}
Try removing it from the namespace or use the full namespace instead i.e.
System.Console.Writeline("abc");
this is the correct answer that worked for me
$(document).ready(function () {
function resizeIframe() {
if ($('iframe').contents().find('html').height() > 100) {
$('iframe').height(($('iframe').contents().find('html').height()) + 'px')
} else {
setTimeout(function (e) {
resizeIframe();
}, 50);
}
}
resizeIframe();
});
the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);
on the client side i use
new Date(+data.replace(/\D/g, ''));
The rule of thumb is to use the function most suited to your needs.
If you just want the keys and do not plan to ever read any of the values, use keys():
foreach my $key (keys %hash) { ... }
If you just want the values, use values():
foreach my $val (values %hash) { ... }
If you need the keys and the values, use each():
keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }
If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():
%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
producing the expected resulting hash:
(a => 1, A => 2, b => 2, B => 4)
But using each() to do the same thing:
%h = (a => 1, b => 2);
keys %h;
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
produces incorrect results in hard-to-predict ways. For example:
(a => 1, A => 2, b => 2, B => 8)
This, however, is safe:
keys %h;
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
All of this is described in the perl documentation:
% perldoc -f keys
% perldoc -f each
This can also happen if your package name is invalid.
For example, if your "package" is com.my-company
(which is not a valid Java package name due to the dash), IntelliJ will prevent you from creating a Java Class in that package.
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
$ echo "This is a sentence." | tr -s " " "\012"
This
is
a
sentence.
For checking for spaces, use grep:
$ echo "This is a sentence." | grep " " > /dev/null
$ echo $?
0
$ echo "Thisisasentence." | grep " " > /dev/null
$ echo $?
1
There are at least 2 different methods of invoking functions on radio button selection:
1) Using ng-change
directive:
<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>
and then, in a controller:
$scope.newValue = function(value) {
console.log(value);
}
Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/
2) Watching the model for changes. This doesn't require anything special on the input level:
<input type="radio" ng-model="value" value="foo">
but in a controller one would have:
$scope.$watch('value', function(value) {
console.log(value);
});
And the jsFiddle: http://jsfiddle.net/vDTRp/2/
Knowing more about your the use case would help to propose an adequate solution.
You can use the parseInt() function to convert the string to a number, e.g:
parseInt($('#elem').css('top'));
Update: (as suggested by Ben): You should give the radix too:
parseInt($('#elem').css('top'), 10);
Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).
Token based authentication is stateless, server need not store user information in the session. This gives ability to scale application without worrying where the user has logged in. There is web Server Framework affinity for cookie based while that is not an issue with token based. So the same token can be used for fetching a secure resource from a domain other than the one we are logged in which avoids another uid/pwd authentication.
Very good article here:
According to the documentation it is changed,
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html
Example :
spring:
datasource:
url: 'jdbc:mysql://localhost/db?useSSL=false'
username: root
password: pass
driver: com.mysql.jdbc.Driver
hikari:
minIdle: 10
idle-timeout: 10000
maximumPoolSize: 30
These are the following configuration changes we can do on hikari, please add/update according to your need.
autoCommit
connectionTimeout
idleTimeout
maxLifetime
connectionTestQuery
connectionInitSql
validationTimeout
maximumPoolSize
poolName
allowPoolSuspension
readOnly
transactionIsolation
leakDetectionThreshold
As of May 2017, multiple FROM
s can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.
The general syntax involves adding
FROM
additional times within your Dockerfile - whichever is the lastFROM
statement is the final base image. To copy artifacts and outputs from intermediate images useCOPY --from=<base_image_number>
.
FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
The result would be two images, one for building, one with just the resulting app (much, much smaller)
REPOSITORY TAG IMAGE ID CREATED SIZE
multi latest bcbbf69a9b59 6 minutes ago 10.3MB
golang 1.7.3 ef15416724f6 4 months ago 672MB
what is a base image?
A set of files, plus EXPOSE
'd ports, ENTRYPOINT
and CMD
.
You can add files and build a new image based on that base image, with a new Dockerfile
starting with a FROM
directive: the image mentioned after FROM
is "the base image" for your new image.
does it mean that if I declare
neo4j/neo4j
in aFROM
directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Only if you don't overwrite CMD
and ENTRYPOINT
.
But the image in itself is enough: you would use a FROM neo4j/neo4j
if you had to add files related to neo4j
for your particular usage of neo4j
.
This table might be helpful for you:
Going down the first column, you will see how the log works in each level. i.e for WARN, (FATAL, ERROR and WARN) will be visible. For OFF, nothing will be visible.
Very interesting discussion thread, i also faced the same problem may be worse one because
So read the threads here and implemented my version, which helped me in pushing up my contents in iPad in landscape mode. Here is code ( this is not fool proof and all, but it fixed my issue) First u need to have a delegate in your custom cell class, which on editing begins, sends the textfield to ur viewcontroller and set the activefield = theTextField there
// IMPLEMENTED TO HANDLE LANDSCAPE MODE ONLY
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect aRect = myTable.frame;
CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
aRect.size.height -= kbSize.height+50;
// This will the exact rect in which your textfield is present
CGRect rect = [myTable convertRect:activeField.bounds fromView:activeField];
// Scroll up only if required
if (!CGRectContainsPoint(aRect, rect.origin) ) {
[myTable setContentOffset:CGPointMake(0.0, rect.origin.y) animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillHide:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
myTable.contentInset = contentInsets;
myTable.scrollIndicatorInsets = contentInsets;
NSDictionary* info = [aNotification userInfo];
CGSize kbValue = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGSize kbSize = CGSizeMake(kbValue.height, kbValue.width);
CGRect bkgndRect = activeField.superview.frame;
bkgndRect.size.height += kbSize.height;
[activeField.superview setFrame:bkgndRect];
[myTable setContentOffset:CGPointMake(0.0, 10.0) animated:YES];
}
-anoop4real
This post can help you as a little bit related :
Using RegEX To Prefix And Append In Notepad++
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$ Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^ points to the start of the line. $ points to the end of the line.
\1 will be the source match within the parentheses.
We were using code that resembles the code above in a previous post using
...
String signature = new BigInteger(1,md5.digest()).toString(16);
...
However, watch out for using BigInteger.toString()
here, as it will truncate leading zeros...
(for an example, try s = "27"
, checksum should be "02e74f10e0327ad868d138f2b4fdd6f0"
)
I second the suggestion to use Apache Commons Codec, I replaced our own code with that.
Because in C++, the final executable code does not carry any symbol information, it's more or less pure machine code.
Thus, you need a way to describe the interface of a piece of code, that is separate from the code itself. This description is in the header file.
In case you want to download the repo from your shell/terminal it should work like this:
wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2
or whatever download URL you might have.
Please make sure the user:password are both URL-encoded. So for instance if your username contains the @
symbol then replace it with %40
.
I stumbled on this post while trying to change the display format for dates in sql-developer. Just wanted to add to this what I found out:
But a lot of times, I just want to retain the DEFAULT_FORMAT while modifying the format only during a bunch of related queries. That's when I would change the format of the session with the following:
alter SESSION set NLS_DATE_FORMAT = 'my_required_date_format'
Eg:
alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'
In Java 8 I would use:
Set<String> set = Stream.of("a", "b").collect(Collectors.toSet());
This gives you a mutable Set
pre-initialized with "a" and "b". Note that while in JDK 8 this does return a HashSet
, the specification doesn't guarantee it, and this might change in the future. If you specifically want a HashSet
, do this instead:
Set<String> set = Stream.of("a", "b")
.collect(Collectors.toCollection(HashSet::new));
Check and install php5-mcrypt:
sudo apt-get install php5-mcrypt
As you have mentioned it doesn't change anything.
First, you should redirect both standard input and standard error from the crontab execution like below:
*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1
Then you can view the file /tmp/listener.log
to see if the script executed as you expected.
Second, I guess what you mean by change anything is by watching the files created by your program:
f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')
The crontab job above won't create these file in directory /home/souza/Documets/Listener
, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener
, the following cron job will do the trick:
*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1
Change to the working directory and execute the script from there, and then you can view the files created in place.
try this
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('.View').html('');
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
}
</script>
Here's an awfully complicated solution, but it works:
public static BigDecimal roundBigDecimal(final BigDecimal input){
return input.round(
new MathContext(
input.toBigInteger().toString().length(),
RoundingMode.HALF_UP
)
);
}
Test Code:
List<BigDecimal> bigDecimals =
Arrays.asList(new BigDecimal("100.12"),
new BigDecimal("100.44"),
new BigDecimal("100.50"),
new BigDecimal("100.75"));
for(final BigDecimal bd : bigDecimals){
System.out.println(roundBigDecimal(bd).toPlainString());
}
Output:
100
100
101
101
Since Java 8, it seems like the java.time
standard library is the way to go. From Joda time web page:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Back to your question. Were you to use Java 8, I think you want LocalDateTime
. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.
HeyRed.Mime.MimeGuesser.GuessMimeType
from Nuget would be the ultimate solution if you want to host your ASP.NET solution on non-windows environments.
File extension mapping is very insecure. If an attacker would upload invalid extensions, a mapping dictionary would e.g. allow executables to be distributed inside .jpg files. Therefore, always use a content-sniffing library to know the real content-type.
public static string MimeTypeFrom(byte[] dataBytes, string fileName)
{
var contentType = HeyRed.Mime.MimeGuesser.GuessMimeType(dataBytes);
if (string.IsNullOrEmpty(contentType))
{
return HeyRed.Mime.MimeTypesMap.GetMimeType(fileName);
}
return contentType;
One correct answer is:
/a/b/*[self::c or self::d or self::e]
Do note that this
a/b/*[local-name()='c' or local-name()='d' or local-name()='e']
is both too-long and incorrect. This XPath expression will select nodes like:
OhMy:c
NotWanted:d
QuiteDifferent:e
When inside a component script tag you can use the router and do something like this
this.$router.push('/url-path')
It's work for me.This will help you definitely
showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked){
// show password
password_login.setTransformationMethod(PasswordTransformationMethod.getInstance());
Log.i("checker", "true");
}
else{
Log.i("checker", "false");
// hide password
password_login.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Please take a look at Thread.UncaughtExceptionHandler
Better (alternative) way is to use Callable and Future to get the same result...
Just wanted to mention react-router v4 changed radically since this question was posted/answed.
There is no <Match>
component any more! <Switch>
is to make sure only the first match is rendered. <Redirect>
well .. redirects to another route. Use or leave out exact
to either in- or exclude a partial match.
See the docs. They are great. https://reacttraining.com/react-router/
Here's an example I hope is useable to answer your question.
<Router>
<div>
<Redirect exact from='/' to='/front'/>
<Route path="/" render={() => {
return (
<div>
<h2>Home menu</h2>
<Link to="/front">front</Link>
<Link to="/back">back</Link>
</div>
);
}} />
<Route path="/front" render={() => {
return (
<div>
<h2>front menu</h2>
<Link to="/front/help">help</Link>
<Link to="/front/about">about</Link>
</div>
);
}} />
<Route exact path="/front/help" render={() => {
return <h2>front help</h2>;
}} />
<Route exact path="/front/about" render={() => {
return <h2>front about</h2>;
}} />
<Route path="/back" render={() => {
return (
<div>
<h2>back menu</h2>
<Link to="/back/help">help</Link>
<Link to="/back/about">about</Link>
</div>
);
}} />
<Route exact path="/back/help" render={() => {
return <h2>back help</h2>;
}} />
<Route exact path="/back/about" render={() => {
return <h2>back about</h2>;
}} />
</div>
</Router>
Hope it helped, let me know. If this example is not answering your question well enough, tell me and I'll see if I can modify it.
In some cases it is possible using @import "file.css", and most modern browsers should support this, older browsers such as NN4, will go slightly nuts.
Note: the import statement must precede all other declarations in the file, and test it on all your target browsers before using it in production.
String jsonStr = "{\"a\": \"A\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
You can use jQuery's css
function to test the CSS properties, eg. if ($('node').css('display') == 'block')
.
Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.
Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.
Not sure if this is what you're looking for.
http://code.google.com/p/monad-tutorial/ is a work in progress to address exactly this question.
You are accessing an object that is not defined.
The solution is check for null or undefined (to see whether the object exists) and only then iterate.
If you have Android open source code, you can find the styles definition under:
src/frameworks/base/core/res/res/values
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">
@android:drawable/btn_check_label_background
</item>
<item name="android:button">
?android:attr/listChoiceIndicatorMultiple
</item>
</style>
First check the $_GET['s']
is set or not. Change your conditions like this
<?php
if (isset($_GET['s']) && $_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif (isset($_GET['s']) && $_GET['s'] == null)
echo "<body>"
?>
And also handle properly your ifelse
conditions
You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:
To send your own cookies to the server, you can use the cookies parameter:
>>> cookies = dict(cookies_are='working')
>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
A python 3 adaption of søren-løvborg's answer
from html.parser import HTMLParser
from html.entities import html5
class HTMLTextExtractor(HTMLParser):
""" Adaption of http://stackoverflow.com/a/7778368/196732 """
def __init__(self):
super().__init__()
self.result = []
def handle_data(self, d):
self.result.append(d)
def handle_charref(self, number):
codepoint = int(number[1:], 16) if number[0] in (u'x', u'X') else int(number)
self.result.append(unichr(codepoint))
def handle_entityref(self, name):
if name in html5:
self.result.append(unichr(html5[name]))
def get_text(self):
return u''.join(self.result)
def html_to_text(html):
s = HTMLTextExtractor()
s.feed(html)
return s.get_text()
I suggest you first call shutil.copytree
, and if an exception is thrown, then retry with shutil.copy
.
import shutil, errno
def copyanything(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
If any of these answers above don't work, and you're on an apache server, adding the following to your .htaccess file:
//most of the common formats, add any that apply
AddType video/mp4 .mp4
AddType audio/mp4 .m4a
AddType video/mp4 .m4v
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/webm .webm
I had a similar problem and adding this solved all my playback issues.
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
You know what's cooler than -P
? nothing
If you use this server more than a few times, setup/create a ~/.ssh/config
file with an entry like:
Host www.myserver.com
Port 80
or
Host myserver myserver80 short any.name.u.want yes_anything well-within-reason
HostName www.myserver.com
Port 80
User username
Then you can use:
scp [email protected]:/root/file.txt .
or
scp short:/root/file.txt .
You can use anything on the "Host" line with ssh, scp, rsync, git & more
There are MANY configuration option that you can use in config files, see:
man ssh_config
A better way to set the location in JS is via:
window.location.href = 'https://stackoverflow.com';
Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.
An alternative also it to use the Aggregate()
extension method.
var sum = arr.Aggregate((temp, x) => temp+x);
In C and C++ memory requirements of some variable :
signed char: -2^07 to +2^07-1
short: -2^15 to +2^15-1
int: -2^15 to +2^15-1
long: -2^31 to +2^31-1
long long: -2^63 to +2^63-1
signed char: -2^07 to +2^07-1
short: -2^15 to +2^15-1
int: -2^31 to +2^31-1
long: -2^31 to +2^31-1
long long: -2^63 to +2^63-1
depends on compiler and architecture of hardware
The international standard for the C language requires only that the size of short variables should be less than or equal to the size of type int, which in turn should be less than or equal to the size of type long.
I had installations of both Visual Studio 2019 and 2017. I tried installing the .NET Core 2.X SDK for VS2017 separately but with no luck.
The issue is, that I have .NET Core 3.0 SDK installed as default sdk-version, which VS2017 does not like.
My solution was to switch the SDK version for the specific project.
$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.100
Commit: cd82f021f4
Runtime Environment:
OS Name: Windows
OS Version: 10.0.18362
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.100\
Host (useful for support):
Version: 3.1.0
Commit: 65f04fb6db
.NET Core SDKs installed:
1.1.14 [C:\Program Files\dotnet\sdk]
2.1.202 [C:\Program Files\dotnet\sdk]
2.1.509 [C:\Program Files\dotnet\sdk]
2.2.110 [C:\Program Files\dotnet\sdk]
3.0.100 [C:\Program Files\dotnet\sdk]
3.1.100 [C:\Program Files\dotnet\sdk]
$ dotnet new globaljson --sdk-version 2.2.110 --force
Now, dotnet
will use the specified SDK version for this solution.
I have not found a way to do this system-wide without also messing up my 3.0 projects.
According to the following post, you can't do this with log4j: Use MaxBackupIndex in DailyRollingFileAppender -log4j
As far as I know, this functionality was supposed to make it into log4j 2.0 but that effort got sidetracked. According to the logback website, logback is the intended successor to log4j so you might consider using that.
There's an API called SLF4J which provides a common API to logging. It will load up the actual logging implementation at runtime so depending on the configuration that you have provided, it might use java.util.log or log4j or logback or any other library capable of providing logging facilities. There'll be a bit of up-front work to go from using log4j directly to using SLF4J but they provide some tools to automate this process. Once you've converted your code to use SLF4J, switching logging backends should simply be a case of changing the config file.
There's an easy way to do that. Very easy. Since I noticed that
$scope.yourModel = [];
removes all $scope.yourModel array list you can do like this
function deleteAnObjectByKey(objects, key) {
var clonedObjects = Object.assign({}, objects);
for (var x in clonedObjects)
if (clonedObjects.hasOwnProperty(x))
if (clonedObjects[x].id == key)
delete clonedObjects[x];
$scope.yourModel = clonedObjects;
}
The $scope.yourModel will be updated with the clonedObjects.
Hope that helps.
Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name
evaluates to a tuple and that tuple is the actual value the function is returning.
This explains better: Postman docs
Request body
While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.
form-data
multipart/form-data is the default encoding a web form uses to transfer data.This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.urlencoded
This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.
raw
A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.
binary
binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.
UPDATE
As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.
The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.
If you're behind a proxy server, just add your proxy settings in gradle.properties
systemProp.http.proxyHost=x.xx.xx.x
systemProp.http.proxyPort=xxxx
systemProp.https.proxyHost=x.xx.xx.x
systemProp.https.proxyPort=xxxx
It worked for me.
Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts
There is no limit. It only depends on your free memory and system maximum file size. But that doesn't mean you shouldn't take precautionary measure in tackling memory usage in your database. Always create a script that can delete rows that are out of use or that will keep total no of rows within a particular figure, say a thousand.
i've read the answers and i have done this:
cd repos
mv .git repos.git
cd repos.git
git config --bool core.bare true # from another answer
cd ../
mv repos.git ../
cd ../
rm -rf repos/ # or delete using a file manager if you like
this will leave the contents of repos/.git
as the bare repos.git
try this method given below, modify to suit your need.
SELECT
employment_status.staff_type,
COUNT(monthly_pay_register.age),
monthly_pay_register.BASIC_SALARY,
monthly_pay_register.TOTAL_MONTHLY_ALLOWANCES,
monthly_pay_register.MONTHLY_GROSS,
monthly_pay_register.TOTAL_MONTHLY_DEDUCTIONS,
monthly_pay_register.MONTHLY_PAY
FROM
(monthly_pay_register INNER JOIN deduction_logs
ON
monthly_pay_register.employee_info_employee_no = deduction_logs.employee_no)
INNER JOIN
employment_status ON deduction_logs.employee_no = employment_status.employee_no
WHERE
monthly_pay_register.`YEAR`=2017
and
monthly_pay_register.`MONTH`='may'
You can create a detached master branch using only porcelain Git commands:
git init
touch GO_AWAY
git add GO_AWAY
git commit -m "GO AWAY - this branch is detached from reality"
That gives us a master branch with a rude message (you may want to be more polite). Now we create our "real" branch (let's call it trunk in honour of SVN) and divorce it from master:
git checkout -b trunk
git rm GO_AWAY
git commit --amend --allow-empty -m "initial commit on detached trunk"
Hey, presto! gitk --all will show master and trunk with no link between them.
The "magic" here is that --amend causes git commit to create a new commit with the same parent as the current HEAD, then make HEAD point to it. But the current HEAD doesn't have a parent as it's the initial commit in the repository, so the new HEAD doesn't get one either, making them detached from each other.
The old HEAD commit doesn't get deleted by git-gc because refs/heads/master still points to it.
The --allow-empty flag is only needed because we're committing an empty tree. If there were some git add's after the git rm then it wouldn't be necessary.
In truth, you can create a detached branch at any time by branching the initial commit in the repository, deleting its tree, adding your detached tree, then doing git commit --amend.
I know this doesn't answer the question of how to modify the default branch on the remote repository, but it gives a clean answer on how to create a detached branch.
To undo git checkout
do git checkout -
, similarly to cd
and cd -
in shell.
It's quite Easy to show a Toast Message in Flutter.Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));
You want to use the Integer.parseInt(String) method.
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
You can also do as follows:
public static int[][] copy(int[][] src) {
int[][] dst = new int[src.length][];
for (int i = 0; i < src.length; i++) {
dst[i] = Arrays.copyOf(src[i], src[i].length);
}
return dst;
}
Using netbeans New Entity Classes from Database with a mysql auto_increment column, creates you an attribute with the following hibernate.hbm.xml: id is auto increment
This code copies all stored procedures in the Master database to the target database, you can copy just the procedures you like by filtering the query on procedure name.
@sql is defined as nvarchar(max), @Name is the target database
DECLARE c CURSOR FOR
SELECT Definition
FROM [ResiDazeMaster].[sys].[procedures] p
INNER JOIN [ResiDazeMaster].sys.sql_modules m ON p.object_id = m.object_id
OPEN c
FETCH NEXT FROM c INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = REPLACE(@sql,'''','''''')
SET @sql = 'USE [' + @Name + ']; EXEC(''' + @sql + ''')'
EXEC(@sql)
FETCH NEXT FROM c INTO @sql
END
CLOSE c
DEALLOCATE c
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
Updated version of HCD's solution which avoids conflict:
var y = $j(window).scrollTop();
$j("html, body").animate({ scrollTop: y + $j(window).height() }, 600);
SELECT author FROM lyrics WHERE author LIKE 'B%';
Make sure you have an index on author
, though!
This declaration:
double F[1000][1000000];
would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.
None of the answers says about the way, when I'll have .css.erb
extension, how to reference images. For me worked both in production and development as well :
The asset pipeline automatically evaluates ERB. This means if you add an erb extension to a CSS asset (for example, application.css.erb
), then helpers like asset_path
are available in your CSS rules:
.class { background-image: url(<%= asset_path 'image.png' %>) }
This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as app/assets/images/image.png
, which would be referenced here. If this image is already available in public/assets
as a fingerprinted file, then that path is referenced.
If you want to use a data URI - a method of embedding the image data directly into the CSS file - you can use the asset_data_uri
helper.
.logo { background: url(<%= asset_data_uri 'logo.png' %>) }
This inserts a correctly-formatted data URI into the CSS source.
Note that the closing tag cannot be of the style -%>.
I am having this problem all the time, so I made a tiny tool to convert text to an escaped multi-line Objective-C string:
http://multilineobjc.herokuapp.com/
Hope this saves you some time.
When I got this error, it turned out I had a call to the map function inside my "async" function, so this error message was actually referring to the map function not being marked as "async". I got around this issue by taking the "await" call out of the map function and coming up with some other way of getting the expected behavior.
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
I had the same problem with a Galaxy S3 mini (android 4.1.2) and I simply made my custom checkbox extend AppCompatCheckBox instead of CheckBox. Now it works perfectly.
watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.
You can set read watchpoints on memory locations:
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:
gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.
So you have to expand them yourself:
gdb$ print $ebx
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()
Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.
gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.
The correct way depends on whether you only want a specific image in your content to have a border or there is a pattern in your code where certain images need to have a border. In the first case, go with the style attribute on the img element, otherwise give it a meaningful class name and define that border in your stylesheet.
I had the same problem. What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.
Configuring and running the maven-eclipse plugin, (for example from the command line mvn eclipse:eclipse
)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.
let date = new Date();
let dd = date.getDate();//day of month
let mm = date.getMonth();// month
let yyyy = date.getFullYear();//day of week
if (dd < 10) {//if less then 10 add a leading zero
dd = "0" + dd;
}
if (mm < 10) {
mm = "0" + mm;//if less then 10 add a leading zero
}
I find it's a lot easier (than accepted answer) to create a local subdomain by project and tell Apache to serve multiple sites by name.
For example, let's say you created a project under c:/wamp64/www/sites/mysite
, to be able to access it at http://mysite.localhost you simply need to do the following:
1. Tell your machine to answer to different names
Add 127.0.0.1 mysite.localhost
to C:\windows\system32\drivers\etc\hosts
2. Flush your DNS cache
Open a Command Prompt as administrator and type net stop dnscache
, then net start dnscache
.
3. Tell Apache where to look Click on Wamp's icon in tray, go to Apache -> httpd.conf, and add this at the end:
# Tells Apache to identify which site by name
NameVirtualHost *:80
# Tells Apache to serve the default WAMP Server page to "localhost"
<VirtualHost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>
# Tells Apache to serve Client 1's pages to "client1.localhost"
# Duplicate and modify this block to add another client
<VirtualHost 127.0.0.1>
# The name to respond to
ServerName client1.localhost
# Folder where the files live
DocumentRoot "C:/wamp64/www/sites/mysite"
# A few helpful settings...
<Directory "C:/wamp64/www/sites/mysite">
allow from all
order allow,deny
# Enables .htaccess files for this site
AllowOverride All
</Directory>
# Apache will look for these two files, in this order, if no file is specified in the URL
DirectoryIndex index.html index.php
</VirtualHost>
(source)
4. Restart Apache Click on Wamp's icon in tray, select "restart"
5. Define a base url
Go to your project folder, add <base href="http://mysite.localhost" />
to your <head>
section to prevent /links to server root from being broken.
Personally, I inject this html code dynamically into my template using PHP (something like $site_root = (IS_LOCALHOST) ? '<base href="http://mysite.localhost" />' : null;
) so I don't have to bother removing that once on production.
Using keyboardShouldPersistTaps
in the ScrollView
you can pass in "handled", which deals with the issues that people are saying comes with using the ScrollView. This is what the documentation says about using 'handled': the keyboard will not dismiss automatically when the tap was handled by a children, (or captured by an ancestor).
Here is where it's referenced.
You can try this...
<div class="image">
<img src="" alt="" />
<h2>Text you want to display over the image</h2>
</div>
CSS
.image {
position: relative;
width: 100%; /* for IE 6 */
}
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
In this example, the line do_something_else()
will not be executed if do_not_continue
is True
. Control will return, instead, to whichever function called some_function
.
def some_function():
if do_not_continue:
return # implicitly, this is the same as saying `return None`
do_something_else()
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
...
(three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed. This is not specific to React. It is a Javascript operator.
All these answers here are helpful, but I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator).
1. Combine Arrays (Concatenate Arrays)
There are a variety of ways to combine arrays, but the spread operator allows you to place this at any place in an array. If you'd like to combine two arrays and place elements at any point within the array, you can do as follows:
var arr1 = ['two', 'three'];
var arr2 = ['one', ...arr1, 'four', 'five'];
// arr2 = ["one", "two", "three", "four", "five"]
2. Copying Arrays
When we wanted a copy of an array, we used to have the Array.prototypr.slice() method. But, you can do the same with the spread operator.
var arr = [1,2,3];
var arr2 = [...arr];
// arr2 = [1,2,3]
3. Calling Functions without Apply
In ES5, to pass an array of two numbers to the doStuff()
function, you often use the Function.prototype.apply() method as follows:
function doStuff (x, y, z) { }
var args = [0, 1, 2];
// Call the function, passing args
doStuff.apply(null, args);
However, by using the spread operator, you can pass an array into the function.
doStuff(...args);
4. Destructuring Arrays
You can use destructuring and the rest operator together to extract the information into variables as you'd like them:
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
5. Function Arguments as Rest Parameters
ES6 also has the three dots ( ...) which is a rest parameter that collects all remaining arguments of a function into an array.
function f(a, b, ...args) {
console.log(args);
}
f(1,2,3,4,5);
// [ 3, 4, 5 ]
6. Using Math Functions
Any function where spread is used as the argument can be used by functions that can accept any number of arguments.
let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1
7. Combining Two Objects
You can use the spread operator to combine two objects. This is an easy and cleaner way to do it.
var carType = {
model: 'Toyota',
yom: '1995'
};
var carFuel = 'Petrol';
var carData = {
...carType,
carFuel
}
console.log(carData);
// {
// model: 'Toyota',
// yom: '1995',
// carFuel = 'Petrol'
// }
8. Separate a String into Separate Characters
You can use the spread operator to spread a string into separate characters.
let chars = ['A', ...'BC', 'D'];
console.log(chars); // ["A", "B", "C", "D"]
You can think of more ways to use the Spread Operator. What I have listed here are the popular use cases of it.
Thanks @twoleggedhorse.
Here is the solution.
First we created a function
CREATE FUNCTION GetAIntFromStoredProc(@parm Nvarchar(50)) RETURNS INTEGER
AS
BEGIN
DECLARE @id INTEGER
set @id= (select TOP(1) id From tbl where col=@parm)
RETURN @id
END
then we do the select query
Select col1, col2, col3,
GetAIntFromStoredProc(T.col1) As col4
From Tbl as T
Where col2=@parm
In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.
It's easy to implement and degrades nicely for screen readers and users with no javascript.
Take a look at the two examples here: http://attardi.org/labels/
I usually use the second method (labels2) on my forms.
This is all I had to add to add get anaconda working for zsh.
echo ". /anaconda3/etc/profile.d/conda.sh" >> ~/.zshrc
source ~/.zshrc
Based on the accepted answer, for those who encountered a similar issue, with full schema qualification:
([MyDataBase].[MySchemaName].[MyTable]
)... results in an error, you need to be in the context of that DB
That is, the following will throw an error:
DBCC CHECKIDENT ([MyDataBase].[MySchemaName].[MyTable], RESEED, 0)
Enclose the fully-qualified table name with single quotes instead:
DBCC CHECKIDENT ('[MyDataBase].[MySchemaName].[MyTable]', RESEED, 0)
Just using replace
:
var text = 'Hello World';_x000D_
_x000D_
new_text = text.replace(' ', '_');_x000D_
_x000D_
console.log(new_text);
_x000D_
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
You can achieve that using DATE_FORMAT() (click the link for more other formats)
SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY,
DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();
I have converted it to int because my Price field was int and Average method return double .I hope this will help
Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.
So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override
modifier and provide a custom implementation.
public abstract class E
{
public abstract void AbstractMethod(int i);
public virtual void VirtualMethod(int i)
{
// Default implementation which can be overridden by subclasses.
}
}
public class D : E
{
public override void AbstractMethod(int i)
{
// You HAVE to override this method
}
public override void VirtualMethod(int i)
{
// You are allowed to override this method.
}
}
IMHO, a very nice solution is to use c++11 emplace_back function:
revenue.emplace_back("string", map[i].second);
It just creates a new element in place.
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
I did this a bit different. In my gridview I set the AutoGenerateDeleteButton="true"
. To find the delete button I use jQuery and add a click event to the found Anchors.
jQuery("a").filter(function () {
return this.innerHTML.indexOf("Delete") == 0;
}).click(function () { return confirm("Are you sure you want to delete this record?");
});
This is quick and simple for what I need to do. Just be mindful that Every Anchor in the page that displays Delete will be selected by jQuery and will have the event added to it.
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
Your quotes are in the wrong spot. Here's a simple example:
<div style={{backgroundColor: "#FF0000"}}>red</div>
Here's a solution that also works on Firefox:
transition: all 0.3s ease, background-position 1ms;
I made a small demo: http://jsfiddle.net/aWzwh/
You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.
$(items).each(function(i, item){
setTimeout(function(){
geoLocate("my address", function(myLatlng){
...
});
}, 200 * i);
}
Two things. First, you must base64 decode the mykey.pem
file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey
ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec
, which is based on the SubjectPublicKeyInfo
ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
// ...
String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
If the time is in milliseconds and one need to preserve them:
DECLARE @value VARCHAR(32) = '1561487667713';
SELECT DATEADD(MILLISECOND, CAST(RIGHT(@value, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(@value, 10) AS INT), '1970-01-01T00:00:00'))
Query Execution Time:
DECLARE @EndTime datetime
DECLARE @StartTime datetime
SELECT @StartTime=GETDATE()
` -- Write Your Query`
SELECT @EndTime=GETDATE()
--This will return execution time of your query
SELECT DATEDIFF(MILLISECOND,@StartTime,@EndTime) AS [Duration in millisecs]
Query Out Put Will be Like:
To Optimize Query Cost :
Click on your SQL Management Studio
Run your query and click on Execution plan beside the Messages tab of your query result. you will see like
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I was fighting with this issue for a while. In my case I was using in complex type (List) as the Item Source and was using a KeyType as the selected value. On the load event, the KeyType was getting set to null. This caused everything to break. None of the sub elements would get updated when the key changed. It turned out that when I added a check to make sure the proposed value for KeyType was not null, everything worked as expected.
#region Property: SelectedKey
// s.Append(string.Format("SelectedKey : {0} " + Environment.NewLine, SelectedKey.ToString()));
private KeyType _SelectedKey = new KeyType();
public KeyType SelectedKey
{
get { return _SelectedKey; }
set
{
if(value != null )
if (!_SelectedKey.Equals(value))
{
_SelectedKey = value;
OnPropertyChanged("SelectedKey");
}
}
}
#endregion SelectedKey
A more readable variant using an extension.
extension Dictionary {
func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
var mutableCopy = self
for (key, value) in dict {
// If both dictionaries have a value for same key, the value of the other dictionary is used.
mutableCopy[key] = value
}
return mutableCopy
}
}
It is caused by a lack of precision with doubles / decimals (i.e. - the function will not always give the result you expect).
See the following link: MSDN on Math.Round
Here is the relevant quote:
Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter.This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.
What about this:
double? amount = string.IsNullOrEmpty(strAmount) ? (double?)null : Convert.ToDouble(strAmount);
Of course, this doesn't take into account the convert failing.
Try to use the rack-cors gem. And add the header field in your Ajax call.
@unutbu's answer is spot on, just wanted to add a warning that your mask needs to be dtype bool, not 'object'. Ie your mask can't have ever had any nan's. See here - even if your mask is nan-free now, it will remain 'object' type.
The inverse of an 'object' series won't throw an error, instead you'll get a garbage mask of ints that won't work as you expect.
In[1]: df = pd.DataFrame({'A':[True, False, np.nan], 'B':[True, False, True]})
In[2]: df.dropna(inplace=True)
In[3]: df['A']
Out[3]:
0 True
1 False
Name: A, dtype object
In[4]: ~df['A']
Out[4]:
0 -2
0 -1
Name: A, dtype object
After speaking with colleagues about this one I have an explanation: It looks like pandas is reverting to the bitwise operator:
In [1]: ~True
Out[1]: -2
As @geher says, you can convert it to bool with astype before you inverse with ~
~df['A'].astype(bool)
0 False
1 True
Name: A, dtype: bool
(~df['A']).astype(bool)
0 True
1 True
Name: A, dtype: bool
The root cause is: your environment variable LC_ALL
is missing or invalid somehow
Short answer-
just run the following command:
$ export LC_ALL=C
If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc
file.
Long answer-
Here is my locale
settings:
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C
Python2.7
$ uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
$ python --version
Python 2.7.9
$ pip --version
pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
$ unset LC_ALL
$ pip install virtualenv
Traceback (most recent call last):
File "/usr/local/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib/python2.7/locale.py", line 579, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
$ export LC_ALL=C
$ pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages
sudo apt-get install curl-devel
sudo apt-get install libcurl-dev
(will install the default alternative)
OR
sudo apt-get install libcurl4-openssl-dev
(the OpenSSL variant)
OR
sudo apt-get install libcurl4-gnutls-dev
(the gnutls variant)
I don't think mongodb supports this type of selective upserting. I have the same problem as LeMiz, and using update(criteria, newObj, upsert, multi) doesn't work right when dealing with both a 'created' and 'updated' timestamp. Given the following upsert statement:
update( { "name": "abc" },
{ $set: { "created": "2010-07-14 11:11:11",
"updated": "2010-07-14 11:11:11" }},
true, true )
Scenario #1 - document with 'name' of 'abc' does not exist: New document is created with 'name' = 'abc', 'created' = 2010-07-14 11:11:11, and 'updated' = 2010-07-14 11:11:11.
Scenario #2 - document with 'name' of 'abc' already exists with the following: 'name' = 'abc', 'created' = 2010-07-12 09:09:09, and 'updated' = 2010-07-13 10:10:10. After the upsert, the document would now be the same as the result in scenario #1. There's no way to specify in an upsert which fields be set if inserting, and which fields be left alone if updating.
My solution was to create a unique index on the critera fields, perform an insert, and immediately afterward perform an update just on the 'updated' field.
If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+
.
You can then map
each element using the Number
function to convert it. Note that parseInt
will not work (i.e. arr.map(parseInt)
) because map
passes three arguments to the mapping function: the element, the index, and the original array. parseInt
accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaN
s in the result. However, Number
ignores any arguments other than the first, so it works directly.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]
You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]
With an anonymous function for the callback, you can decide what parameters to use, so parseInt
can also work.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]
I had the same problem as you mentioned here above and my code was doing great all day yesterday.
I kept on programming this morning and when I opened my application (my file with an Auto_Open sub), I got the Run-time error '13' Type mismatch, I went on the web to find answers, I tried a lot of things, modifications and at one point I remembered that I read somewhere about "Ghost" data that stays in a cell even if we don't see it.
My code do only data transfer from one file I opened previously to another and Sum it. My code stopped at the third SheetTab (So it went right for the 2 previous SheetTab where the same code went without stopping) with the Type mismatch message. And it does that every time at the same SheetTab when I restart my code.
So I selected the cell where it stopped, manually entered 0,00 (Because the Type mismatch comes from a Summation variables declared in a DIM as Double) and copied that cell in all the subsequent cells where the same problem occurred. It solved the problem. Never had the message again. Nothing to do with my code but the "Ghost" or data from the past. It is like when you want to use the Control+End and Excel takes you where you had data once and deleted it. Had to "Save" and close the file when you wanted to use the Control+End to make sure Excel pointed you to the right cell.
You'll need to create local variables for those columns, assign them during the select and use them for your conditional tests.
declare @yes_ans int,
@no_ans int,
@na_ans int
SELECT @yes_ans = yes_ans, @no_ans = no_ans, @na_ans = na_ans
from dbo.qrc_maintally
where school_id = @SchoolId
If @yes_ans > @no_ans and @yes_ans > @na_ans
begin
Set @Final = 'Yes'
end
-- etc.
I was also facing same error when I was inserting the data into HIVE external table which was pointing to Elastic search cluster.
I replaced the older JAR elasticsearch-hadoop-2.0.0.RC1.jar
to elasticsearch-hadoop-5.6.0.jar
, and everything worked fine.
My Suggestion is please use the specific JAR as per the elastic search version. Don't use older JARs if you are using newer version of elastic search.
Thanks to this post Hive- Elasticsearch Write Operation #409
You should consider svcutil (svcutil question)
Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.
Note that various 3rd party tools also exist for this.
The newer PHP-Versions provide some new classes called DateTime
, DateInterval
, DateTimeZone
and DatePeriod
. The cool thing about this classes is, that it considers different timezones, leap years, leap seconds, summertime, etc. And on top of that it's very easy to use. Here's what you want with the help of this objects:
// Create two new DateTime-objects...
$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2006-04-14T11:30:00');
// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);
// Call the format method on the DateInterval-object
echo $diff->format('%a Day and %h hours');
The DateInterval-object, which is returned also provides other methods than format
. If you want the result in hours only, you could to something like this:
$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2006-04-14T11:30:00');
$diff = $date2->diff($date1);
$hours = $diff->h;
$hours = $hours + ($diff->days*24);
echo $hours;
And here are the links for documentation:
All these classes also offer a procedural/functional way to operate with dates. Therefore take a look at the overview: http://php.net/manual/book.datetime.php
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Not really what you're looking for, but it may be useful to you. Face Detection/Computer Vision algorithms in MATLAB.
I fixed this issue by installing JDK x64. I guess you're using jdk x86 and it's not enough memory for gradle.
I just found a real-world application and will use it more often now, I think.
If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). You can use instanceof
to check if the first parameter of your function is an instance of jQuery.Event
and react appropriately.
var myFunction = function (el) {
if (el instanceof $.Event)
// event specific code
else
// generic code
};
$('button').click(recalc); // Will execute event specific code
recalc('myParameter'); // Will execute generic code
In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. The code I used:
var recalc = function (el) {
el = (el == undefined || el instanceof $.Event) ? $('span.allItems') : $(el);
// calculate...
};
I have edited the given above example...
public class YourActivity extends implements OnMarkerClickListener
{
......
private void setMarker()
{
.......
googleMap.setOnMarkerClickListener(this);
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
......
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show();
}
}
you also can add this inline instead of config, just add it to the same file before you add your own disable stuff
/* eslint-env es6 */
/* eslint-disable no-console */
my case was disable a file and eslint-disable were not working for me alone
/* eslint-env es6 */
/* eslint-disable */
Example 1:
This is how the and operator works.
x and y => if x is false, then x, else y
So in other words, since mylist1
is not False
, the result of the expression is mylist2
. (Only empty lists evaluate to False
.)
Example 2:
The &
operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:
>>> 3 & 1
1
It's easier to see what's happening using a binary literal (same numbers as above):
>>> 0b0011 & 0b0001
0b0001
Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.
So, given a couple statements about my car
The logical "and" of these two statements is:
(is my car red?) and (does car have wheels?) => logical true of false value
Both of which are true, for my car at least. So the value of the statement as a whole is logically true.
The bitwise "and" of these two statements is a little more nebulous:
(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number
If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that &
is interchangeable with and
, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError
.
Example 3 and 4:
Numpy implements arithmetic operations for arrays:
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.
But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.
So to answer your and
vs &
question: Use and
.
The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.
The logical operations (and
, or
, not
), however, are used all the time.
You could modify .adm
and add
.adm{
clear:both;
}
That should make it move to a new line
You can use:
sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>
Example:
sed -i -e 's/Hello/Bye/' file.txt
This works flawless in Mac.
See the details about entryComponent
:
If you are loading any component dynamically then you need to put it in both declarations
and entryComponent
:
@NgModule({
imports: [...],
exports: [...],
entryComponents: [ConfirmComponent,..],
declarations: [ConfirmComponent,...],
providers: [...]
})
public - can be access by anyone anywhere.
private - can only be accessed from with in the class it is a part of.
protected - can only be accessed from with in the class or any object that inherits off of the class.
Nothing is like null but in VB.
Static means you have one instance of that object, method for every instance of that class.
Use Datepart function: DATEPART(datepart, date)
E.g#
SELECT DatePart(@YourVar, hh)*60) + DatePart(@YourVar, mi)*60)
This will give you total time of day in minutes allowing you to compare more easily.
You can use DateDiff if your dates are going to be the same, otherwise you'll need to strip out the date as above
I found this warning too then I fixed it by using SSL=false suffix to the connection string like this example code.
Example:
connectionString = "jdbc:mysql://{server-name}:3306/%s?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"
timer.scheduleAtFixedRate( new Task(), 1000,3000);
It is easier with Kotlin using for-in loop:
for (childView in ll.children) {
//childView is a child of ll
}
Here ll
is id
of LinearLayout
defined in layout XML.
in
Python strings and listsHere are a few useful examples that speak for themselves concerning the in
method:
"foo" in "foobar"
True
"foo" in "Foobar"
False
"foo" in "Foobar".lower()
True
"foo".capitalize() in "Foobar"
True
"foo" in ["bar", "foo", "foobar"]
True
"foo" in ["fo", "o", "foobar"]
False
["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]
Caveat. Lists are iterables, and the in
method acts on iterables, not just strings.
You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.
const newTodo = new Todo({text:'cook dinner'});
newTodo.save().then((docs) => {
console.log('todo saved',docs);
mongoose.connection.close();
},(e) => {
console.log('unable to save');
});
Bootstrap 4
Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Bootstrap horizontal menu collapse to sidemenu
Bootstrap 3
I think what you're looking for is generally known as an "off-canvas" layout. Here is the standard off-canvas example from the official Bootstrap docs: http://getbootstrap.com/examples/offcanvas/
The "official" example uses a right-side sidebar the toggle off and on separately from the top navbar menu. I also found these off-canvas variations that slide in from the left and may be closer to what you're looking for..
http://www.bootstrapzero.com/bootstrap-template/off-canvas-sidebar http://www.bootstrapzero.com/bootstrap-template/facebook
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
If you have a request going to an application in the site, make sure you set maxRequestLength in the root web.config. The maxRequestLength in the applications's web.config appears to be ignored.
I've got the same problem here. I have an UTF-8 Page an need to post to an ISO-8859-1 server.
Looks like IE can't handle ISO-8859-1. But it can handle ISO-8859-15.
<form accept-charset="ISO-8859-15">
...
</form>
So this worked for me, since ISO-8859-1 and ISO-8859-15 are almost the same.
We can use TRUNC function in Oracle DB. Here is an example.
SELECT TRUNC(TO_DATE('01 Jan 2018 08:00:00','DD-MON-YYYY HH24:MI:SS')) FROM DUAL
Output: 1/1/2018
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Didnt work for me.
I created a new key and string value and managed to get it working
Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
1.2975118E7
is scientific notation.
1.2975118E7 = 1.2975118 * 10^7 = 12975118
Also, Math.round(f)
returns an integer. You can't use it to get your desired format x.xx
.
You could use String.format
.
String s = String.format("%.2f", 1.2975118);
// 1.30
Here is an example of my custom Filter class:
package com.dawson.controller.filter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class DawsonApiFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getHeader("x-dawson-nonce") == null || req.getHeader("x-dawson-signature") == null) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("application/json");
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required headers not specified in the request");
return;
}
chain.doFilter(request, response);
}
}
And I added it to the Spring boot configuration by adding it to Configuration class as follows:
package com.dawson.configuration;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.dawson.controller.filter.DawsonApiFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@SpringBootApplication
public class ApplicationConfiguration {
@Bean
public FilterRegistrationBean dawsonApiFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new DawsonApiFilter());
// In case you want the filter to apply to specific URL patterns only
registration.addUrlPatterns("/dawson/*");
return registration;
}
}
See if the plugin has a 'skip' configuration parameter. Nearly all do. if it does, just add it to a declaration in the child:
<plugin>
<groupId>group</groupId>
<artifactId>artifact</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
If not, then use:
<plugin>
<groupId>group</groupId>
<artifactId>artifact</artifactId>
<executions>
<execution>
<id>TheNameOfTheRelevantExecution</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
Here is one that I have been using: -
[<1000000]0.00," KB";[<1000000000]0.00,," MB";0.00,,," GB"
Seems to work fine.
in .pro : LIBS += Ole32.lib OleAut32.lib Psapi.lib advapi32.lib
in .h/.cpp: #pragma comment(lib,"user32.lib")
#pragma comment(lib,"psapi.lib")
If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.
def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
'''
low and high are colors that will be used for the two
ends of the spectrum. they can be either color strings
or rgb color tuples
'''
c = mcolors.ColorConverter().to_rgb
if isinstance(low, basestring): low = c(low)
if isinstance(high, basestring): high = c(high)
return make_colormap([low, c('white'), 0.5, c('white'), high])
The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo:
For some reason using python3 I had to escape the "\"-sign
somestring.replace('\\n', '')
Hope this helps someone else!
Below might be useful.
Source: https://msdn.microsoft.com/en-us/library/ms175976.aspx
BEGIN TRANSACTION;
BEGIN TRY
-- your code --
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
ES6+ solutions:
To see the structure of form data:
console.log([...formData])
To see each key-value pair:
for (let [key, value] of formData.entries()) {
console.log(`${key}: ${value}`);
}
If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }
:
$.ajax({
url: 'yourURL',
type: 'POST',
data: yourData,
xhrFields: { responseType: 'blob' },
success: function (data, textStatus, jqXHR) {
let src = window.URL.createObjectURL(data);
}
});
"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.
The reason why a rebase is then better than a merge is that:
I confirm that the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.
However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).
On that topic (rebase then merge workflow), barraponto mentions in the comments two interesting posts, both from randyfay.com:
Using this technique, your work always goes on top of the public branch like a patch that is up-to-date with current
HEAD
.
(a similar technique exists for bazaar)
git push --force
(instead of a git pull --rebase
for instance)From your post, I understand that you cannot set the width to your li.
How about this?
ul {
border:2px solid red;
display:inline-block;
}
li {
display:inline;
padding:0 30%; /* try adjusting the side % to give a feel of center aligned.*/
}
_x000D_
<ul>
<li>Hello</li>
<li>Hezkdhkfskdhfkllo</li>
<li>Hello</li>
</ul>
_x000D_
Here's a demo. http://codepen.io/anon/pen/HhBwx
array1.NonIntersect(array2);
Nonintersect such operator is not present in Linq you should do
except -> union -> except
a.except(b).union(b.Except(a));
I like the answer indirectly given by Gafter. However, I propose it is wrong. I changed Gafter's code a little. It compiles and it runs for a while then it bombs where Gafter predicted it would
class Box<T> {
final T x;
Box(T x) {
this.x = x;
}
}
class Loophole {
public static <T> T[] array(final T... values) {
return (values);
}
public static void main(String[] args) {
Box<String> a = new Box("Hello");
Box<String> b = new Box("World");
Box<String> c = new Box("!!!!!!!!!!!");
Box<String>[] bsa = array(a, b, c);
System.out.println("I created an array of generics.");
Object[] oa = bsa;
oa[0] = new Box<Integer>(3);
System.out.println("error not caught by array store check");
try {
String s = bsa[0].x;
} catch (ClassCastException cause) {
System.out.println("BOOM!");
cause.printStackTrace();
}
}
}
The output is
I created an array of generics.
error not caught by array store check
BOOM!
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at Loophole.main(Box.java:26)
So it appears to me you can create generic array types in java. Did I misunderstand the question?
A little different to the other answers, using a similar concept but divs instead of pseudoclasses:
input {_x000D_
position: absolute;_x000D_
left: 10px;_x000D_
top: 10px;_x000D_
width: 50px;_x000D_
height: 20px;_x000D_
padding: 0px;_x000D_
font-size: 14pt;_x000D_
border: solid 0.5px #000;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.spinner-button {_x000D_
position: absolute;_x000D_
cursor: default;_x000D_
z-index: 2;_x000D_
background-color: #ccc;_x000D_
width: 14.5px;_x000D_
text-align: center;_x000D_
margin: 0px;_x000D_
pointer-events: none;_x000D_
height: 10px;_x000D_
line-height: 10px;_x000D_
}_x000D_
_x000D_
#inc-button {_x000D_
left: 46px;_x000D_
top: 10.5px;_x000D_
}_x000D_
_x000D_
#dec-button {_x000D_
left: 46px;_x000D_
top: 20.5px;_x000D_
}
_x000D_
<input type="number" value="0" min="0" max="100"/>_x000D_
<div id="inc-button" class="spinner-button">+</div>_x000D_
<div id="dec-button" class="spinner-button">-</div>
_x000D_
You simply need to use the asset
helper function in Laravel. (The url
helper can also be used in this manner)
<img src="{{ asset('images/arrow.gif') }}" />
For the absolute path, you use public_path
instead.
<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>
If you are providing the URL to a public image from a controller (backend) you can use asset
as well, or secure_asset
if you want HTTPS. eg:
$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif
return $secure_url;
Lastly, if you want to go directly to the image on a given route you can redirect to it:
return \Redirect::to($secure_url);
More Laravel helper functions can be found here
EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'
; worked for me.
closing the varchar
/string
with two pairs of single quotes did the trick. Other option could be to use using
keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'
; Remember using
keyword will not work, if you are using EXECUTE IMMEDIATE
to execute DDL's with parameters, however, using quotes will work for DDL's.
You can just use an object:
var test = {}
test[2300] = 'Some string';
The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:
SELECT *
FROM server1table
INNER JOIN server2.database.dbo.server2table ON .....
This is fairly easy, using marshalling.
Top of file
using System.Runtime.InteropServices
Function
byte[] getBytes(CIFSPacket str) {
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
And to convert it back:
CIFSPacket fromBytes(byte[] arr) {
CIFSPacket str = new CIFSPacket();
int size = Marshal.SizeOf(str);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
Marshal.FreeHGlobal(ptr);
return str;
}
In your structure, you will need to put this before a string
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;
And make sure SizeConst is as big as your biggest possible string.
And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx
This is not a very nice fix but it works:
CSS:
.new-tab-opener
{
display: none;
}
HTML:
<a data-href="http://www.google.com/" href="javascript:">Click here</a>
<form class="new-tab-opener" method="get" target="_blank"></form>
Javascript:
$('a').on('click', function (e) {
var f = $('.new-tab-opener');
f.attr('action', $(this).attr('data-href'));
f.submit();
});
Live example: http://jsfiddle.net/7eRLb/
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages. It's easy to forget that. They're just names that point to objects, in this case an integer on each iteration.
Your class:
class name {
public:
string first;
string last;
name() { } //Default constructor.
name(string a, string b){
first = a;
last = b;
}
};
Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.
So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.
Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.
.left {
float: left;
width: 125px;
text-align: right;
margin: 2px 10px;
display: inline;
}
.right {
float: left;
text-align: left;
margin: 2px 10px;
display: inline;
}
This is a really old question, but I came across this on a search and I think I know the source of your problem.
JSON does not allow "real" newlines in its data; it can only have escaped newlines. See the answer from @YOU. According to the question, it looks like you attempted to escape line breaks in Python two ways: by using the line continuation character ("\"
) or by using "\n"
as an escape.
But keep in mind: if you are using a string in python, special escaped characters ("\t"
, "\n"
) are translated into REAL control characters! The "\n"
will be replaced with the ASCII control character representing a newline character, which is precisely the character that is illegal in JSON. (As for the line continuation character, it simply takes the newline out.)
So what you need to do is to prevent Python from escaping characters. You can do this by using a raw string (put r
in front of the string, as in r"abc\ndef"
, or by including an extra slash in front of the newline ("abc\\ndef"
).
Both of the above will, instead of replacing "\n"
with the real newline ASCII control character, will leave "\n"
as two literal characters, which then JSON can interpret as a newline escape.
Think about this in terms of behaviour, not in terms of what methods there are. The method called method
has a particular behaviour if b
is true. It has different behaviour if b
is false. This means you should write two different tests for method
; one for each case. So instead of having three method-oriented tests (one for method
, one for method1
, one for method2
, you have two behaviour-oriented tests.
Related to this (I suggested this in another SO thread recently, and got called a four-letter word as a result, so feel free to take this with a grain of salt); I find it helpful to choose test names that reflect the behaviour that I'm testing, rather than the name of the method. So don't call your tests testMethod()
, testMethod1()
, testMethod2()
and so forth. I like names like calculatedPriceIsBasePricePlusTax()
or taxIsExcludedWhenExcludeIsTrue()
that indicate what behaviour I'm testing; then within each test method, test only the indicated behaviour. Most such behaviours will involve just one call to a public method, but may involve many calls to private methods.
Hope this helps.
Supposing your content is inside a string named mystring
...
You can use:
@Html.Raw(mystring)
Alternatively you can convert your string to HtmlString
or any other type that implements IHtmlString
in model or directly inline and use regular @
:
@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
surprise to see that no have given this syntax.
.each
syntax with data or collection
jQuery.each(collection, callback(indexInArray, valueOfElement));
OR
jQuery.each( jQuery('#list option'), function(indexInArray, valueOfElement){
//your code here
});
For Windows and Python 3.x, my two cents contribution about renaming the file on download :
pip install wget
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')
Truely working command line example :
python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"
Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc
included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo
Try this:
def to_utf8(str)
str = str.force_encoding('UTF-8')
return str if str.valid_encoding?
str.encode("UTF-8", 'binary', invalid: :replace, undef: :replace, replace: '')
end
FUNCTIONAL REQUIREMENTS the activities the system must perform
This is the way I got the solution. Simple and Sweet. Independent of Screen density:
export default class AwesomeProject extends Component {
constructor(props){
super(props);
this.state = {text: ""}
}
render() {
return (
<View
style={{
flex: 1,
backgroundColor: "#ececec",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}
>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 1"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<TextInput
style={{ flex: 0.8, height: 40, borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Text 2"
value={this.state.text}
/>
</View>
<View style={{ padding: 10, flexDirection: "row" }}>
<Button
onPress={onButtonPress}
title="Press Me"
accessibilityLabel="See an Information"
/>
</View>
</View>
);
}
}
You can add the script tags like how we use in the asp.net while doing client side validations like below.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
//Your code
});
</script>
There's no guaranteed way to force the user to clear the DNS cache, and it is often done by their ISP on top of their OS. It shouldn't take more than 24 hours for the updated DNS to propagate. Your best option is to make the transition seamless to the user by using something like mod_proxy with Apache to create a reverse proxy to your new server. That would cause all queries to the old server to still return the proper results and after a few days you would be free to remove the reverse proxy.
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
Subclipse for Eclipse has an excellent graphical diff plugin if you are using SVN (subversion) source control.
Here is an efficient Python implementation:
def PointInsideTriangle2(pt,tri):
'''checks if point pt(2) is inside triangle tri(3x2). @Developer'''
a = 1/(-tri[1,1]*tri[2,0]+tri[0,1]*(-tri[1,0]+tri[2,0])+ \
tri[0,0]*(tri[1,1]-tri[2,1])+tri[1,0]*tri[2,1])
s = a*(tri[2,0]*tri[0,1]-tri[0,0]*tri[2,1]+(tri[2,1]-tri[0,1])*pt[0]+ \
(tri[0,0]-tri[2,0])*pt[1])
if s<0: return False
else: t = a*(tri[0,0]*tri[1,1]-tri[1,0]*tri[0,1]+(tri[0,1]-tri[1,1])*pt[0]+ \
(tri[1,0]-tri[0,0])*pt[1])
return ((t>0) and (1-s-t>0))
and an example output:
In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx
In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.
Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db
and no longer by its IP.
Since itunesconnect has been changed i am updating with the new steps here.
You have to follow through these steps
Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
startActivity(i);
}
});