Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.
-Python Tricks
As mentioned in other answers - when you use an instance method you need to pass self
as the first argument - this is the source of the error.
With addition to that,it is important to understand that only instance methods take self
as the first argument in order to refer to the instance.
In case the method is Static you don't pass self
, but a cls
argument instead (or class_
).
Please see an example below.
class City:
country = "USA" # This is a class level attribute which will be shared across all instances (and not created PER instance)
def __init__(self, name, location, population):
self.name = name
self.location = location
self.population = population
# This is an instance method which takes self as the first argument to refer to the instance
def print_population(self, some_nice_sentence_prefix):
print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")
# This is a static (class) method which is marked with the @classmethod attribute
# All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
@classmethod
def change_country(cls, new_country):
cls.country = new_country
Some tests just to make things more clear:
# Populate objects
city1 = City("New York", "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")
#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!
#2.A) Use the static method in the object
city2.change_country("Canada")
#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada
import functools
class Example:
def wrapper(func):
@functools.wraps(func)
def wrap(self, *args, **kwargs):
print("inside wrap")
return func(self, *args, **kwargs)
return wrap
@wrapper
def method(self):
print("METHOD")
wrapper = staticmethod(wrapper)
e = Example()
e.method()
The reason you need to use self.
is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self
is the convention, and people will generally frown at you when you use something else.) self
is not special to the code, it's just another object.
Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self.
.
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
In this code:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
... the self
variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A
class and call its methods, it will be passed automatically, as in ...
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
The __init__
method is roughly what represents a constructor in Python. When you call A()
Python creates an object for you, and passes it as the first parameter to the __init__
method. Any additional parameters (e.g., A(24, 'Hello')
) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.
If you want a functionality like the compress folder of any common graphical file manager you can use the following code, it uses the zipfile module. Using this code you will have the zip file with the path as its root folder.
import os
import zipfile
def zipdir(path, ziph):
# Iterate all the directories and files
for root, dirs, files in os.walk(path):
# Create a prefix variable with the folder structure inside the path folder.
# So if a file is at the path directory will be at the root directory of the zip file
# so the prefix will be empty. If the file belongs to a containing folder of path folder
# then the prefix will be that folder.
if root.replace(path,'') == '':
prefix = ''
else:
# Keep the folder structure after the path folder, append a '/' at the end
# and remome the first character, if it is a '/' in order to have a path like
# folder1/folder2/file.txt
prefix = root.replace(path, '') + '/'
if (prefix[0] == '/'):
prefix = prefix[1:]
for filename in files:
actual_file_path = root + '/' + filename
zipped_file_path = prefix + filename
zipf.write( actual_file_path, zipped_file_path)
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('/tmp/justtest/', zipf)
zipf.close()
I recently came up with the following convention for naming my tests, their classes and containing projects in order to maximize their descriptivenes:
Lets say I am testing the Settings
class in a project in the MyApp.Serialization
namespace.
First I will create a test project with the MyApp.Serialization.Tests
namespace.
Within this project and of course the namespace I will create a class called IfSettings
(saved as IfSettings.cs).
Lets say I am testing the SaveStrings()
method. -> I will name the test CanSaveStrings()
.
When I run this test it will show the following heading:
MyApp.Serialization.Tests.IfSettings.CanSaveStrings
I think this tells me very well, what it is testing.
Of course it is usefull that in English the noun "Tests" is the same as the verb "tests".
There is no limit to your creativity in naming the tests, so that we get full sentence headings for them.
Usually the Test names will have to start with a verb.
Examples include:
DetectsInvalidUserInput
)ThrowsOnNotFound
)WillCloseTheDatabaseAfterTheTransaction
)etc.
Another option is to use "that" instead of "if".
The latter saves me keystrokes though and describes more exactly what I am doing, since I don't know, that the tested behavior is present, but am testing if it is.
[Edit]
After using above naming convention for a little longer now, I have found, that the If prefix can be confusing, when working with interfaces. It just so happens, that the testing class IfSerializer.cs looks very similar to the interface ISerializer.cs in the "Open Files Tab". This can get very annoying when switching back and forth between the tests, the class being tested and its interface. As a result I would now choose That over If as a prefix.
Additionally I now use - only for methods in my test classes as it is not considered best practice anywhere else - the "_" to separate words in my test method names as in:
[Test] public void detects_invalid_User_Input()
I find this to be easier to read.
[End Edit]
I hope this spawns some more ideas, since I consider naming tests of great importance as it can save you a lot of time that would otherwise have been spent trying to understand what the tests are doing (e.g. after resuming a project after an extended hiatus).
I needed something exactly as this (in a little more complex environment and the solution with a lot of 'mouseenters' and 'mouseleaves' wasnt working properly) so i created a little jquery plugin that adds the method ismouseover. It has worked pretty well so far.
//jQuery ismouseover method
(function($){
$.mlp = {x:0,y:0}; // Mouse Last Position
function documentHandler(){
var $current = this === document ? $(this) : $(this).contents();
$current.mousemove(function(e){jQuery.mlp = {x:e.pageX,y:e.pageY}});
$current.find("iframe").load(documentHandler);
}
$(documentHandler);
$.fn.ismouseover = function(overThis) {
var result = false;
this.eq(0).each(function() {
var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this);
var offset = $current.offset();
result = offset.left<=$.mlp.x && offset.left + $current.outerWidth() > $.mlp.x &&
offset.top<=$.mlp.y && offset.top + $current.outerHeight() > $.mlp.y;
});
return result;
};
})(jQuery);
Then in any place of the document yo call it like this and it returns true or false:
$("#player").ismouseover()
I tested it on IE7+, Chrome 1+ and Firefox 4 and is working properly.
echo array_search("car",array_keys($a));
A few steps you have to follow:
If example
is not final
then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final
then you could null
out all the elements:
Arrays.fill( example, null );
ArrayList
or similar collectionvar url = window.location.origin + window.location.pathname;
The Spring documentation says they're logged at DEBUG level:
All SQL issued by this class is logged at the DEBUG level under the category corresponding to the fully qualified class name of the template instance (typically JdbcTemplate, but it may be different if you are using a custom subclass of the JdbcTemplate class).
In XML terms, you need to configure the logger something like:
<category name="org.springframework.jdbc.core.JdbcTemplate">
<priority value="debug" />
</category>
This subject was however discussed here a month ago and it seems not as easy to get to work as in Hibernate and/or it didn't return the expected information: Spring JDBC is not logging SQL with log4j This topic under each suggests to use P6Spy which can also be integrated in Spring according this article.
No, @Controller
is not the same as @Service
, although they both are specializations of @Component
, making them both candidates for discovery by classpath scanning. The @Service
annotation is used in your service layer, and @Controller
is for Spring MVC controllers in your presentation layer. A @Controller
typically would have a URL mapping and be triggered by a web request.
I had originally created my Dockerfile in PowerShell and though I didn't see an extension on the file it showed as a PS File Type...once I created the file from Notepad++ being sure to select the "All types (.)" File Type with no extension on the File Name (Dockerfile). That allowed my image build command to complete successfully....Just make sure your Dockerfile has a Type of "File"...
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
conio.h
is a C
header file used in old MS-DOS compilers to create text user interfaces. Compilers that targeted non-DOS operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions.
The #include <curses.h>
will give you almost all the functionalities that was provided in conio.h
nucurses need to be installed at the first place
In deb based Distros use
sudo apt-get install libncurses5-dev libncursesw5-dev
And in rpm based distros use
sudo yum install ncurses-devel ncurses
For getch()
class of functions, you can try this
thanks for existing answers, but added signal.getsignal()
import signal
# store default handler of signal.SIGINT
default_handler = signal.getsignal(signal.SIGINT)
catch_count = 0
def handler(signum, frame):
global default_handler, catch_count
catch_count += 1
print ('wait:', catch_count)
if catch_count > 3:
# recover handler for signal.SIGINT
signal.signal(signal.SIGINT, default_handler)
print('expecting KeyboardInterrupt')
signal.signal(signal.SIGINT, handler)
print('Press Ctrl+c here')
while True:
pass
For CakePHP 4.*
echo $this->Html->link(
'Dashboard',
['controller' => 'Dashboards', 'action' => 'index', '_full' => true]
);
Run the following commands to completely uninstall Jenkins from MacOS Sierra. You don't need to change anything, just run these commands.
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins '/Library/Application Support/Jenkins' /Library/Documentation/Jenkins
sudo rm -rf /Users/Shared/Jenkins
sudo rm -rf /var/log/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
pkgutil --pkgs
grep 'org\.jenkins-ci\.'
xargs -n 1 sudo pkgutil --forget
Salam
Shah
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
There are multiple ways to achieve this:
--simulator
flag--udid
flagFirstly you need to list all the available devices. To list all the devices run
xcrun simctl list device
This will give output as follows:
These are the available devices for iOS 13.0 onwards:
== Devices ==
-- iOS 13.6 --
iPhone 8 (5C7EF61D-6080-4065-9C6C-B213634408F2) (Shutdown)
iPhone 8 Plus (5A694E28-EF4D-4CDD-85DD-640764CAA25B) (Shutdown)
iPhone 11 (D6820D3A-875F-4CE0-B907-DAA060F60440) (Shutdown)
iPhone 11 Pro (B452E7A1-F21C-430E-98F0-B02F0C1065E1) (Shutdown)
iPhone 11 Pro Max (94973B5E-D986-44B1-8A80-116D1C54665B) (Shutdown)
iPhone SE (2nd generation) (90953319-BF9A-4C6E-8AB1-594394AD26CE) (Booted)
iPad Pro (9.7-inch) (9247BC07-00DB-4673-A353-46184F0B244E) (Shutdown)
iPad (7th generation) (3D5B855D-9093-453B-81EB-B45B7DBF0ADF) (Shutdown)
iPad Pro (11-inch) (2nd generation) (B3AA4C36-BFB9-4ED8-BF5A-E37CA38394F8) (Shutdown)
iPad Pro (12.9-inch) (4th generation) (DBC7B524-9C75-4C61-A568-B94DA0A9BCC4) (Shutdown)
iPad Air (3rd generation) (03E3FE18-AB46-481E-80A0-D37383ADCC2C) (Shutdown)
-- tvOS 13.4 --
Apple TV (41579EEC-0E68-4D36-9F98-5822CD1A4104) (Shutdown)
Apple TV 4K (B168EF40-F2A4-4A91-B4B0-1F541201479B) (Shutdown)
Apple TV 4K (at 1080p) (D55F9086-A56E-4893-ACAD-579FB63C561E) (Shutdown)
-- watchOS 6.2 --
Apple Watch Series 4 - 40mm (D4BA8A57-F9C1-4F55-B3E0-6042BA7C4ED4) (Shutdown)
Apple Watch Series 4 - 44mm (65D5593D-29B9-42CD-9417-FFDBAE9AED87) (Shutdown)
Apple Watch Series 5 - 40mm (1B73F8CC-9ECB-4018-A212-EED508A68AE3) (Shutdown)
Apple Watch Series 5 - 44mm (5922489B-5CF9-42CD-ACB0-B11FAF88562F) (Shutdown)
Then from the output you can select the name or the uuid then proceed as you wish.
--simulator
run:npx react-native run-ios --simulator="iPhone SE"
--udid
flag run:npx react-native run-ios --udid 90953319-BF9A-4C6E-8AB1-594394AD26CE
I hope this answer helped you.
In case of shared hosting when you do not have command line access simply navigate to laravel/bootstrap/cache folder and delete (or rename) config.php and you are all done!
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
WHEN valueN THEN resultN
[
ELSE elseResult
]
END
http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.
Shameless self-promotion: there's a jQuery plugin for that.
HTML:
<form action="#" id="myform">
<div><input type="checkbox" id="checkall"> <label for="checkall"> Check all</label></div>
<fieldset id="slaves">
<div><label><input type="checkbox"> Checkbox</label></div>
<div><label><input type="checkbox"> Checkbox</label></div>
<div><label><input type="checkbox"> Checkbox</label></div>
<div><label><input type="checkbox"> Checkbox</label></div>
<div><label><input type="checkbox"> Checkbox</label></div>
</fieldset>
</form>?
JS:
$('#checkall').checkAll('#slaves input:checkbox', {
reportTo: function () {
var prefix = this.prop('checked') ? 'un' : '';
this.next().text(prefix + 'check all');
}
});?
...and you're done.
I really like to sort the keys in one liner code:
print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);
Try this:
public static void main(String[] args)
{
Pattern p = Pattern.compile("^\\d+$");
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
String temp;
Matcher numberMatcher;
System.out.print("Enter number 1: ");
try
{
num1 = kb.nextInt();
}
catch (java.util.InputMismatchException e)
{
System.out.println("Invalid Input");
//
return;
}
while(num2<num1)
{
System.out.print("Enter number 2: ");
temp = kb.next();
numberMatcher = p.matcher(temp);
if (numberMatcher.matches())
{
num2 = Integer.parseInt(temp);
}
else
{
System.out.println("Invalid Number");
}
}
}
You could try to parse the string into an int
as well, but usually people try to avoid throwing exceptions.
What I have done is that I have defined a regular expression that defines a number, \d
means a numeric digit. The +
sign means that there has to be one or more numeric digits. The extra \
in front of the \d
is because in java, the \
is a special character, so it has to be escaped.
Add FormsModule
in Imports Array.
i.e
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Or this can be done without using [(ngModel)]
by using
<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
instead of
<input [(ngModel)]="hero.name" placeholder="Name">
It can also be caused by this bug, if you're having Eclipse 4.5/4.6, an Eclipse Xtext plugin version older than v2.9.0, and a particular workspace configuration.
The workaround would be to create a new workspace and import the existing projects.
Following Glens idea, here it goes another possibility. It would allow you to scroll inside the div, but would prevent the body to scroll with it, when the div scroll ends. However, it seems to accumulate too many preventDefault if you scroll too much, and then it creates a lag if you want to scroll up. Does anybody have a suggestion to fix that?
$(".scrollInsideThisDiv").bind("mouseover",function(){
var bodyTop = document.body.scrollTop;
$('body').on({
'mousewheel': function(e) {
if (document.body.scrollTop == bodyTop) return;
e.preventDefault();
e.stopPropagation();
}
});
});
$(".scrollInsideThisDiv").bind("mouseleave",function(){
$('body').unbind("mousewheel");
});
Go to properties of your project ( with Alt+Enter or righ-click )
check on Apache Tomcat v7.0 under Targeted Runtime and it works.
Generally...
Hibernate is used for handling database operations. There is a rich set of database utility functionality, which reduces your number of lines of code. Especially you have to read @Annotation of hibernate. It is an ORM framework and persistence layer.
Spring provides a rich set of the Injection based working mechanism. Currently, Spring is well-known. You have to also read about Spring AOP. There is a bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.
Struts2 provides action based programming. There are a rich set of Struts tags. Struts prove action based programming so you have to maintain all the relevant control of your view.
In Addition, Tapestry is a different framework for Java. In which you have to handle only .tml
(template file). You have to create two main files for any class. One is JAVA class and another one is its template. Both names are same. Tapestry automatically calls related classes.
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can do this:
select *
from user_source
where upper(text) like upper('%SOMETEXT%');
Alternatively, SQL Developer has a built-in report to do this under:
View > Reports > Data Dictionary Reports > PLSQL > Search Source Code
The 11G docs for USER_SOURCE are here
UserSelect =null
AlertDialog.Builder builder = new Builder(ImonaAndroidApp.LoginScreen);
builder.setMessage("you message");
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserSelect = true ;
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserSelect = false ;
}
});
// in UI thread
builder.show();
// wait until the user select
while(UserSelect ==null);
Have you tried C# port for Mozilla Universal Charset Detector
Example from http://code.google.com/p/ude/
public static void Main(String[] args)
{
string filename = args[0];
using (FileStream fs = File.OpenRead(filename)) {
Ude.CharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
if (cdet.Charset != null) {
Console.WriteLine("Charset: {0}, confidence: {1}",
cdet.Charset, cdet.Confidence);
} else {
Console.WriteLine("Detection failed.");
}
}
}
A summary (and very minor improvement) on the most common answers that I found for this as at 2020.
Call with :w!!
or :W!!
.
After it expands, press enter
.
!!
after the w/W, it will not expand and might report: E492: Not an editor command: W!!
NOTE Use which tee
output to replace /usr/bin/tee
if it differs in your case.
Put these in your ~/.vimrc
file:
" Silent version of the super user edit, sudo tee trick.
cnoremap W!! execute 'silent! write !sudo /usr/bin/tee "%" >/dev/null' <bar> edit!
" Talkative version of the super user edit, sudo tee trick.
cmap w!! w !sudo /usr/bin/tee >/dev/null "%"
First, the linked answer below was about the only other that seemed to mitigate most known problems and differ in any significant way from the others. Worth reading: https://stackoverflow.com/a/12870763/2927555
My answer above was pulled together from multiple suggestions on the conventional sudo tee theme and thus very slightly improves on the most common answers I found. My version above:
Works with whitespace in file names
Mitigates path modification attacks by specifying the full path to tee.
Gives you two mappings, W!! for silent execution, and w!! for not silent, i.e Talkative :-)
The difference in using the non-silent version is that you get to choose between [O]k and [L]oad. If you don't care, use the silent version.
Information for the above was drawn from a bunch of other answers and comments on this, but notably:
Dr Beco's answer: https://stackoverflow.com/a/48237738/2927555
idbrii's comment to this: https://stackoverflow.com/a/25010815/2927555
Han Seoul-Oh's comment to this: How does the vim "write with sudo" trick work?
Bruno Bronosky comment to this: https://serverfault.com/a/22576/195239
This answer also explains why the apparently most simple approach is not such a good idea: https://serverfault.com/a/26334/195239
Yes, in my perspective there is no reason why you should write your own. Most of the Open Source BPM/Workflow frameworks are extremely flexible, you just need to learn the basics. If you choose jBPM you will get much more than a simple workflow engine, so it depends what are you trying to build.
Cheers
I do something similar in one of my blog postings. A simple C++ example is shown.
The aim was to use the open source cvBlobsLib library for the detection of spot samples printed to microarray slides, but the images have to be converted from colour -> grayscale -> black + white as you mentioned, in order to achieve this.
You need to convert Array to string :
//arrayOfValues = [1, 2, 3];
$.get('/controller/MyAction', { arrayOfValues: "1, 2, 3" }, function (data) {...
this works even in form of int, long or string
public ActionResult MyAction(int[] arrayOfValues )
Use Simple HTML
<frameset cols="25%,*">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
document.getElementById('id').style = 'left: 55%; z-index: 999; overflow: hidden; width: 0px; height: 0px; opacity: 0; display: none;';
works for me
A shorter answer from here, adapted to this question:
var arr = $('.requiredText');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Just for completeness.
We have already 2019 and z-index
is still not supported in SVG.
You can see on the site SVG2 support in Mozilla that the state for z-index
– Not implemented.
You can also see on the site Bug 360148 "Support the 'z-index' property on SVG elements" (Reported: 12 years ago).
But you have 3 possibilities in SVG to set it:
element.appendChild(aChild);
parentNode.insertBefore(newNode, referenceNode);
targetElement.insertAdjacentElement(positionStr, newElement);
(No support in IE for SVG)With all this 3 functions.
var state = 0,_x000D_
index = 100;_x000D_
_x000D_
document.onclick = function(e)_x000D_
{_x000D_
if(e.target.getAttribute('class') == 'clickable')_x000D_
{_x000D_
var parent = e.target.parentNode;_x000D_
_x000D_
if(state == 0)_x000D_
parent.appendChild(e.target);_x000D_
else if(state == 1)_x000D_
parent.insertBefore(e.target, null); //null - adds it on the end_x000D_
else if(state == 2)_x000D_
parent.insertAdjacentElement('beforeend', e.target);_x000D_
else_x000D_
e.target.style.zIndex = index++;_x000D_
}_x000D_
};_x000D_
_x000D_
if(!document.querySelector('svg').insertAdjacentElement)_x000D_
{_x000D_
var label = document.querySelectorAll('label')[2];_x000D_
label.setAttribute('disabled','disabled');_x000D_
label.style.color = '#aaa';_x000D_
label.style.background = '#eee';_x000D_
label.style.cursor = 'not-allowed';_x000D_
label.title = 'This function is not supported in SVG for your browser.';_x000D_
}
_x000D_
label{background:#cef;padding:5px;cursor:pointer}_x000D_
.clickable{cursor:pointer}
_x000D_
With: _x000D_
<label><input type="radio" name="check" onclick="state=0" checked/>appendChild()</label>_x000D_
<label><input type="radio" name="check" onclick="state=1"/>insertBefore()</label><br><br>_x000D_
<label><input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()</label>_x000D_
<label><input type="radio" name="check" onclick="state=3"/>Try it with z-index</label>_x000D_
<br>_x000D_
<svg width="150" height="150" viewBox="0 0 150 150">_x000D_
<g stroke="none">_x000D_
<rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>_x000D_
<rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>_x000D_
<rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>_x000D_
</g>_x000D_
</svg>
_x000D_
I like Tony approach. It works, but I decided to implement in different way. Here my comments:
1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.
By the way, ui-if was removed. Now you have ng-if build-in.
2) I prefer to write a service like this:
angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {
var factory = {};
factory.getGridHeight = function(gridOptions) {
var length = gridOptions.data.length;
var rowHeight = 30; // your row height
var headerHeight = 40; // your header height
var filterHeight = 40; // your filter height
return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {
return value.replace(unit, '');
}
return factory;
});
And then in the controller write the following:
angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {
...
// Execute this when you have $scope.gridData loaded...
$scope.gridHeight = uiGridService.getGridHeight($scope.gridData);
And at the HTML file:
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>
When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.
3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.
$scope.gridData = {
enableSorting: true,
multiSelect: false,
enableRowSelection: true,
showFooter: false,
enableFiltering: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
enableGridMenu: true,
noUnselect: true,
expandableRowTemplate: 'subGrid.html',
expandableRowHeight: 380, // 10 rows * 30px + 40px (header) + 40px (filters)
onRegisterApi: function(gridApi) {
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));
if (row.isExpanded)
{
height += changedRowHeight;
}
else
{
height -= changedRowHeight;
}
$scope.jdeNewUserConflictsGridHeight = height + 'px';
});
},
columnDefs : [
{ field: 'GridField1', name: 'GridField1', enableFiltering: true }
]
}
The chosen answer looks like does not apply to modern browsers, at least on Firefox 52. What I observed is that the requests of loading resources like css, javascript are issued before HTML parser reaches the element, for example
<html>
<head>
<!-- prints the date before parsing and blocks HTMP parsering -->
<script>
console.log("start: " + (new Date()).toISOString());
for(var i=0; i<1000000000; i++) {};
</script>
<script src="jquery.js" type="text/javascript"></script>
<script src="abc.js" type="text/javascript"></script>
<link rel="stylesheets" type="text/css" href="abc.css"></link>
<style>h2{font-wight:bold;}</style>
<script>
$(document).ready(function(){
$("#img").attr("src", "kkk.png");
});
</script>
</head>
<body>
<img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
<script src="kkk.js" type="text/javascript"></script>
</body>
</html>
What I found that the start time of requests to load css and javascript resources were not being blocked. Looks like Firefox has a HTML scan, and identify key resources(img resource is not included) before starting to parse the HTML.
Notes.Select(x => x.Author).Distinct();
This will return a sequence (IEnumerable<string>
) of Author
values -- one per unique value.
Also another difference is taking into consideration a situation where there is a skew join and you have to coalesce on top of it. A repartition will solve the skew join in most cases, then you can do the coalesce.
Another situation is, suppose you have saved a medium/large volume of data in a data frame and you have to produce to Kafka in batches. A repartition helps to collectasList before producing to Kafka in certain cases. But, when the volume is really high, the repartition will likely cause serious performance impact. In that case, producing to Kafka directly from dataframe would help.
side notes: Coalesce does not avoid data movement as in full data movement between workers. It does reduce the number of shuffles happening though. I think that's what the book means.
It would be easier to recreate the data frame. This would also interpret the columns types from scratch.
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'Beta'
select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1
If you want the query to work as where col like '%Beta%'
you can use contains
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'et'
select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1
For Linux users, check the value of GIT_HOME
in your .env
file in the home directory.
cd home/<username>/
.env
file and check the value of GIT_HOME
and select the git path appropriatelyPS: If you are not able to find the .env
file, click on View
on the formatting tool bar, select Show hidden files
. You should be able to find the .env
file now.
Android Studio cannot find the svn
command because it's not on PATH
, and it doesn't know where svn
is installed.
One way to fix is to edit the PATH
environment variable: add the directory that contains svn.exe
. You will need to restart Android Studio to make it re-read the PATH
variable.
Another way is to set the absolute path of svn.exe
in the Use command client box in the settings screen that you included in your post.
UPDATE
According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe
to PATH
, and Android Studio will correctly pick it up.
If you're doing a very simple GUI and you're already using Visual Studio then it may make sense to just go with MFC. You can just use the Visual Studio MFC wizard to create a dialog based application, drop two controls on it and away you go.
MFC is dated and has its fair share of annoyances, but it will certainly do the job for you if you're just talking about a button and a text box.
I don't have any experience with Qt, so I can't compare the two.
As other answers have mentioned, the following calls will compute the hash:
MD5Context md5;
MD5Init(&md5);
MD5Update(&md5, data, datalen);
MD5Final(digest, &md5);
The purpose of splitting it up into that many functions is to let you stream large datasets.
For example, if you're hashing a 10GB file and it doesn't fit into ram, here's how you would go about doing it. You would read the file in smaller chunks and call MD5Update
on them.
MD5Context md5;
MD5Init(&md5);
fread(/* Read a block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
fread(/* Read the next block into data. */)
MD5Update(&md5, data, datalen);
...
// Now finish to get the final hash value.
MD5Final(digest, &md5);
If you want to carry on using CSS3 selectors but need to support older browsers I would suggest using a polyfill such as Selectivizr.js
You could give each position on each slider a different binary value from 1 to 1000000000 and then work with the sum.
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
The parametric equation for a circle is
x = cx + r * cos(a)
y = cy + r * sin(a)
Where r is the radius, cx,cy the origin, and a the angle.
That's pretty easy to adapt into any language with basic trig functions. Note that most languages will use radians for the angle in trig functions, so rather than cycling through 0..360 degrees, you're cycling through 0..2PI radians.
Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):
apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql
or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:
apt-get install php5-pgsql
Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:
dpkg -s libpq-dev
To get specific view from recycler view list OR show error at edittext of recycler view.
private void popupErrorMessageAtPosition(int itemPosition) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
View view = viewHolder.itemView;
EditText etDesc = (EditText) view.findViewById(R.id.et_description);
etDesc.setError("Error message here !");
}
I'd this issue on Linux Mint (Maya) 13, And I fixed it by Installing postgresql and postgresql-server :
apt-get install postgresql-9.1
sudo apt-get install postgresql-server-dev-9.1
When you call setBackgoundColor it overwrites/removes any existing background resource, including any borders, corners, padding, etc. What you want to do is change the color of the existing background resource...
View v;
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
Experiment with PorterDuff.Mode.* for different effects.
According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.
What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:
var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
v := m[k]
// k is the key and v is the value; do your computation here
}
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
#include<stdio.h>
main()
{
int a[5] = {55,11,66,77,72};
int max,min,i;
int smax,smin;
max = min = a[0];
smax = smin = a[0];
for(i=0;i<=4;i++)
{
if(a[i]>max)
{
smax = max;
max = a[i];
}
if(max>a[i]&&smax<a[i])
{
smax = a[i];
}
}
printf("the first max element z %d\n",max);
printf("the second max element z %d\n",smax);
}
You want font-weight, not text-decoration (along with suitable additional markup, such as <em>
or <span>
, so you can apply different styling to different parts of the heading)
SSLSocketFactory does not expose its X509TrustManager, which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call sslSocketFactory(SSLSocketFactory, X509TrustManager), which avoids such reflection.
Source: OkHttp documentation
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslContext.getSocketFactory(),
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
});
I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables
to 1.
var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";
request.get( {
url : url,
headers : {
"Authorization" : auth
}
}, function(error, response, body) {
console.log('body : ', body);
} );
Minimal POSIX C exit status example
To understand $?
, you must first understand the concept of process exit status which is defined by POSIX. In Linux:
when a process calls the exit
system call, the kernel stores the value passed to the system call (an int
) even after the process dies.
The exit system call is called by the exit()
ANSI C function, and indirectly when you do return
from main
.
the process that called the exiting child process (Bash), often with fork
+ exec
, can retrieve the exit status of the child with the wait
system call
Consider the Bash code:
$ false
$ echo $?
1
The C "equivalent" is:
false.c
#include <stdlib.h> /* exit */
int main(void) {
exit(1);
}
bash.c
#include <unistd.h> /* execl */
#include <stdlib.h> /* fork */
#include <sys/wait.h> /* wait, WEXITSTATUS */
#include <stdio.h> /* printf */
int main(void) {
if (fork() == 0) {
/* Call false. */
execl("./false", "./false", (char *)NULL);
}
int status;
/* Wait for a child to finish. */
wait(&status);
/* Status encodes multiple fields,
* we need WEXITSTATUS to get the exit status:
* http://stackoverflow.com/questions/3659616/returning-exit-code-from-child
**/
printf("$? = %d\n", WEXITSTATUS(status));
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o bash bash.c
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o false false.c
./bash
Output:
$? = 1
In Bash, when you hit enter, a fork + exec + wait happens like above, and bash then sets $?
to the exit status of the forked process.
Note: for built-in commands like echo
, a process need not be spawned, and Bash just sets $?
to 0 to simulate an external process.
Standards and documentation
POSIX 7 2.5.2 "Special Parameters" http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02 :
? Expands to the decimal exit status of the most recent pipeline (see Pipelines).
man bash
"Special Parameters":
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. [...]
? Expands to the exit status of the most recently executed foreground pipeline.
ANSI C and POSIX then recommend that:
0
means the program was successful
other values: the program failed somehow.
The exact value could indicate the type of failure.
ANSI C does not define the meaning of any vaues, and POSIX specifies values larger than 125: What is the meaning of "POSIX"?
Bash uses exit status for if
In Bash, we often use the exit status $?
implicitly to control if
statements as in:
if true; then
:
fi
where true
is a program that just returns 0.
The above is equivalent to:
true
result=$?
if [ $result = 0 ]; then
:
fi
And in:
if [ 1 = 1 ]; then
:
fi
[
is just an program with a weird name (and Bash built-in that behaves like it), and 1 = 1 ]
its arguments, see also: Difference between single and double square brackets in Bash
So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
and got the following back:
{'name': 'NWIS Time Series Instantaneous Values'}
It appears to have found the timeSeries element without needing to use numerical indices.
What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.
I had the same question except that I wanted to combine the criteria into an OR condition. The format given by Wouter Overmeire combines the criteria into an AND condition such that both must be satisfied:
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
A B C D
d 1 3 9 6
But I found that, if you wrap each condition in (... == True)
and join the criteria with a pipe, the criteria are combined in an OR condition, satisfied whenever either of them is true:
df[((df.A==1) == True) | ((df.D==6) == True)]
Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:
unicodedata.category('?')
'Lo'
unicodedata.category('A')
'Lu'
unicodedata.category('1')
'Nd'
unicodedata.category('a')
'Ll'
The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:
def only_letters(s):
for c in s:
cat = unicodedata.category(c)
if cat not in ('Ll','Lu','Lo'):
return False
return True
And then:
only_letters('Bzdrezylo')
True
only_letters('He7lo')
False
As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.
As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product
. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d)
.
Given fp
: the file name to the image, d
: the tile size, opt.path
: the path to the directory containing the images, and opt.out
: is the directory where tiles will be outputted:
def tile(filename, dir_in, dir_out, d):
name, ext = os.path.splitext(filename)
img = Image.open(os.path.join(dir_in, fp))
w, h = img.size
grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
for i, j in grid:
box = (j, i, j+d, i+d)
out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
img.crop(box).save(out)
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
In my situation, in order to include color.sh
from the same directory in init.sh
, I had to do something as follows.
. ./color.sh
Not sure why the ./
and not color.sh
directly. The content of color.sh
is as follows.
RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`
Making use of File color.sh
does not error but, the color do not display. I have tested this in Ubuntu 18.04
and the Bash
version is:
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Use an image loading library like Picasso or Glide. Using these libraries will prevent crashes in the future.
Hello this working you try! in your case is .navbar-fixed-top{}
.navbar-fixed-bottom{
width:1200px;
left:20%;
}
@basarat's answer was great. Here is simplified but a little bit extended example you can use:
export type TMyEnumType = 'value1'|'value2';
export class MyEnumType {
static VALUE1: TMyEnumType = 'value1';
static VALUE2: TMyEnumType = 'value2';
}
console.log(MyEnumType.VALUE1); // 'value1'
const variable = MyEnumType.VALUE2; // it has the string value 'value2'
switch (variable) {
case MyEnumType.VALUE1:
// code...
case MyEnumType.VALUE2:
// code...
}
Cython
It seems that the goto answer for this is Cython. I'm really surprised no one else mentioned this yet? Here's the home page: https://cython.org
In a nutshell, this transforms your python into C and compiles it, thus making it as well protected as any "normal" compiled distributable C program.
There are limitations though. I haven't explored them in depth myself, because as I started to read about them, I dropped the idea for my own purposes. But it might still work for yours. Essentially, you can't use Python to the fullest, with the dynamic awesomeness it offers. One major issue that jumped out at me, was that keyword parameters are not usable :( You must write function calls using positional parameters only. I didn't confirm this, but I doubt you can use conditional imports, or evals. I'm not sure how polymorphism is handled...
Anyway, if you aren't trying to obfuscate a huge code base after the fact, or ideally if you have the use of Cython in mind to begin with, this is a very notable option.
You can also use the same syntax for an array. For example, searching within a Pandas series:
ser = pd.Series(['some', 'strings', 'to', 'query'])
if item in ser.values:
# do stuff
You can either use the backslash character to escape a single character or symbol
'Java_22 \& Oracle_14'
or braces to escape a string of characters or symbols
'{Java_22 & Oracle_14}'
You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:
public class MyTable
{
[Key, Column(Order = 0)]
public string SomeId { get; set; }
[Key, Column(Order = 1)]
public int OtherId { get; set; }
}
You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.
EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.
It is:
<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>
In VB.net you set an anonymous type using
new with {.class = "tab" }
and, as other point out, your third parameter should be an object (could be an anonymous type, also).
Cant have two public classes in same file
public class StaticDemo{
Change to
class StaticDemo{
To get the x/y after scroll ended as the original questions was requesting, the easiest way is probably this:
<ScrollView
horizontal={true}
pagingEnabled={true}
onMomentumScrollEnd={(event) => {
// scroll animation ended
console.log(e.nativeEvent.contentOffset.x);
console.log(e.nativeEvent.contentOffset.y);
}}>
...content
</ScrollView>
When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:
select *
from little
left join big
on left( big.key, len(little.key) ) = little.key
I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.
Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.
The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).
Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages
$ python2.6 -c "import sys; [sys.stdout.write('rob\n') for r in range(10)]"
Works fine. Use "[ ]" to inline your for loop.
Just adding this. In your package.json, if your "main": "index.js" is correctly set. Just use node .
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
...
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
...
}
}
You could also just use the bytes where they are, casting them to the type you need.
unsigned char *bytePtr = (unsigned char *)[data bytes];
while True
is true -- ie always. This is an infinite loop
Note the important distinction here between True
which is a keyword in the language denoting a constant value of a particular type, and 'true' which is a mathematical concept.
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
I'll start with the answer then context NOTE this fix was logged above, I'm just re-stating it for anyone googling.
use commands:
phpize
./configure
make
make install (as root)
enable extension=mysqli.so in your php.ini file
This is logged as an answer from here (please upvote it if it helped you too): https://stackoverflow.com/a/39277373/3912517
Context: I'm trying to add LimeSurvey to the standard WordPress Docker. The single point holding me back is "PHP PDO driver library" which is "None found"
php -i | grep PDO
PHP Warning: PHP Startup: Unable to load dynamic library 'pdo_odbc' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning: Module 'mysqli' already loaded in Unknown on line 0
PDO
PDO support => enabled
PDO drivers => sqlite
PDO Driver for SQLite 3.x => enabled
Ubuntu 16 (Ubuntu 7.3.0)
apt-get install php7.0-mysql
Result:
Package 'php7.0-mysql' has no installation candidate
Get instructions saying all I have to do is run this:
add-apt-repository -y ppa:ondrej/apache2
But then I get this:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 223: ordinal not in range(128)
So I try and force some type of UTF: LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/apache2 and I get this: no valid OpenPGP data found.
Follow some other instructions to run this: apt-get update and I get this: Err:14 http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic/main amd64 Packages 404 Not Found Err:15 http://ppa.launchpad.net/ondrej/php/ubuntu cosmic/main amd64 Packages 404 Not Found and - I think because of that - I then get:
The repository 'http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic Release' does not have a Release file.
By this stage, I'm still getting this on apt-get update:
Package 'php7.0-mysql' has no installation candidate.
I start trying to add in php libraries, got Unicode issues, tried to get around that and.... you get the idea... whack-a-mole. I gave up and looked to see if I could compile it and I found the answer I started with.
You might be wondering why I wrote so much? So that anyone googling can find this solution (including me!).
Please not that rand()
does not generate a cryptographically secure value according to the docs:
http://php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
Instead it is better to use random_int()
, available on PHP 7 (See: http://php.net/manual/en/function.random-int.php).
So to extend @Marcus's answer, you should use:
function generateSecureRandomNumber($digits): int {
return random_int(pow(10, $digits - 1), pow(10, $digits) - 1);
}
function generateSecureRandomNumberWithPadding($digits): string {
$randomNumber = random_int(0, pow(10, $digits) - 1);
return str_pad($randomNumber, $digits, '0', STR_PAD_LEFT);
}
Note that using rand()
is fine if you don't need a secure random number.
string.Format("{0:hh:mm:ss tt}", DateTime.Now)
This should give you the string value of the time. tt should append the am/pm.
You can also look at the related topic:
Thanks to "Darin Dimitrov", This is the extension methods.
public static partial class Ext
{
public static Uri GetUriWithparameters(this Uri uri,Dictionary<string,string> queryParams = null,int port = -1)
{
var builder = new UriBuilder(uri);
builder.Port = port;
if(null != queryParams && 0 < queryParams.Count)
{
var query = HttpUtility.ParseQueryString(builder.Query);
foreach(var item in queryParams)
{
query[item.Key] = item.Value;
}
builder.Query = query.ToString();
}
return builder.Uri;
}
public static string GetUriWithparameters(string uri,Dictionary<string,string> queryParams = null,int port = -1)
{
var builder = new UriBuilder(uri);
builder.Port = port;
if(null != queryParams && 0 < queryParams.Count)
{
var query = HttpUtility.ParseQueryString(builder.Query);
foreach(var item in queryParams)
{
query[item.Key] = item.Value;
}
builder.Query = query.ToString();
}
return builder.Uri.ToString();
}
}
Sounds like you need to use position:fixed and then set the the top position to a percentage and the and either the left or the right position to a fixed unit.
The SPE IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.
I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.
Using test
if test ! -z "$(docker images -q <name:tag>)"; then
echo "Exist"
fi
or in one line
test ! -z "$(docker images -q <name:tag>)" && echo exist
Please check below javascript in IE. Don't know if other modern browser will work or not.
<html>
<head>
<script type="text/javascript">
function OpenOutlookDoc(){
try {
var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="a subject test";
mailItem.To = "[email protected]";
mailItem.HTMLBody = "<b>bold</b>";
mailItem.display (0);
}
catch(e){
alert(e);
// act on any error that you get
}
}
</script>
</head>
<body>
<a href="javascript:OpenOutlookDoc()">Click</a>
</body>
</html>
This can be accomplished without javascript, with this metatag:
<meta http-equiv="refresh" content="5" >
where content ="5" are the seconds that the page will wait until refreshed.
But you said only if there was no activity, what kind for activity would that be?
DateAndTime Reformat:
SELECT *, to_char( last_update, 'DD-MON-YYYY') as re_format from actor;
DEMO:
Comparator
provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable
allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator
.
Otherwise you can use Comparable
.
position: relative act as a parent element position: absolute act a child of relative position. you can see the below example
.postion-element{
position:relative;
width:200px;
height:200px;
background-color:green;
}
.absolute-element{
position:absolute;
top:10px;
left:10px;
background-color:blue;
}
Keep in mind that the Fusion API is unmanaged. The current reference for it is here: Development Guide > Unmanaged API Reference > Fusion
However, there is a managed method to add an assembly to GAC: System.EnterpriseServices.Internal.Publish.GacInstall And, if you need to register any Types: System.EnterpriseServices.Internal.Publish.RegisterAssembly
The reference for the publish class is here: .NET Framework Class Library > System.EnterpriseServices Namespaces > System.EnterpriseServices.Internal
However, these methods were designed for installing components that are required by a web service application such as ASP.NET or WCF. As a result they don't register the assemblies with Fusion; thus, they can be uninstalled by other applications, or using gacutil and cause your assembly to stop working. So, if you use them outside of a web server where an administrator is managing the GAC then be sure to add a reference to your application in SOFTWARE\Wow6432Node\Microsoft\Fusion\References (for 64-bit OS) or SOFTWARE\Microsoft\Fusion\References (for 32-bit OS) so that nobody can remove your support assemblies unless they uninstall your application.
select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/
Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.
The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:
SQL> create table t23 (id number not null primary key)
2 /
Table created.
SQL> select constraint_name, constraint_type
2 from user_constraints
3 where table_name = 'T23'
4 /
CONSTRAINT_NAME C
------------------------------ -
SYS_C00935190 C
SYS_C00935191 P
SQL>
'C'
for check, 'P'
for primary.
Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191
.
To be honest most people don't bother naming NOT NULL constraints.
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
This would return bool:
Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)
I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:
Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.
They both return the same thing, as noted in the documentation you linked; an HttpSession object.
You can also look at a concrete implementation (e.g. Tomcat) and see what it's actually doing: Request.java class. In this case, basically they both call:
Session session = doGetSession(true);
You can not use input for it, you need to use textarea instead.
Use textarea with the wrap="soft"
code and optional the rest of the attributes like this:
<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>
Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40"
like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea>
To hide the scroll the style for it. if you only use overflow:scroll;
or overflow:hidden;
or overflow:auto;
it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden;
in the style area:
To make the textarea not resizable you can use the style with resize:none;
like this:
<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>
That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.
NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input>
that is made to not work with rows at all.
This query fetches a list of all columns in a database without having to specify a table name. It returns a list of only column names:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'db_name'
However, when I ran this query in phpmyadmin, it displayed a series of errors. Nonetheless, it worked. So use it with caution.
Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.
import cv2
img = cv2.imread('1.jpg', 1)
path = '/tmp'
cv2.imwrite(str(path) + 'waka.jpg',img)
cv2.waitKey(0)
I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.
Example:
import os
final_path = os.path.join(path_1,path_2,path_3......)
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
that code works fine on both Windows and Ubuntu :)
By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”
It is generally best to explicitly specify essential attributes such as type=text
instead of defaulting them. The reason is that there is no simple reliable way to refer to the input
elements with defaulted type
attribute.
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
This work for me :
sudo service redis-server start
font-weight: 900;
I had a different issue with Font Awesome 5. Default font-weight should be 900 for FontAwesome icons but I overwrote it to 400 for span and i tags. It just worked, when I corrected it.
Here is the issue reference in their Github page, https://github.com/FortAwesome/Font-Awesome/issues/11946
I hope it will help someone.
I found useful npm package https://www.npmjs.com/package/element-resize-detector
An optimized cross-browser resize listener for elements.
Can use it with React component or functional component(Specially useful for react hooks)
This MySQL library worked for me:
sudo apt-get install php5-mysqlnd-ms
Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str)
call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
In simple term it can be stated as:
Spring boot = Spring MVC + Auto Configuration(Don't need to write spring.xml file for configurations) + Server(You can have embedded Tomcat, Netty, Jetty server).
And Spring Boot is an Opinionated framework, so its build taking in consideration for fast development, less time need for configuration and have a very good community support.
For your case, just use:
var votevalue = +$(this).data('votevalue');
There are some ways to convert string to number in javascript.
The best way:
var str = "1";
var num = +str; //simple enough and work with both int and float
You also can:
var str = "1";
var num = Number(str); //without new. work with both int and float
or
var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DON'T:
var str = "1";
var num = new Number(str); //num will be an object. typeof num == 'object'
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
pull = fetch + merge.
You need to commit what you have done before merging.
So pull after commit.
Because QuerySets implement the Python __or__
operator (|
), or union, it just works. As you'd expect, the |
binary operator returns a QuerySet
so order_by()
, .distinct()
, and other queryset filters can be tacked on to the end.
combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')
Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.
Is the final order defined by a list of indices ?
>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]
>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']
edit: meh. AJ was faster... How can I reorder a list in python?
Construction
With factories, Angular will invoke the function to get the result. It is the result that is cached and injected.
//factory
var obj = fn();
return obj;
With services, Angular will invoke the constructor function by calling new. The constructed function is cached and injected.
//service
var obj = new fn();
return obj;
Implementation
Factories typically return an object literal because the return value is what's injected into controllers, run blocks, directives, etc
app.factory('fn', function(){
var foo = 0;
var bar = 0;
function setFoo(val) {
foo = val;
}
function setBar (val){
bar = val;
}
return {
setFoo: setFoo,
serBar: setBar
}
});
Service functions typically do not return anything. Instead, they perform initialization and expose functions. Functions can also reference 'this' since it was constructed using 'new'.
app.service('fn', function () {
var foo = 0;
var bar = 0;
this.setFoo = function (val) {
foo = val;
}
this.setBar = function (val){
bar = val;
}
});
Conclusion
When it comes to using factories or services they are both very similar. They are injected into a controllers, directives, run block, etc, and used in client code in pretty much the same way. They are also both singletons - meaning the same instance is shared between all places where the service/factory is injected.
So which should you prefer? Either one - they are so similar that the differences are trivial. If you do choose one over the other, just be aware how they are constructed, so that you can implement them properly.
why don't you try this?
password="your password"
username="username"
Ip="<IP>"
sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>
I think you need to add some context to your question. However, basic information about these things can be found here:
window.opener
https://developer.mozilla.org/en-US/docs/Web/API/Window.opener
I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.
window.parent
https://developer.mozilla.org/en-US/docs/Web/API/Window.parent
I've used this mostly when working with IFrames that need to communicate with the window object that contains them.
window.top
https://developer.mozilla.org/en-US/docs/Web/API/Window.top
This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.
If you add some more detail to your question, I can supply other more relevant examples.
UPDATE:
There are a few ways you can handle your situation.
You have the following structure:
When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.
So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:
childwindow.appMainWindow = window.opener
After making the assignment above, close dialog 1.
Then from the code running inside dialog2, you should be able to use
window.appMainWindow
to reference the main window, window object.
Hope this helps.
Perfect Answer by Jinu and Daniel
Adding to this I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)
compile ('org.apache.httpcomponents:httpmime:4.3'){
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'
else if your compileSdkVersion is 23 then use
android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
A general answer involves using a Manager
object. Adapted from the docs:
from multiprocessing import Process, Manager
def f(d):
d[1] += '1'
d['2'] += 2
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
d[1] = '1'
d['2'] = 2
p1 = Process(target=f, args=(d,))
p2 = Process(target=f, args=(d,))
p1.start()
p2.start()
p1.join()
p2.join()
print d
Output:
$ python mul.py
{1: '111', '2': 6}
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
This one work for me.I found it myself by combining other answers
private Boolean exit = false;
@override
public void onBackPressed(){
if (exit) {
finish(); // finish activity
}
else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
}, 1000);
}
Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.
However, it is not quite that simple. hjust
and vjust
as described there are how it works in geom_text
and theme_text
(sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust
of 0.5 and a vjust
of 0.5 center the box on the reference point. Reducing hjust
moves the box right by an amount of the box width times 0.5-hjust
. Thus when hjust=0
, the left edge of the box is at the reference point. Increasing hjust
moves the box left by an amount of the box width times hjust-0.5
. When hjust=1
, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2
, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5
box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].
But, sometimes this doesn't work. For example
DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))
The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider
p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))
The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.
'Use Chrome, invite troubles' - Anonymous. (Just a symbolic reference)
Well, Chrome is notoriously famous for a lot of default security-enabled utilities, and that's where your problem originates from.
This can, however, be undone by 'setting the default email client' (as the default email client is unset), or by setting up the default handler under 'chrome://settings/handlers' (by default, it's set to 'Ignore').
as of RC5 you need to import the HttpModule like so :
import { HttpModule } from '@angular/http';
then include the HttpModule in the imports array as mentioned above by Günter.
I got this error when I was trying to be smart and extract the cloning URL from the repo's URL myself. I did it wrong. I was doing:
git@https://github.company.com/Project/Core-iOS
where I had to do:
[email protected]:Project/Core-iOS.git
I had 3 mistakes:
https://
.com
I need :
instead of /
.git
I found that using the tornado
package to be the fastest and simplest way to achieve this:
from tornado import ioloop, httpclient, gen
def main(urls):
"""
Asynchronously download the HTML contents of a list of URLs.
:param urls: A list of URLs to download.
:return: List of response objects, one for each URL.
"""
@gen.coroutine
def fetch_and_handle():
httpclient.AsyncHTTPClient.configure(None, defaults=dict(user_agent='MyUserAgent'))
http_client = httpclient.AsyncHTTPClient()
waiter = gen.WaitIterator(*[http_client.fetch(url, raise_error=False, method='HEAD')
for url in urls])
results = []
# Wait for the jobs to complete
while not waiter.done():
try:
response = yield waiter.next()
except httpclient.HTTPError as e:
print(f'Non-200 HTTP response returned: {e}')
continue
except Exception as e:
print(f'An unexpected error occurred querying: {e}')
continue
else:
print(f'URL \'{response.request.url}\' has status code <{response.code}>')
results.append(response)
return results
loop = ioloop.IOLoop.current()
web_pages = loop.run_sync(fetch_and_handle)
return web_pages
my_urls = ['url1.com', 'url2.com', 'url100000.com']
responses = main(my_urls)
print(responses[0])
The article previously mentioned is good. http://forums.oracle.com/forums/thread.jspa?threadID=191750 (as far as it goes)
If this is not something that runs frequently (don't do it on your home page), you can turn off connection pooling.
There is one other "gotcha" that is not mentioned in the article. If the first thing you try to do with the connection is call a stored procedure, ODP will HANG!!!! You will not get back an error condition to manage, just a full bore HANG! The only way to fix it is to turn OFF connection pooling. Once we did that, all issues went away.
Pooling is good in some situations, but at the cost of increased complexity around the first statement of every connection.
If the error handling approach is so good, why don't they make it an option for ODP to handle it for us????
There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
Have a look at the documentation. You made the following mistakes.
Firstly, ps.executeQuery()
doesn't have any parameters. Instead you passed the SQL query into it.
Secondly, regarding the prepared statement, you have to use the ?
symbol if want to pass any parameters. And later bind it using
setXXX(index, value)
Here xxx stands for the data type.
It's really easy to create folders. Actually it's just creating keys.
You can see my below code i was creating a folder with utc_time as name.
Do remember ends the key with '/' like below, this indicates it's a key:
Key='folder1/' + utc_time + '/'
client = boto3.client('s3')
utc_timestamp = time.time()
def lambda_handler(event, context):
UTC_FORMAT = '%Y%m%d'
utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
utc_time = utc_time.strftime(UTC_FORMAT)
print 'start to create folder for => ' + utc_time
putResponse = client.put_object(Bucket='mybucketName',
Key='folder1/' + utc_time + '/')
print putResponse
If you would want to put multiple values into the string you could make use of format
nums = [1,2,3]
plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))
Would result in the string hanning123.pdf
. This can be done with any array.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to understand some ramifications that exist when using EIMIs. And because of these ramifications, you should try to avoid EIMIs as much as possible. Fortunately, generic interfaces help you avoid EIMIs quite a bit. But there may still be times when you will need to use them (such as implementing two interface methods with the same name and signature). Here are the big problems with EIMIs:
- There is no documentation explaining how a type specifically implements an EIMI method, and there is no Microsoft Visual Studio IntelliSense support.
- Value type instances are boxed when cast to an interface.
- An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.
Specifically:
...snip...
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
...snip...
http://www.cplusplus.com/reference/clibrary/cstring/strcat.html
There's an example here as well.
I used this to create a toggle effect between two functions.
var x = false;
$(element).on('click', function(){
if (!x){
//function
x = true;
}
else {
//function
x = false;
}
});
strcat
concats str2
onto str1
You'll get runtime errors because str1
is not being properly allocated for concatenation
tl;dr; Clicking OK is the workaround, everything will work fine after that.
I also received this error message.
Configuring Web http://localhost:xxxxx/ for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.
Environment: Windows 10, IIS8, VS 2012 Web.
After finding this page, along with several seemingly invasive solutions, I read through the hotfix option at https://support.microsoft.com/en-us/help/3002339/unexpected-dialog-box-appears-when-you-open-projects-in-visual-studio as suggested here.
Please avoid doing anything too drastic, and note the section of that page marked "Workaround" as shown below:
Workaround
To work around this issue, click OK when the dialog box appears after you either create a new project or open an existing Web Site Project or Windows Azure project. After you do this, the project works as expected.
In other words, click OK on the dialog box one time, and the message is gone forever. The project will work just fine.
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
Tested on Ubuntu:
sudo apt install git-extras
git-show-tree
This produces an effect similar to the 2 most upvoted answers here.
Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html
Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow
shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch
or manually via git branch --set-upstream-to=upstream_branch
).
git branch
you are on too!"Using NPM ( make sure that you have node version 8+ )
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
npm i @angular/cli --save
Using Yarn
yarn remove @angular/cli
yarn global add @angular/cli
yarn add @angular/cli
ng update @angular/cli
ng update @angular/core
ng update @angular/material
ng update rxjs
Normally that would mean that you have to update your code everywhere RxJS imports and operators are used, but thankfully there’s a package that takes care of most of the heavy lifting:
npm i -g rxjs-tslint
//or using yarn
yarn global add rxjs-tslint
Then you can run rxjs-5-to-6-migrate
rxjs-5-to-6-migrate -p src/tsconfig.app.json
finally remove rxjs-compat
npm uninstall rxjs-compat
// or using Yarn
yarn remove rxjs-compat
Refer to this link https://alligator.io/angular/angular-6/
So you have to manually update your package.json
file.
Then run
npm update
npm install --save rxjs-compat
npm i -g rxjs-tslint
rxjs-5-to-6-migrate -p src/tsconfig.app.json
I found hitting ctrl+break while the macro wasn't running fixed the problem.
This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:
SELECT SM.definition
FROM sys.sql_modules SM
INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
WHERE SO.type = 'v'
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?
import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class MyClass {
public static void main(String[] args) throws InterruptedException{
while(true){
//Thread.sleep(100);
System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x +
", " +
MouseInfo.getPointerInfo().getLocation().y + ")");
}
}
}
In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.
The solution that work for me is the following
_private.convertParams=function(params){
var params= [];
Object.keys(values).forEach(function(key) {
params.push({"id":key,"option":"Igual","value":params[key].id})
});
return params;
}
Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.
The solution:
h2:after {
content: "\00a0";
}
Firstly, in your react project go to your package.json and adjust this line line of code to match your destination domain address + folder:
"homepage": "https://yourwebsite.com/your_folder_name/",
Secondly, go to terminal in your react project and type:
npm run build
Now, take all files from that newly created build folder and upload them into your_folder_name, with filezilla in subfolder like this:
public_html/your_folder_name
Check in the browser!
I added @Component
annotation from import org.springframework.stereotype.Component
and the problem was solved.
I think Extensions
is a better way instead of #pragma mark
.
The Code before using Extensions
:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
...
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
...
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
...
}
}
The code after using Extensions
:
class ViewController: UIViewController {
...
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
...
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
...
}
}
There isn't any need to call any API. You can get the country code from your device where it is located. Just use this function:
fun getUserCountry(context: Context): String? {
try {
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val simCountry = tm.simCountryIso
if (simCountry != null && simCountry.length == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US)
}
else if (tm.phoneType != TelephonyManager.PHONE_TYPE_CDMA) { // Device is not 3G (would be unreliable)
val networkCountry = tm.networkCountryIso
if (networkCountry != null && networkCountry.length == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US)
}
}
}
catch (e: Exception) {
}
return null
}
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.
The old wisdom
"mark it private unless you have a good reason not to"
made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".
Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.
Have you ever:
These are the three biggest rationalizations I've heard for marking methods private by default:
I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.
Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.
This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.
This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.
I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".
This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)
SOLVED! I register to stockoverflow just to share to you the only solution (at least in ASP.NET/IE/FF/Chrome) that works! The idea is to replace innerHTML value of a div by its current innerHTML value.
Here is the HTML snippet:
<div class="content-2" id="divGranite">
<h2>Granite Purchase</h2>
<IFRAME runat="server" id="frameGranite" src="Jobs-granite.aspx" width="820px" height="300px" frameborder="0" seamless ></IFRAME>
</div>
And my Javascript code:
function refreshGranite() {
var iframe = document.getElementById('divGranite')
iframe.innerHTML = iframe.innerHTML;
}
Hope this helps.
Maybe the uuid module?
Checkout the .SaveAs()
method in Excel object.
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
Or following:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
A Type agnostic solution:
for _, key := range reflect.ValueOf(yourMap).MapKeys() {
value := s.MapIndex(key).Interface()
fmt.Println("Key:", key, "Value:", value)
}
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
Java's URI Class can help you out of this:
public static String getCurrentUrl(HttpServletRequest request){
URL url = new URL(request.getRequestURL().toString());
String host = url.getHost();
String userInfo = url.getUserInfo();
String scheme = url.getProtocol();
String port = url.getPort();
String path = request.getAttribute("javax.servlet.forward.request_uri");
String query = request.getAttribute("javax.servlet.forward.query_string");
URI uri = new URI(scheme,userInfo,host,port,path,query,null)
return uri.toString();
}
DisplayMember and ValueMember are mostly only useful if you're databinding to objects that have those properties defined. You would then need to add an instance of that object.
e.g.:
public class MyObject
{
public string clan { get; set; }
public int sifOsoba { get; set; }
public MyObject(string aClan, int aSif0soba)
{
this.clan = aClan;
this.sif0soba = aSif0soba;
}
public override string ToString() { return this.clan; }
}
....
list.Items.Add(new MyObject("hello", 5));
If you're binding it manually then you can use the example provided by goggles
Did you try this?
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:background="#303030"
>
<RelativeLayout
android:id="@+id/widget42"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
>
<ImageButton
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="map"
android:src="@drawable/outbox_pressed"
android:background="@null"
android:layout_toRightOf="@+id/location"
/>
<ImageButton
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="location"
android:src="@drawable/inbox_pressed"
android:background="@null"
/>
</RelativeLayout>
<ImageButton
android:id="@+id/home"
android:src="@drawable/button_back"
android:background="@null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px"
android:orientation="horizontal"
android:background="#252525"
>
<EditText
android:id="@+id/searchfield"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="@drawable/customshape"
/>
<ImageButton
android:id="@+id/search_button"
android:src="@drawable/search_press"
android:background="@null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
</LinearLayout>
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:apiKey="apikey" />
</TableLayout>
Instead of using a separate CTE to get the total, you can use a window function without the "partition by" clause.
If you are using:
count(*)
to get the count for a group, you can use:
sum(count(*)) over ()
to get the total count.
For example:
select Grade, 100. * count(*) / sum(count(*)) over ()
from table
group by Grade;
It tends to be faster in my experience, but I think it might internally use a temp table in some cases (I've seen "Worktable" when running with "set statistics io on").
EDIT: I'm not sure if my example query is what you are looking for, I was just illustrating how the windowing functions work.
private void startFloatingWidgetService() {
startService(new Intent(MainActivity.this,FloatingWidgetService.class)
.setAction(FloatingWidgetService.ACTION_PLAY));
}
instead of :
private void startFloatingWidgetService() {
startService(new Intent(FloatingWidgetService.ACTION_PLAY));
}
Because when you try 2nd one then you get an error saying : java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.floatingwidgetchathead_demo.SampleService.ACTION_START }
Then your Service be like this :
static final String ACTION_START = "com.floatingwidgetchathead_demo.SampleService.ACTION_START";
static final String ACTION_PLAY = "com.floatingwidgetchathead_demo.SampleService.ACTION_PLAY";
static final String ACTION_PAUSE = "com.floatingwidgetchathead_demo.SampleService.ACTION_PAUSE";
static final String ACTION_DESTROY = "com.yourcompany.yourapp.SampleService.ACTION_DESTROY";
@SuppressLint("LogConditional")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
//System.out.println("ACTION: "+action);
switch (action){
case ACTION_START:
Log.d(TAG, "onStartCommand: "+action);
break;
case ACTION_PLAY:
Log.d(TAG, "onStartCommand: "+action);
addRemoveView();
addFloatingWidgetView();
break;
case ACTION_PAUSE:
Log.d(TAG, "onStartCommand: "+action);
break;
case ACTION_DESTROY:
Log.d(TAG, "onStartCommand: "+action);
break;
}
return START_STICKY;
}
Accepted answer is good.
Just putting it again here, so its easy to understand & try in future
git diff c1...c2 > mypatch_1.patch
git diff c1..c2 > mypatch_2.patch
git diff c1^..c2 > mypatch_3.patch
I got the same diff for all the above commands.
Above helps in
1. seeing difference of between commit c1 & another commit c2
2. also making a patch file that shows diff and can be used to apply changes to another branch
If it not showing difference correctly
then c1 & c2 may be taken wrong
so adjust them to a before commit like c1 to c0, or to one after like c2 to c3
Use gitk
to see the commits SHAs, 1st 8 characters are enough to use them as c0, c1, c2 or c3. You can also see the commits ids from Gitlab > Repository > Commits, etc.
Hope that helps.
Create a PHP file outside your document root. If your document root is
/var/www/html/
create the a file named minify.php one level above it
/var/www/minify.php
Copy paste the following PHP code into it
<?php function minify_output($buffer){ $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s'); $replace = array('>','<','\\1'); if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) { $buffer = preg_replace($search, $replace, $buffer); } return $buffer; } ob_start("minify_output");?>
Save the minify.php file and open the php.ini file. If it is a dedicated server/VPS search for the following option, on shared hosting with custom php.ini add it.
auto_prepend_file = /var/www/minify.php
Reference: http://websistent.com/how-to-use-php-to-minify-html-output/
after chasing a ghost for two days, trying to figure out why the width of a text was incorrect, i realized it was because of white spaces in the text string that would stop the width calculation.
so, another tip is to check if the whitespaces are causing problems. use
non-breaking space and see if that fixes it up.
the other functions people suggested work well too, but it was the whitespaces causing trouble.
They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
I fixed mine by closing eclipse and deleting the whole .metadata folder inside my workspace folder.
One of the most straightforward ways to do it is
git for-each-ref --format='%(refname:short)' refs/heads/
This works perfectly for scripts as well.
System.Threading.Thread.Sleep(
(int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);
Or with using
statements:
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
I prefer this to 1000 * numSeconds
(or simply 3000
) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep
before. It better documents your intent.
Make your Foreign key attributes nullable. That will work.
We had a problem like this with ASP.Net. Our IIS was returning an Internal Server Error when trying to execute a jQuery $.post
to get some html content due to PageHandlerFactory was restricted to respond only GET,HEAD,POST,DEBUG
Verbs. So you can change that restriction adding the verb "OPTIONS" to the list or selecting "All Verbs"
You can modify that in your IIS Manager, selecting your website, then selecting Handler Mappings, double click in your PageHandlerFactory for *.apx files as you need (We use Integrated application pool with framework 4.0). Click on Request Restrictions, then go to Verbs Tabn and apply your modification.
Now our $.post
request is working as expected :)
i'd try tinyproxy. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for Lua, especially after seeing how well it worked for mysqlproxy
Here's a solution that doesn't use negative margins or calc
. Run the snippet below to see the final result.
Explanation
We give the header and the footer a fixed height of 30px
and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header
and above-footer
to pad the div above and below with 30px
.
All of the content is wrapped in a position: relative
div so that the header and footer are at the top/bottom of the content and not the window.
We use the classes fit-to-parent
and min-fit-to-parent
to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.
Inside the header and footer, we use the display: table
and display: table-cell
styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%
, which causes a scroll bar to appear when it isn't really needed.)
.fit-parent {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
min-height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
.footer {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
height: 30px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
<body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
My webpage_x000D_
</div>_x000D_
</div>_x000D_
<div class='fit-parent above-footer below-header'>_x000D_
<div class='fit-parent' id='main-inner'>_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
</div>_x000D_
</div>_x000D_
<div class='footer valign-outer' style='background-color: white'>_x000D_
<div class='valign-inner padding-lr-small'>_x000D_
© 2005 Old Web Design_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
pd.to_numeric
with errors='coerce'
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use
pd.__version__ # '0.24.1' pd.to_numeric(s, errors='coerce').astype('Int32') 0 1 1 2 2 3 3 4 4 NaN dtype: Int32
There are other options to choose from as well, read the docs for more.
DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
here I'm providing solution to setup terraform enviroment variable in windows to beginners.
Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\
and Save it.
multi-disciplinary
will not be hyphenated, as explained by kennytm. But multi-\-disciplinary
has the same hyphenation opportunities that multidisciplinary
has.
I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):
The command
\-
inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
Please add this css code
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like
angular.module('MyModule', [...])
.service('MyService', ['$http', function($http){
return {
users: [...],
getUserFriends: function(userId){
return $http({
method: 'GET',
url: '/api/user/friends/' + userId
});
}
....
}
}])
if you need more
Find More About Why We Need AngularJs Services and Factories
Add the lines in the gradle.properties file
android.useAndroidX=true
android.enableJetifier=true
Using the Vimeo url(https://player.vimeo.com/video/30572181), here is my example
<!DOCTYPE html>_x000D_
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>_x000D_
<title>Vimeo</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<img src="" id="thumbImg">_x000D_
</div>_x000D_
<script>_x000D_
$(document).ready(function () {_x000D_
var vimeoVideoUrl = 'https://player.vimeo.com/video/30572181';_x000D_
var match = /vimeo.*\/(\d+)/i.exec(vimeoVideoUrl);_x000D_
if (match) {_x000D_
var vimeoVideoID = match[1];_x000D_
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=?', { format: "json" }, function (data) {_x000D_
featuredImg = data[0].thumbnail_large;_x000D_
$('#thumbImg').attr("src", featuredImg);_x000D_
});_x000D_
}_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
Apart from "readability", no. They're functionally equivalent.
("Readability" is in quotes because I hate == false
and find !
much more readable. But others don't.)
You need to download their source from the github. Find the main file and then include it in your main file.
An example of this can be found here > How to manually install a node.js module?
Usually you need to find the source and go through the package.json file. There you can find which is the main file. So that you can include that in your application.
To include example.js in your app. Copy it in your application folder and append this on the top of your main js file.
var moduleName = require("path/to/example.js")
You could do it in one document if you had a conditional based on params sent over. Eg:
if (isset($_GET['secret_param'])) {
<run script>
} else {
<display button>
}
I think the best way though is to have two files.
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
int[] arr = {111, 111, 110, 101, 101, 102, 115, 112};
/* for ascending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
/*for descending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
private int[] getSortedArray(int[] k){
int localIndex =0;
for(int l=1;l<k.length;l++){
if(l>1){
localIndex = l;
while(true){
k = swapelement(k,l);
if(l-- == 1)
break;
}
l = localIndex;
}else
k = swapelement(k,l);
}
return k;
}
private int[] swapelement(int[] ar,int in){
int temp =0;
if(ar[in]<ar[in-1]){
temp = ar[in];
ar[in]=ar[in-1];
ar[in-1] = temp;
}
return ar;
}
private int[] getDescOrder(int[] byt){
int s =-1;
for(int i = byt.length-1;i>=0;--i){
int k = i-1;
while(k >= 0){
if(byt[i]>byt[k]){
s = byt[k];
byt[k] = byt[i];
byt[i] = s;
}
k--;
}
}
return byt;
}
output:-
ascending order:-
101, 101, 102, 110, 111, 111, 112, 115
descending order:-
115, 112, 111, 111, 110, 102, 101, 101
I searched for help on this topic as I came across the same issue.
Although the following may not be the Answer to the question asked originally in 2012 it may be a solution for those who come across this thread.
A way to solve this is to check where your project is within the solution. It turns out for my instance (I was trying to install a NuGet package but it wouldn't and the listed error came up) that my project file was not included within the solution directory although showing in the solution explorer. I deleted the project from the directory out of scope and re-added the project but this time within the correct location.