It seems that now you can just mark the method parameter with @RequestParam
and it will do the job for you.
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam Map<String, String> body ) {
//work with Map
}
Check encoding and language:
$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR
Get all languages:
$ locale -a
Change to pt_PT.utf8:
$ export LC_ALL=pt_PT.utf8
$ export LANG="$LC_ALL"
First add the import line:
from pyspark.sql.functions import min, max
df.agg(min("age")).show()
+--------+
|min(age)|
+--------+
| 29|
+--------+
df.agg(max("age")).show()
+--------+
|max(age)|
+--------+
| 77|
+--------+
Now we can easily do this using the aspect-ratio
ref property
.container {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
Also like below where we can have a variable number of columns
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys
as True
and indent
with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:
with open('data.txt', 'w') as outfile:
json.dump(jsonData, outfile, sort_keys = True, indent = 4,
ensure_ascii = False)
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
I have been asked sorting of a definite range of numbers in better than nlogn time in one of interview. (Not using Counting sort)
Implementing Comparable interface over an object allows implicit sorting algos to use overridden compareTo method to order sort elements and that would be linear time.
A PDB file contains information for the debugger to work with. There's less information in a Release build than in a Debug build anyway. But if you want it to not be generated at all, go to your project's Build properties, select the Release configuration, click on "Advanced..." and under "Debug Info" pick "None".
In Debian NGINX environment i did the following.
Goto /etc/mysql/mysql.conf.d
edit mysqld.cnf
if you find log-error = /var/log/mysql/error.log
add the following 2 lines bellow it.
general_log_file = /var/log/mysql/mysql.log
general_log = 1
To see the logs goto /var/log/mysql
and tail -f mysql.log
Remember to comment these lines out once you are done with debugging if you are in production environment delete mysql.log
as this log file will grow quickly and can be huge.
One easy way to select random items is to shuffle then slice.
import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
The problem seems to be that block
elements only scale up to 100% of their containing element, no matter how big their content is—it just overflows. However, making them inline-block
elements apparently resizes their width to their actual content.
HTML:
<div id="container">
<div class="wide">
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
</div>
<div class="wide">
bar
</div>
</div>
CSS:
.wide { min-width: 100%; display: inline-block; background-color: yellow; }
#container { display: inline-block; }
(The container
element addresses your follow-up question to make the second div
as big as the previous one, and not just the screen width.)
I also set up a JS fiddle showing my demo code.
If you run into any troubles (esp. cross-browser issues) with inline-block
, looking at Block-level elements within display: inline-block might help.
I would one-up'd mightymada's answer if I had the reputation - I just implemented an asp.net HTML to PDF solution using Pechkin. results are wonderful.
There is a nuget package for Pechkin, but as the above poster mentions in his blog (http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - I hope she doesn't mind me reposting it), there's a memory leak that's been fixed in this branch:
https://github.com/tuespetre/Pechkin
The above blog has specific instructions for how to include this package (it's a 32 bit dll and requires .net4). here is my code. The incoming HTML is actually assembled via HTML Agility pack (I'm automating invoice generations):
public static byte[] PechkinPdf(string html)
{
//Transform the HTML into PDF
var pechkin = Factory.Create(new GlobalConfig());
var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), html);
//Return the PDF file
return pdf;
}
again, thank you mightymada - your answer is fantastic.
Keyword float
:
<h1 style="text-align:left;float:left;">Title</h1>
<h2 style="text-align:right;float:right;">Context</h2>
<hr style="clear:both;"/>
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
You can use Array#filter
function and additional array for storing sorted values;
var recordsSorted = []
ids.forEach(function(e) {
recordsSorted.push(records.filter(function(o) {
return o.empid === e;
}));
});
console.log(recordsSorted);
Result:
[ [ { empid: 1, fname: 'X', lname: 'Y' } ],
[ { empid: 4, fname: 'C', lname: 'Y' } ],
[ { empid: 5, fname: 'C', lname: 'Y' } ] ]
If you also want to bind closing of infowindow to some event, try something like this
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
windows.push(infowindow)
google.maps.event.addListener(map,'click', function(){
infowindow.close();
});
};
})(marker,content,infowindow));
For a basic hand symbol:
Try
cursor: pointer
If you want a hand symbol like drag some item and drop it, try:
cursor: grab
For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!) you can use SUB QUERY! The Syntax Would be as follows
SELECT t1.id
FROM example t1 INNER JOIN
(select id from (example2 t1
join example3 t2
on t1
.id
= t2
.id
)) as t2 ON t1.id = t2.id;
Hope you Get My Point!
Simple: e.g. if div id 'mydiv'
jQuery.fancybox.open({href: "#mydiv"});
This also makes JS code functional which is inside div.
AtomicReference is also a solution to pass the error to the main thread .Is same approach like the one of Dan Cruz .
AtomicReference<Throwable> errorReference = new AtomicReference<>();
Thread thread = new Thread() {
public void run() {
throw new RuntimeException("TEST EXCEPTION");
}
};
thread.setUncaughtExceptionHandler((th, ex) -> {
errorReference.set(ex);
});
thread.start();
thread.join();
Throwable newThreadError= errorReference.get();
if (newThreadError!= null) {
throw newThreadError;
}
The only change is that instead of creating a volatile variable you can use AtomicReference which did same thing behind the scenes.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<fork>true</fork>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
Actually you may not use SimpleDateFormat, you can use something like this;
@JsonSerialize(using=JsonDateSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date blkDate;
This way you can directly get the date with format as specified.
Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:
with open('data.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
Note: use json.loads
instead of json.load
. In Python 3, json.loads
takes a string parameter. json.load
takes a file-like object parameter. data_file.read()
returns a string object.
To be honest, I don't think it's a problem to load all json data into memory in most cases. I see this in JS, Java, Kotlin, cpp, rust almost every language I use. Consider memory issue like a joke to me :)
On the other hand, I don't think you can parse json without reading all of it.
For my use case, I needed to access just the system properties, but provide default values in case they are undefined.
This is how you do it:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="myBean" class="path.to.my.BeanClass">
<!-- can be overridden with -Dtest.target.host=http://whatever.com -->
<constructor-arg value="${test.target.host:http://localhost:18888}"/>
</bean>
The LocalLinks extension from the most popular answer didn't work for me (given, I was trying to use file:// to open a directory in windows explorer, not a file), so I looked into another workaround. I found that this "Open in IE" extension is a good workaround: https://chrome.google.com/webstore/detail/open-in-ie/iajffemldkkhodaedkcpnbpfabiglmdi
This isn't an ideal fix, as instead of clicking the link, users will have to right-click and choose Open in IE, but it at least makes the link functional.
One thing to note though, in IE10 (and IE9 after a certain update point) you will have to add the site to your Trusted Sites (Internet Options > Security > Trusted sites). If the site is not in trusted sites, the file:// link does not work in IE either.
[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .
System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.
Here is a code for IE >= 9 by using split(" ") on the className :
function toggleClass(element, className) {
var arrayClass = element.className.split(" ");
var index = arrayClass.indexOf(className);
if (index === -1) {
if (element.className !== "") {
element.className += ' '
}
element.className += className;
} else {
arrayClass.splice(index, 1);
element.className = "";
for (var i = 0; i < arrayClass.length; i++) {
element.className += arrayClass[i];
if (i < arrayClass.length - 1) {
element.className += " ";
}
}
}
}
See Creating a shared and static library with the gnu compiler [gcc]
gcc -c -o out.o out.c
-c
means to create an intermediary object file, rather than an executable.
ar rcs libout.a out.o
This creates the static library. r
means to insert with replacement, c
means to create a new archive, and s
means to write an index. As always, see the man page for more info.
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
cd C:\Users\%username%\AppData\Local rmdir /S /Q Temp
del C:\Windows\Prefetch*.* /Q
del C:\Windows\Temp*.* /Q
del C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Recent Items*.* /Q pause
The difference between them is, that a val
is executed when it is defined whereas a lazy val
is executed when it is accessed the first time.
scala> val x = { println("x"); 15 }
x
x: Int = 15
scala> lazy val y = { println("y"); 13 }
y: Int = <lazy>
scala> x
res2: Int = 15
scala> y
y
res3: Int = 13
scala> y
res4: Int = 13
In contrast to a method (defined with def
) a lazy val
is executed once and then never again. This can be useful when an operation takes long time to complete and when it is not sure if it is later used.
scala> class X { val x = { Thread.sleep(2000); 15 } }
defined class X
scala> class Y { lazy val y = { Thread.sleep(2000); 13 } }
defined class Y
scala> new X
res5: X = X@262505b7 // we have to wait two seconds to the result
scala> new Y
res6: Y = Y@1555bd22 // this appears immediately
Here, when the values x
and y
are never used, only x
unnecessarily wasting resources. If we suppose that y
has no side effects and that we do not know how often it is accessed (never, once, thousands of times) it is useless to declare it as def
since we don't want to execute it several times.
If you want to know how lazy vals
are implemented, see this question.
An easy way to combine them and ensure it's always correct is:
string.Format("{0}/{1}", Url1.Trim('/'), Url2);
Can change the text colour by overriding the getView method as follows:
new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, list()){
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//change the color to which ever you want
((CheckedTextView) view).setTextColor(Color.RED);
//change the size to which ever you want
((CheckedTextView) view).setTextSize(5);
//for using sp values use setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
return view;
}
}
Try this For check duplicates
>>> def checkDuplicate(List):
duplicate={}
for i in List:
## checking whether the item is already present in dictionary or not
## increasing count if present
## initializing count to 1 if not present
duplicate[i]=duplicate.get(i,0)+1
return [k for k,v in duplicate.items() if v>1]
>>> checkDuplicate([1,2,3,"s",1,2,3])
[1, 2, 3]
I see a bunch of answers that say putting everything about user 123 at resource "/user/123" is RESTful.
Roy Fielding, who coined the term, says REST APIs must be hypertext-driven. In particular, "A REST API must not define fixed resource names or hierarchies".
So if your "/user/123" path is hardcoded on the client, it's not really RESTful. A good use of HTTP, maybe, maybe not. But not RESTful. It has to come from hypertext.
In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
Now, suppose you are using a direct post variable into the MySQL query then, use it this way:
$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";
This is the best practice for using PHP variables into MySQL.
the best and easiest way is to use "MySQL for Excel" app that is a free app from oracle. this app added a plugin to excel to export and import data to mysql. you can download that from here
You put your image in resources folder and use follow code:
JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));
Note first that your question shows a bit of misunderstanding. origin/HEAD represents the default branch on the remote, i.e. the HEAD that's in that remote repository you're calling origin. When you switch branches in your repo, you're not affecting that. The same is true for remote branches; you might have master
and origin/master
in your repo, where origin/master
represents a local copy of the master
branch in the remote repository.
origin's HEAD will only change if you or someone else actually changes it in the remote repository, which should basically never happen - you want the default branch a public repo to stay constant, on the stable branch (probably master). origin/HEAD is a local ref representing a local copy of the HEAD in the remote repository. (Its full name is refs/remotes/origin/HEAD.)
I think the above answers what you actually wanted to know, but to go ahead and answer the question you explicitly asked... origin/HEAD is set automatically when you clone a repository, and that's about it. Bizarrely, that it's not set by commands like git remote update
- I believe the only way it will change is if you manually change it. (By change I mean point to a different branch; obviously the commit it points to changes if that branch changes, which might happen on fetch/pull/remote update.)
Edit: The problem discussed below was corrected in Git 1.8.4.3; see this update.
There is a tiny caveat, though. HEAD is a symbolic ref, pointing to a branch instead of directly to a commit, but the git remote transfer protocols only report commits for refs. So Git knows the SHA1 of the commit pointed to by HEAD and all other refs; it then has to deduce the value of HEAD by finding a branch that points to the same commit. This means that if two branches happen to point there, it's ambiguous. (I believe it picks master if possible, then falls back to first alphabetically.) You'll see this reported in the output of git remote show origin
:
$ git remote show origin
* remote origin
Fetch URL: ...
Push URL: ...
HEAD branch (remote HEAD is ambiguous, may be one of the following):
foo
master
Oddly, although the notion of HEAD printed this way will change if things change on the remote (e.g. if foo is removed), it doesn't actually update refs/remotes/origin/HEAD
. This can lead to really odd situations. Say that in the above example origin/HEAD actually pointed to foo, and origin's foo branch was then removed. We can then do this:
$ git remote show origin
...
HEAD branch: master
$ git symbolic-ref refs/remotes/origin/HEAD
refs/remotes/origin/foo
$ git remote update --prune origin
Fetching origin
x [deleted] (none) -> origin/foo
(refs/remotes/origin/HEAD has become dangling)
So even though remote show knows HEAD is master, it doesn't update anything. The stale foo branch is correctly pruned, and HEAD becomes dangling (pointing to a nonexistent branch), and it still doesn't update it to point to master. If you want to fix this, use git remote set-head origin -a
, which automatically determines origin's HEAD as above, and then actually sets origin/HEAD to point to the appropriate remote branch.
Making it open from rtl isn't good for user experience, to make it responsive to the user locale I just added the following line to my DrawerLayout parameters:
android:layoutDirection="locale"
Added it to my AppBarLayout to make the hamburger layout match the drawer opening direction too.
To convert XML File in to JSON include the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
and you can Download Jar from Maven Repository here. Then implement as:
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);
app:cardBackgroundColor="#488747"
use this in your card view and you can change a color of your card view
The most likely you already have a constraint with the name iduser
or idcategory
in your database. Just rename the constraints if so.
Constraints must be unique for the entire database, not just for the specific table you are creating/altering.
To find out where the constraints are currently in use you can use the following query:
SELECT `TABLE_SCHEMA`, `TABLE_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_NAME` IN ('iduser', 'idcategory');
Given there is only one (or with this solution potentially not even one) submit button, here is jQuery based solution that will work for multiple forms on the same page...
<script type="text/javascript">
$(document).ready(function () {
var makeAllFormSubmitOnEnter = function () {
$('form input, form select').live('keypress', function (e) {
if (e.which && e.which == 13) {
$(this).parents('form').submit();
return false;
} else {
return true;
}
});
};
makeAllFormSubmitOnEnter();
});
</script>
The simple answer is onPressed : null
gives a disabled button.
Error reporting will have not included notices on the previous server which is why you haven't seen the errors.
You should be checking whether the index s
actually exists in the $_GET
array before attempting to use it.
Something like this would be suffice:
if (isset($_GET['s'])) {
if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
else if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
else if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
echo "<body>";
}
It may be beneficial (if you plan on adding more cases) to use a switch
statement to make your code more readable.
switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
case 'jwshxnsyllabus':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
break;
case 'aquinas':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
break;
case 'POP2':
echo "<body onload=\"loadSyllabi('POP2')\">";
break;
default:
echo "<body>";
break;
}
EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s=
meant to output no <body>
tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>
.
You can use the following commands to delete.
Use the "match all docs" query in a delete by query command:
'<delete><query>*:*</query></delete>
You must also commit after running the delete so, to empty the index, run the following two commands:
curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'
Another strategy would be to add two bookmarks in your browser:
http://localhost:8983/solr/update?stream.body=<delete><query>*:*</query></delete>
http://localhost:8983/solr/update?stream.body=<commit/>
Source docs from SOLR:
https://wiki.apache.org/solr/FAQ#How_can_I_delete_all_documents_from_my_index.3F
You don't mention if this is a GUI program or not, but most GUI packages include a way to capture and handle keyboard input. For example, with tkinter
(in Py3), you can bind to a certain event and then handle it in a function. For example:
import tkinter as tk
def key_handler(event=None):
if event and event.keysym in ('s', 'p'):
'do something'
r = tk.Tk()
t = tk.Text()
t.pack()
r.bind('<Key>', key_handler)
r.mainloop()
With the above, when you type into the Text widget, the key_handler
routine gets called for each (or almost each) key you press.
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
Had similar problem and in the end I had to set both
obj.attr('data-myvar','myval')
and
obj.data('myvar','myval')
And after this
obj.data('myvar') == obj.attr('data-myvar')
Hope this helps.
By default Build location
is in Derived Data
.
Please note: a path to a product can be changed if you delete DerivedData during development process and rebuild it again.
Xcode -> Preferences... -> Locations
You can change the location of Build location
. It will have an effect on the whole workspace
File -> Project/Workspace Settings... -> Advanced
You can change the location of Target using:
Project editor -> select a target -> Build Settings -> Per-configuration Build Products Path
The default value is$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
It makes sense if you want to create an autonomic Build location
Xcode 10.2.1
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
In my case the Exception occurred because I had removed the "hibernate.enable_lazy_load_no_trans=true" in the "hibernate.properties" file...
I had made a copy and paste typo...
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
In case you need to define two or more excludeFilters criteria, you have to use the array.
For instances in this section of code I want to exclude all the classes in the org.xxx.yyy package and another specific class, MyClassToExclude
@ComponentScan(
excludeFilters = {
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.xxx.yyy.*"),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyClassToExclude.class) })
I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop()
all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.
It's easy & efficient to determine if an element is visible in the viewport, or in any scrollable container, by using an observer.
The need to attach a scroll
event and manually checking on the event callback is eliminated, which is more efficient:
// this is the target which is observed
var target = document.querySelector('div')
// configure the intersection observer instance
var intersectionObserverOptions = {
root: null, // default is the viewport
threshold: .5 // percentage of the taregt visible area which will trigger "onIntersection"
}
var observer = new IntersectionObserver(onIntersection, intersectionObserverOptions)
// called when target is fully visible
function onIntersection(entries, opts){
entries.forEach(entry => {
var visible = entry.intersectionRatio >= opts.thresholds[0]
console.clear();
console.log(entry.intersectionRatio.toFixed(2), visible)
target.classList.toggle('visible', visible)
})
}
// provide the observer with a target
observer.observe(target)
// To stop watching, do:
// observer.unobserve(entry.target)
_x000D_
span{ position:fixed; top:0; left:0; }
.box{ width:100px; height:100px; background:red; margin:1000px; transition:.5s; }
.box.visible{ background:green; }
_x000D_
<span>Scroll both Vertically & Horizontally...</span>
<div class='box'></div>
_x000D_
From Wikipedia
History
The DUAL table was created by Chuck Weiss of Oracle corporation to provide a table for joining in internal views:
I created the DUAL table as an underlying object in the Oracle Data Dictionary. It was never meant to be seen itself, but instead used inside a view that was expected to be queried. The idea was that you could do a JOIN to the DUAL table and create two rows in the result for every one row in your table. Then, by using GROUP BY, the resulting join could be summarized to show the amount of storage for the DATA extent and for the INDEX extent(s). The name, DUAL, seemed apt for the process of creating a pair of rows from just one. 1
It may not be obvious from the above, but the original DUAL table had two rows in it (hence its name). Nowadays it only has one row.
Optimization
DUAL was originally a table and the database engine would perform disk IO on the table when selecting from DUAL. This disk IO was usually logical IO (not involving physical disk access) as the disk blocks were usually already cached in memory. This resulted in a large amount of logical IO against the DUAL table.
Later versions of the Oracle database have been optimized and the database no longer performs physical or logical IO on the DUAL table even though the DUAL table still actually exists.
Depending on the AWK
implementation are you using ==
is ok or not.
Have you tried ~
?. For example, if you want $1 to be "hello":
awk '$1 ~ /^hello$/{ print $3; }' <infile>
^
means $1 start, and $
is $1 end.
For anyone looking for how to do it programmatically:
Drawable bckgrndDr = new ColorDrawable(Color.RED);
Drawable secProgressDr = new ColorDrawable(Color.GRAY);
Drawable progressDr = new ScaleDrawable(new ColorDrawable(Color.BLUE), Gravity.LEFT, 1, -1);
LayerDrawable resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, secProgressDr, progressDr });
//setting ids is important
resultDr.setId(0, android.R.id.background);
resultDr.setId(1, android.R.id.secondaryProgress);
resultDr.setId(2, android.R.id.progress);
Setting ids to drawables is crucial, and takes care of preserving bounds and actual state of progress bar
Use this style attribute for no word wrapping:
white-space: nowrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateClient {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
For me it works, and looks simple:
$auto_inc_db = mysql_query("SELECT * FROM my_table_name ORDER BY id ASC ");
while($auto_inc_result = mysql_fetch_array($auto_inc_db))
{
$last_id = $auto_inc_result['id'];
}
$next_id = ($last_id+1);
echo $next_id;//this is the new id, if auto increment is on
Referring to the Microsoft example: [https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.enableraisingevents?view=netframework-4.8]
Best would be to set:
myProcess.EnableRaisingEvents = true;
otherwiese the Code will be blocked. Also no additional properties needed.
// Start a process and raise an event when done.
myProcess.StartInfo.FileName = fileName;
// Allows to raise event when the process is finished
myProcess.EnableRaisingEvents = true;
// Eventhandler wich fires when exited
myProcess.Exited += new EventHandler(myProcess_Exited);
// Starts the process
myProcess.Start();
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
Console.WriteLine(
$"Exit time : {myProcess.ExitTime}\n" +
$"Exit code : {myProcess.ExitCode}\n" +
$"Elapsed time : {elapsedTime}");
}
There is a Win32 port of wget that works decently.
PowerShell's Invoke-WebRequest -Method Head
would work as well.
If BranchA has not been pushed to a remote then you can reorder the commits using rebase
and then simply merge
. It's preferable to use merge
over rebase
when possible because it doesn't create duplicate commits.
git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
You should dismiss you Dialog
in onPause()
so override it.
Also before dismissing you can check for null
and is showing like below snippet:
@Override
protected void onPause() {
super.onPause();
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
On Windows 7, go to C:\Users\%User_Name%\AppData\Roaming\Subversion and remove the auth directory. Just be aware if you are connected to more than 1 SVN server that this will remove the authentication for all of the SVN servers you have configured. If you want to reset just a single server:
Inside the auth directory you should see a folder called svn.simple. Open each of those files with a text editor to determine which one to remove and then remove just that single file.
RxAndroid
is another better alternative to this problem and it saves us from hassles of creating threads and then posting results on Android UI thread.
We just need to specify threads on which tasks need to be executed and everything is handled internally.
Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() {
@Override
public List<String> call() {
return mRestClient.getFavoriteMusicShows();
}
});
mMusicShowSubscription = musicShowsObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<String>>() {
@Override
public void onCompleted() { }
@Override
public void onError(Throwable e) { }
@Override
public void onNext(List<String> musicShows){
listMusicShows(musicShows);
}
});
By specifiying (Schedulers.io())
,RxAndroid will run getFavoriteMusicShows()
on a different thread.
By using AndroidSchedulers.mainThread()
we want to observe this Observable on the UI thread, i.e. we want our onNext()
callback to be called on the UI thread
You might also need to provide your user with an alert showing that those functions are disabled for the text input fields. This will work
function showError(){_x000D_
alert('you are not allowed to cut,copy or paste here');_x000D_
}_x000D_
_x000D_
$('.form-control').bind("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea class="form-control" oncopy="showError()" onpaste="showError()"></textarea>
_x000D_
As far as I understand you need mean terminate as Thread.Abort()
right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.
Thread myThread = new Thread(DoWork);
myThread.Abort();
myThread.Start();
Process example:
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;
class PrintProcessClass
{
private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;
// Print a file with any known extension.
public void PrintDoc(string fileName)
{
elapsedTime = 0;
eventHandled = false;
try
{
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = fileName;
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
return;
}
// Wait for Exited event, but not more than 30 seconds.
const int SLEEP_AMOUNT = 100;
while (!eventHandled)
{
elapsedTime += SLEEP_AMOUNT;
if (elapsedTime > 30000)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
}
}
// Handle Exited event and display process information.
private void myProcess_Exited(object sender, System.EventArgs e)
{
eventHandled = true;
Console.WriteLine("Exit time: {0}\r\n" +
"Exit code: {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
}
public static void Main(string[] args)
{
// Verify that an argument has been entered.
if (args.Length <= 0)
{
Console.WriteLine("Enter a file name.");
return;
}
// Create the process and print the document.
PrintProcessClass myPrintProcess = new PrintProcessClass();
myPrintProcess.PrintDoc(args[0]);
}
}
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
So there might be a few things wrong here.
First start by reading how to use XMLHttpRequest.open()
because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send()
. Here's an example from MDN:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "http://www.mozilla.org/", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send(null);
Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml
file.
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
request.send(null);
if (request.status == 0)
console.log(request.responseText);
Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.
You should check that the spring.handlers
and spring.schemas
files are on the classpath and have the right content.
This can be done with ClassLoader.getResource(..)
. You can run the method with a remote debugger in the runtime environment. The extensible XML authoring setup is described in the Spring Reference B.5. Registering the handler and the schema.
Normally, the files should be in the spring jar (springframework.jar/META-INF/) and on the classpath when Spring can be initiated.
Inline Javascript:
<button onclick="window.location='http://www.example.com';">Visit Page Now</button>
Defining a function in Javascript:
<script>
function visitPage(){
window.location='http://www.example.com';
}
</script>
<button onclick="visitPage();">Visit Page Now</button>
or in Jquery
<button id="some_id">Visit Page Now</button>
$('#some_id').click(function() {
window.location='http://www.example.com';
});
When we capture the image from Camera in Android then Uri
or data.getdata()
becomes null. We have two solutions to resolve this issue.
This is how to retrieve the Uri from the Bitmap Image. First capture image through Intent that will be the same for both methods:
// Capture Image
captureImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, reqcode);
}
}
});
Now implement OnActivityResult
, which will be the same for both methods:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==reqcode && resultCode==RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// Show Uri path based on Image
Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();
// Show Uri path based on Cursor Content Resolver
Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
}
}
Now create all above methods to create the Uri from Image and Cursor methods:
Uri path from Bitmap Image:
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
return Uri.parse(path);
}
Uri from Real path of saved image:
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
This is often achieved by throwing an error from the current context; then analyzing error object for properties like lineNumber
and fileName
(which some browsers have)
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
var err = getErrorObject();
err.fileName;
err.lineNumber; // or `err.line` in WebKit
Don't forget that callee.caller
property is deprecated (and was never really in ECMA 3rd ed. in the first place).
Also remember that function decompilation is specified to be implementation dependent and so might yield quite unexpected results. I wrote about it here and here.
\d
means 'digit'. +
means, '1 or more times'. So \d+
means one or more digit. It will match 12
and 1
.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mywebsite</groupId>
<artifactId>emusicstore</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.9</source>
<target>1.9</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
MyWebAppContextListener.java
package com.emusicstore.utils;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
public class MyWebAppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("************** Starting up! **************");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("************** Shutting down! **************");
System.out.println("Destroying Context...");
System.out.println("Calling MySQL AbandonedConnectionCleanupThread checkedShutdown");
AbandonedConnectionCleanupThread.checkedShutdown();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
if (driver.getClass().getClassLoader() == cl) {
try {
System.out.println("Deregistering JDBC driver {}");
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
System.out.println("Error deregistering JDBC driver {}");
ex.printStackTrace();
}
} else {
System.out.println("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader");
}
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.emusicstore.utils.MyWebAppContextListener</listener-class>
</listener>
<!-- ... -->
</web-app>
Source that inspired me for this bug fix.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
malloc()
and calloc()
are functions from the C standard library that allow dynamic memory allocation, meaning that they both allow memory allocation during runtime.
Their prototypes are as follows:
void *malloc( size_t n);
void *calloc( size_t n, size_t t)
There are mainly two differences between the two:
Behavior: malloc()
allocates a memory block, without initializing it, and reading the contents from this block will result in garbage values. calloc()
, on the other hand, allocates a memory block and initializes it to zeros, and obviously reading the content of this block will result in zeros.
Syntax: malloc()
takes 1 argument (the size to be allocated), and calloc()
takes two arguments (number of blocks to be allocated and size of each block).
The return value from both is a pointer to the allocated block of memory, if successful. Otherwise, NULL will be returned indicating the memory allocation failure.
Example:
int *arr;
// allocate memory for 10 integers with garbage values
arr = (int *)malloc(10 * sizeof(int));
// allocate memory for 10 integers and sets all of them to 0
arr = (int *)calloc(10, sizeof(int));
The same functionality as calloc()
can be achieved using malloc()
and memset()
:
// allocate memory for 10 integers with garbage values
arr= (int *)malloc(10 * sizeof(int));
// set all of them to 0
memset(arr, 0, 10 * sizeof(int));
Note that malloc()
is preferably used over calloc()
since it's faster. If zero-initializing the values is wanted, use calloc()
instead.
.on() is for jQuery version 1.7 and above. If you have an older version, use this:
$("#SomeId").live("click",function(){
//do stuff;
});
With pure javascript:
this === document.activeElement // where 'this' is a dom object
or with jquery's :focus
pseudo selector.
$(this).is(':focus');
Maybe you can try this method:
// DelEleInSlice delete an element from slice by index
// - arr: the reference of slice
// - index: the index of element will be deleted
func DelEleInSlice(arr interface{}, index int) {
vField := reflect.ValueOf(arr)
value := vField.Elem()
if value.Kind() == reflect.Slice || value.Kind() == reflect.Array {
result := reflect.AppendSlice(value.Slice(0, index), value.Slice(index+1, value.Len()))
value.Set(result)
}
}
Usage:
arrInt := []int{0, 1, 2, 3, 4, 5}
arrStr := []string{"0", "1", "2", "3", "4", "5"}
DelEleInSlice(&arrInt, 3)
DelEleInSlice(&arrStr, 4)
fmt.Println(arrInt)
fmt.Println(arrStr)
Result:
0, 1, 2, 4, 5
"0", "1", "2", "3", "5"
I would use ruby-build
with rbenv
. The following lines install Ruby 3.0.0 and set it as your default Ruby version:
$ brew update
$ brew install ruby-build
$ brew install rbenv
$ rbenv install 3.0.0
$ rbenv global 3.0.0
if (text[0] == '\0')
{
/* Code... */
}
Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen
than checking the first byte.
The above example is the fastest and less computation is required.
var myVar = $("#start").find('myClass').val();
needs to be
var myVar = $("#start").find('.myClass').val();
Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>
.
This is the fix that I "create" and it take out the GhostClick and implements the FastClick. Try on your own and let us know if it worked for you.
$(document).on('touchstart click', '.myBtn', function(event){
if(event.handled === false) return
event.stopPropagation();
event.preventDefault();
event.handled = true;
// Do your magic here
});
This is Chris Jester-Young's implementation, cleanest I've ever seen, combined with php.net's and a precision argument.
function formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = array('', 'K', 'M', 'G', 'T');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
echo formatBytes(24962496);
// 23.81M
echo formatBytes(24962496, 0);
// 24M
echo formatBytes(24962496, 4);
// 23.8061M
When you define a layout and view on XML, you can specify the layout width and height of a view to either be wrap content, or fill parent. Taking up half of the area is a bit harder, but if you had something you wanted on the other half you could do something like the following.
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"/>
<ImageView android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"/>
</LinearLayout>
Giving two things the same weight means that they will stretch to take up the same proportion of the screen. For more info on layouts, see the dev docs.
echo '<p class="paragraph'.$i.'"></p>'
should do the trick.
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
SyndFeedInput fr = new SyndFeedInput();
SyndFeed sf = fr.build(new XmlReader(myInputStream));
List<?> entries = sf.getEntries();
I think this is simpler for grabbing the array and stripping spaces:
@Value("#{'${my.array}'.replace(' ', '').split(',')}")
private List<String> array;
You can use \r
(carriage return). Demo:
import sys
total = 10000000
point = total / 100
increment = total / 20
for i in xrange(total):
if(i % (5 * point) == 0):
sys.stdout.write("\r[" + "=" * (i / increment) + " " * ((total - i)/ increment) + "]" + str(i / point) + "%")
sys.stdout.flush()
The problem is that codeAddress()
doesn't have enough scope to be callable from the button. You must declare it outside the callback to ready()
:
function codeAddress() {
var address = document.getElementById("formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
}
$(document).ready(function(){
// Do stuff here, including _calling_ codeAddress(), but not _defining_ it!
});
Even then however, getting a user's real IP address is going to be unreliable. All they need to do is use an anonymous proxy server (one that doesn't honor the headers for http_x_forwarded_for
, http_forwarded
, etc) and all you get is their proxy server's IP address.
You can then see if there is a list of proxy server IP addresses that are anonymous, but there is no way to be sure that is 100% accurate as well and the most it'd do is let you know it is a proxy server. And if someone is being clever, they can spoof headers for HTTP forwards.
Let's say I don't like the local college. I figure out what IP addresses they registered, and get their IP address banned on your site by doing bad things, because I figure out you honor the HTTP forwards. The list is endless.
Then there is, as you guessed, internal IP addresses such as the college network I metioned before. A lot use a 10.x.x.x format. So all you would know is that it was forwarded for a shared network.
Then I won't start much into it, but dynamic IP addresses are the way of broadband anymore. So. Even if you get a user IP address, expect it to change in 2 - 3 months, at the longest.
AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8
in the content type. It failed with a generic "Server Error"
and it took hours to figure out what it didn't like:
request.ContentType = "text/xml; encoding=utf-8";
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(con != null){
con.disconnect();
}if(inStream != null){
inStream.close();
}if(out != null){
out.flush();
out.close();
}
}
}
Since Python 3.5, you can also use splat *
unpacking syntax to unpack a generator expresion:
*(x for x in range(10)),
In Swift 4.2 I would do something like that:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let yourVC = segue.destination as? YourViewController {
yourVC.yourData = self.someData
}
}
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
How to get rid of a header(first row) and an index(first column).
To write to CSV file:
df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)
To read from CSV file:
df = pandas.read_csv('your_array.csv')
a = df.values
If you want to read a CSV file that doesn't contain a header, pass additional parameter header
:
df = pandas.read_csv('your_array.csv', header=None)
I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:
System.Web.HttpContext.Current.Request.UserHostAddress
Initially when i implemented a longClick and a click to perform two separate events the problem i face was that when i had a longclick , the application also performed the action to be performed for a simple click . The solution i realized was to change the return type of the longClick to true which is normally false by default . Change it and it works perfectly .
$sXML = download_page('http://alanstorm.com/atom');
// Comment This
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
// echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form. The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.
Instead of trying to learn vim, use a different easier editor (like nano, for example). As much as I like vim, I do not think using it in this case is the solution. It takes dedication and time to master it.
git config core.editor "nano"
Not sure why no one has mentioned two Base R functions specifically to do this: str2lang()
and str2expression()
. These are variants of parse()
, but seem to return the expression more cleanly:
eval(str2lang("5+5"))
# > 10
eval(str2expression("5+5"))
# > 10
Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Once you have started the SSH agent with:
eval $(ssh-agent)
Do either:
To add your private key to it:
ssh-add
This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.
To add and save your key permanently on macOS:
ssh-add -K
This will persist it after you close and re-open it by storing it in user's keychain.
To add and save your key permanently on Ubuntu (or equivalent):
ssh-add ~/.ssh/id_rsa
function trimArray(&$value)
{
$value = trim($value);
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');
by using array_walk function, we can remove space from array elements and elements return the result in same array.
Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines
If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.
Alternatively
you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well
you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions
Look at this:
function isPalindrome(word){
if(word==null || word.length==0){
// up to you if you want true or false here, don't comment saying you
// would put true, I put this check here because of
// the following i < Math.ceil(word.length/2) && i< word.length
return false;
}
var lastIndex=Math.ceil(word.length/2);
for (var i = 0; i < lastIndex && i< word.length; i++) {
if (word[i] != word[word.length-1-i]) {
return false;
}
}
return true;
}
Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!
Since the string is an array of char no need to use charAt functions!!!
Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome
Just an idea that first came to my mind (sorry if stupid). Three components of colors can be assumed 3D coordinates of points and then you could calculate distance between points.
F.E.
Point1 has R1 G1 B1
Point2 has R2 G2 B2
Distance between colors is
d=sqrt((r2-r1)^2+(g2-g1)^2+(b2-b1)^2)
Percentage is
p=d/sqrt((255)^2+(255)^2+(255)^2)
This is an old post however, one alternative is to use the command options:
ftp -n -s:ftpcmd.txt
the -n will suppress the initial login and then the file contents would be: (replace the 127.0.0.1 with your FTP site url)
open 127.0.0.1
user myFTPuser myftppassword
other commands here...
This avoids the user/password on separate lines
os.getenv('HOSTNAME')
and os.environ['HOSTNAME']
don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:
import socket
socket.gethostbyaddr(socket.gethostname())[0]
It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.
If you defined an alias in /etc/hosts then socket.gethostname()
will return the alias. platform.uname()[1]
does the same thing.
I ran into a case where the above didn't work. This is what I'm using now:
import socket
if socket.gethostname().find('.')>=0:
name=socket.gethostname()
else:
name=socket.gethostbyaddr(socket.gethostname())[0]
It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.
You name it... Lambda version... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
You need several includes... I leave you that as an exercise...
The best thing to do is.
1. fork twitter-bootstrap from github and clone locally.
they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.
2. Do not modify the bootstrap.css file
It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).
3. Create your own css file and overwrite whenever you want original bootstrap stuff
if they set a topbar with, let's say, color: black;
but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">
. If you declare your css file after bootstrap.css
, this will overwrite whatever you want to.
Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.
Angular cli has moved to @angular/cli
, so as from the github readme,
sudo npm uninstall -g @angular/cli
npm cache clean
Not 100% sure what you mean:
Trusted_Connection=True;
IS using Windows credentials and is 100% equivalent to:
Integrated Security=SSPI;
or
Integrated Security=true;
If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection
or Integrated Security
)
server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret
Only in this case, the SQL Server authentication mode is used.
If any of these two settings is present (Trusted_Connection=true
or Integrated Security=true/SSPI
), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD=
setting will be ignored and not used.
For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.
Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.
Summing up:
If you specify either Trusted_Connection=True;
or Integrated Security=SSPI;
or Integrated Security=true;
in your connection string
==> THEN (and only then) you have Windows Authentication happening. Any user id=
setting in the connection string will be ignored.
If you DO NOT specify either of those settings,
==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)
There is a workaround for 'virtual template method' if set of types for the template method is known in advance.
To show the idea, in the example below only two types are used (int
and double
).
There, a 'virtual' template method (Base::Method
) calls corresponding virtual method (one of Base::VMethod
) which, in turn, calls template method implementation (Impl::TMethod
).
One only needs to implement template method TMethod
in derived implementations (AImpl
, BImpl
) and use Derived<*Impl>
.
class Base
{
public:
virtual ~Base()
{
}
template <typename T>
T Method(T t)
{
return VMethod(t);
}
private:
virtual int VMethod(int t) = 0;
virtual double VMethod(double t) = 0;
};
template <class Impl>
class Derived : public Impl
{
public:
template <class... TArgs>
Derived(TArgs&&... args)
: Impl(std::forward<TArgs>(args)...)
{
}
private:
int VMethod(int t) final
{
return Impl::TMethod(t);
}
double VMethod(double t) final
{
return Impl::TMethod(t);
}
};
class AImpl : public Base
{
protected:
AImpl(int p)
: i(p)
{
}
template <typename T>
T TMethod(T t)
{
return t - i;
}
private:
int i;
};
using A = Derived<AImpl>;
class BImpl : public Base
{
protected:
BImpl(int p)
: i(p)
{
}
template <typename T>
T TMethod(T t)
{
return t + i;
}
private:
int i;
};
using B = Derived<BImpl>;
int main(int argc, const char* argv[])
{
A a(1);
B b(1);
Base* base = nullptr;
base = &a;
std::cout << base->Method(1) << std::endl;
std::cout << base->Method(2.0) << std::endl;
base = &b;
std::cout << base->Method(1) << std::endl;
std::cout << base->Method(2.0) << std::endl;
}
Output:
0
1
2
3
NB:
Base::Method
is actually surplus for real code (VMethod
can be made public and used directly).
I added it so it looks like as an actual 'virtual' template method.
Basic validation can be performed by choosing the type attribute of input elements. For example:
<input type="email" />
<input type="URL" />
<input type="number" />
using pattern attribute like:
<input type="text" pattern="[1-4]{5}" />
required attribute
<input type="text" required />
maxlength:
<input type="text" maxlength="20" />
min & max:
<input type="number" min="1" max="4" />
Why not use controller inheritance, all methods/properties defined in scope of HeaderCtrl are accessible in the controller inside ng-view. $scope.servHelper is accessible in all your controllers.
angular.module('fnetApp').controller('HeaderCtrl', function ($scope, MyHelperService) {
$scope.servHelper = MyHelperService;
});
<div ng-controller="HeaderCtrl">
<div ng-view=""></div>
</div>
For support to all API levels you can use it like this:
ViewPropertyAnimator.animate(view).translationYBy(-yourY).translationXBy(-yourX).setDuration(0);
Command 1.
git commit --amend -m "New and correct message"
Then,
Command 2.
git push origin --force
This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it __getitem__
and __len__
methods. I have tested this on Python 2 and 3.
class CustomRange:
def __init__(self, low, high):
self.low = low
self.high = high
def __getitem__(self, item):
if item >= len(self):
raise IndexError("CustomRange index out of range")
return self.low + item
def __len__(self):
return self.high - self.low
cr = CustomRange(0, 10)
for i in cr:
print(i)
Is your NavigationDrawerFragment extending the android.support.v4.app.Fragment? In other words, are you importing the correct package?
import android.support.v4.app.Fragment;
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
@TimeZoneInfo.ConvertTimeFromUtc(timeUtc, TimeZoneInfo.Local)
you just need to put this
($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));
($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));
Just incase if anyone is looking for how to do it in typescript here is the solution
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
// Some action
}
And yes as mentioned by @Coops below, please do not forget to include
import { Watch } from 'vue-property-decorator';
Edit: Alcalyn made a very good point of using Route type instead of using any
import { Watch } from 'vue-property-decorator';
import { Route } from 'vue-router';
Spark gives 5 types of Storage level
MEMORY_ONLY
MEMORY_ONLY_SER
MEMORY_AND_DISK
MEMORY_AND_DISK_SER
DISK_ONLY
cache()
will use MEMORY_ONLY
. If you want to use something else, use persist(StorageLevel.<*type*>)
.
By default persist()
will
store the data in the JVM heap as unserialized objects.
I had the same problem.
For now, I've settled with client-side Wildcard/Regex filtering based on http://www.codeproject.com/Articles/11556/Converting-Wildcards-to-Regexes?msg=1423024#xx1423024xx - it's simple and works as expected.
I've found another discussion on this topic: http://forums.asp.net/t/1654093.aspx/2/10
This post looks promising if you use Entity Framework >= 4.0:
Use SqlFunctions.PatIndex:
http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.patindex.aspx
Like this:
var q = EFContext.Products.Where(x => SqlFunctions.PatIndex("%CD%BLUE%", x.ProductName) > 0);
Note: this solution is for SQL-Server only, because it uses non-standard PATINDEX function.
Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:
$objPHPExcel = new PHPExcel();
$objPHPExcel->getDefaultStyle()
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
And it works flawlessly. Thank you, Mark Baker.
You'd use REGEXP_REPLACE
in order to remove all non-digit characters from a string:
select regexp_replace(column_name, '[^0-9]', '')
from mytable;
or
select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;
Of course you can write a function extract_number
. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.
create function extract_number(in_number varchar2) return varchar2 is
begin
return regexp_replace(in_number, '[^[:digit:]]', '');
end;
From the tutorial:
from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))
Is this role attribute necessary?
Answer: Yes.
It provides you:
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.
To do this you use an outer join:
select tablea.code, tablea.name, tableb.location from tablea left outer join
tableb on tablea.code = tableb.code
Because of an annoying design choice in Ruby before 1.9 — some_string[0]
returns the character code of the first character — the most portable way to write this is some_string[0,1]
, which tells it to get a substring at index 0 that's 1 character long.
I struggled with this, too. Here's what I found. Expanding on Adam's answer, here's a bit more detail, including how to encode VP9 with alpha in a Webm container.
First, Here's a CodePen playground you can play with, feel free to use my videos for testing.
<video width="600" height="100%" autoplay loop muted playsinline>
<source src="https://rotato.netlify.app/alpha-demo/movie-hevc.mov" type='video/mp4'; codecs="hvc1">
<source src="https://rotato.netlify.app/alpha-demo/movie-webm.webm" type="video/webm">
</video>
And here's a full demo page using z-index to layer the transparent video on top and below certain elements. (You can clone the Webflow template)
So, we'll need a Webm movie for Chrome, and an HEVC with Alpha (supported by Safari on all platforms since 2019)
For Chrome, I've tested successfully on version 30 from 2013. (Caniuse webm doesn't seem to say which webm codec is supported, so I had to try my way). Earlier versions of chrome seem to render a black area.
For Safari, it's simpler: Catalina (2019) or iOS 11 (2019)
Depending on which editing app you're using, I recommend exporting the HEVC with Alpha directly.
But many apps don't support the Webm format, especially on Mac, since it's not a part of AVFoundation.
I recommend exporting an intermediate format like ProRes4444 with an alpha channel to not lose too much quality at this step. Once you have that file, making your webm is as simple as
ffmpeg -i "your-movie-in-prores.mov" -c:v libvpx-vp9 movie-webm.webm
See more approaches in this blog post.
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
Take your input and make sure it's a string so that it's iterable.
Then perform a list comprehension and change each value back to a number.
Now, you can do the sum of all the numbers if you want:
inp = [int(i) for i in str(input("Enter a number:"))]
print sum(inp)
Or, if you really want to see the output while it's executing:
def printadd(x,y):
print x+y
return x+y
inp = [int(i) for i in str(input("Enter a number:"))]
reduce(printadd,inp)
position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;
Why is 21 the default port for FTP? Or 80 the default for HTTP? It is a convention.
The default font for iOS is San Francisco . You can refer the link for further details
You can upload artifacts via their native publishing capabilities (e.g. maven deploy, npm publish).
You can also upload artifacts to "raw" repositories via a simple curl request, e.g.
curl --fail -u admin:admin123 --upload-file foo.jar 'http://my-nexus-server.com:8081/repository/my-raw-repo/'
I found the best solution for me, after reading all your answers:
set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"
If AM I get 20160915_ 150101
(with a leading space and time).
If PM I get 20160915_2150101
.
You can try this:
string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);
you can remove hh or mm or ss or tt according your need where hh is hour in 12 hr formate, mm is minutes,ss is seconds,and tt is AM/PM.
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Yes, there is one here: http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding.
You can use php built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change filed name as your requirement
then the result is
and if you want to concat same filed using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
You will get the structure by typing the command:
.schema <tableName>
Best solution you have ever see.
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @Property function fields into dict.
"""
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @property function fields into dict.
Usage:
class MyDjangoModel(... PrintableModel):
to_dict_fields = (...)
to_dict_exclude = (...)
...
a_dict = [inst.to_dict(fields=..., exclude=...) for inst in MyDjangoModel.objects.all()]
"""
import typing
import django.core.exceptions
import django.db.models
import django.forms.models
def get_decorators_dir(cls, exclude: typing.Optional[set]=None) -> set:
"""
Ref: https://stackoverflow.com/questions/4930414/how-can-i-introspect-properties-and-model-fields-in-django
:param exclude: set or None
:param cls:
:return: a set of decorators
"""
default_exclude = {"pk", "objects"}
if not exclude:
exclude = default_exclude
else:
exclude = exclude.union(default_exclude)
return set([name for name in dir(cls) if name not in exclude and isinstance(getattr(cls, name), property)])
class PrintableModel(django.db.models.Model):
class Meta:
abstract = True
def __repr__(self):
return str(self.to_dict())
def to_dict(self, fields: typing.Optional[typing.Iterable]=None, exclude: typing.Optional[typing.Iterable]=None):
opts = self._meta
data = {}
# support fields filters and excludes
if not fields:
fields = set()
else:
fields = set(fields)
default_fields = getattr(self, "to_dict_fields", set())
fields = fields.union(default_fields)
if not exclude:
exclude = set()
else:
exclude = set(exclude)
default_exclude = getattr(self, "to_dict_exclude", set())
exclude = exclude.union(default_exclude)
# support syntax "field__childField__..."
self_fields = set()
child_fields = dict()
if fields:
for i in fields:
splits = i.split("__")
if len(splits) == 1:
self_fields.add(splits[0])
else:
self_fields.add(splits[0])
field_name = splits[0]
child_fields.setdefault(field_name, set())
child_fields[field_name].add("__".join(splits[1:]))
self_exclude = set()
child_exclude = dict()
if exclude:
for i in exclude:
splits = i.split("__")
if len(splits) == 1:
self_exclude.add(splits[0])
else:
field_name = splits[0]
if field_name not in child_exclude:
child_exclude[field_name] = set()
child_exclude[field_name].add("__".join(splits[1:]))
for f in opts.concrete_fields + opts.many_to_many:
if self_fields and f.name not in self_fields:
continue
if self_exclude and f.name in self_exclude:
continue
if isinstance(f, django.db.models.ManyToManyField):
if self.pk is None:
data[f.name] = []
else:
result = []
m2m_inst = f.value_from_object(self)
for obj in m2m_inst:
if isinstance(PrintableModel, obj) and hasattr(obj, "to_dict"):
d = obj.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
else:
d = django.forms.models.model_to_dict(
obj,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
result.append(d)
data[f.name] = result
elif isinstance(f, django.db.models.ForeignKey):
if self.pk is None:
data[f.name] = []
else:
data[f.name] = None
try:
foreign_inst = getattr(self, f.name)
except django.core.exceptions.ObjectDoesNotExist:
pass
else:
if isinstance(foreign_inst, PrintableModel) and hasattr(foreign_inst, "to_dict"):
data[f.name] = foreign_inst.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
elif foreign_inst is not None:
data[f.name] = django.forms.models.model_to_dict(
foreign_inst,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
elif isinstance(f, (django.db.models.DateTimeField, django.db.models.DateField)):
v = f.value_from_object(self)
if v is not None:
data[f.name] = v.isoformat()
else:
data[f.name] = None
else:
data[f.name] = f.value_from_object(self)
# support @property decorator functions
decorator_names = get_decorators_dir(self.__class__)
for name in decorator_names:
if self_fields and name not in self_fields:
continue
if self_exclude and name in self_exclude:
continue
value = getattr(self, name)
if isinstance(value, PrintableModel) and hasattr(value, "to_dict"):
data[name] = value.to_dict(
fields=child_fields.get(name),
exclude=child_exclude.get(name)
)
elif hasattr(value, "_meta"):
# make sure it is a instance of django.db.models.fields.Field
data[name] = django.forms.models.model_to_dict(
value,
fields=child_fields.get(name),
exclude=child_exclude.get(name),
)
elif isinstance(value, (set, )):
data[name] = list(value)
else:
data[name] = value
return data
https://gist.github.com/shuge/f543dc2094a3183f69488df2bfb51a52
This is my experience
.navbar { min-height:38px; }
.navbar .navbar-brand{ padding: 0 12px;font-size: 16px;line-height: 38px;height: 38px; }
.navbar .navbar-nav > li > a { padding-top: 0px; padding-bottom: 0px; line-height: 38px; }
.navbar .navbar-toggle { margin-top: 3px; margin-bottom: 0px; padding: 8px 9px; }
.navbar .navbar-form { margin-top: 2px; margin-bottom: 0px }
.navbar .navbar-collapse {border-color: #A40303;}
Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.
simple
:Create a directory:
mkdir simple
cd simple
Create a new module:
go mod init github.com/username/simple
# Here, the module name is: github.com/username/simple.
# You're free to choose any module name.
# It doesn't matter as long as it's unique.
# It's better to be a URL: so it can be go-gettable.
Put all your files in that directory.
Finally, run:
go run .
Alternatively, you can create an executable program by building it:
go build .
# then:
./simple # if you're on xnix
# or, just:
simple # if you're on Windows
For more information, you may read this.
Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.
You are not able to access those properties as they are marked as protected
meaning:
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
Use the StringFormat
property (or ContentStringFormat
on ContentControl
and its derivatives, e.g. Label
).
<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />
Note the {}
prior to the standard String.Format
positional argument notation allows the braces to be escaped in the markup extension language.
You can also dynamically add attributes with variables directly in an object literal.
const amountAttribute = 'amount';
const foo = {
[amountAttribute]: 1
};
foo[amountAttribute + "__more"] = 2;
Results in:
{
amount: 1,
amount__more: 2
}
As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices :( ), I put here a link towards the answer I made on a similar question :
https://stackoverflow.com/a/40707446/717372
Some sources on how to use HttpClient the right way:
Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}
private void UpdateExcel(string sheetName, int row, int col, string data)
{
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];
oSheet.Cells[row, col] = data;
oWB.Save();
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (oWB != null)
oWB.Close();
}
}
In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:
conda install openpyxl
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
This is quite an old thread, but I thought I'd throw my two cents in just the same as the accepted answer didn't work particularly well for me. I tried gbn's solution on a large dataset and found it to be terribly slow (>45 seconds on 5 million plus records in SQL Server 2012). Looking at the execution plan it's obvious that the issue is that it requires a SORT operation which slows things down significantly.
Here's an alternative that I lifted from the entity framework that needs no SORT operation and does a NON-Clustered Index search. This reduces the execution time down to < 2 seconds on the aforementioned record set.
SELECT
[Limit1].[DocumentID] AS [DocumentID],
[Limit1].[Status] AS [Status],
[Limit1].[DateCreated] AS [DateCreated]
FROM (SELECT DISTINCT [Extent1].[DocumentID] AS [DocumentID] FROM [dbo].[DocumentStatusLogs] AS [Extent1]) AS [Distinct1]
OUTER APPLY (SELECT TOP (1) [Project2].[ID] AS [ID], [Project2].[DocumentID] AS [DocumentID], [Project2].[Status] AS [Status], [Project2].[DateCreated] AS [DateCreated]
FROM (SELECT
[Extent2].[ID] AS [ID],
[Extent2].[DocumentID] AS [DocumentID],
[Extent2].[Status] AS [Status],
[Extent2].[DateCreated] AS [DateCreated]
FROM [dbo].[DocumentStatusLogs] AS [Extent2]
WHERE ([Distinct1].[DocumentID] = [Extent2].[DocumentID])
) AS [Project2]
ORDER BY [Project2].[ID] DESC) AS [Limit1]
Now I'm assuming something that isn't entirely specified in the original question, but if your table design is such that your ID column is an auto-increment ID, and the DateCreated is set to the current date with each insert, then even without running with my query above you could actually get a sizable performance boost to gbn's solution (about half the execution time) just from ordering on ID instead of ordering on DateCreated as this will provide an identical sort order and it's a faster sort.
Expanding on Atrur Klesun's idea... you can just access it by its name if you use getElementById to reach the form. In one line:
document.getElementById('form_id').elements['select_name'].value;
I used it like so for radio buttons and worked fine. I guess it's the same here.
Serge is right - my workaround:
function mySleep (sec)
{
SpreadsheetApp.flush();
Utilities.sleep(sec*1000);
SpreadsheetApp.flush();
}
EDIT: Okay, now we know it's Java...
Section 4.2.2 of the Java Language Specification states:
The Java programming language provides a number of operators that act on integral values:
[...]
The numerical operators, which result in a value of type int or long: [...] The additive operators + and - (§15.18)
In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int
or long
, which is why you need to cast to assign to a short
variable.
Original answer (C#)
In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:
int operator +(int x, int y);
uint operator +(uint x, uint y);
long operator +(long x, long y);
ulong operator +(ulong x, ulong y);
float operator +(float x, float y);
double operator +(double x, double y);
These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:
decimal operator +(decimal x, decimal y);
(Enumeration addition, string concatenation and delegate combination are also defined there.)
As you can see, there's no short operator +(short x, short y)
operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
In addition to the other answers, this error can result if there's an inconsistency in an order by clause. For instance:
select
substr(year_month, 1, 4)
,count(*) as tot
from
schema.tbl
group by
substr(year_month, 1, 4)
order by
year_month
SELECT *
FROM Header WHERE (userID LIKE '%''%')
Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.
document.getElementById("ele_id").style.color="blue";
But, for changing multiple properies the more robust way is using Object.assign()
or, object spread operator {...}
;
const ele=document.getElementById("ele_id");
const custom_style={
display: "block",
color: "red"
}
//Object.assign():
Object.assign(ele.style,custum_style);
Spread operator works similarly, just the syntax is a little different.
public class CustomCollection : List<Object>
{
public Object this[int index]
{
// ...
}
}
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
The other answers are WRONG.
Running argsort
once is not the solution.
For example, the following code:
import numpy as np
x = [3,1,2]
np.argsort(x)
yields array([1, 2, 0], dtype=int64)
which is not what we want.
The answer should be to run argsort
twice:
import numpy as np
x = [3,1,2]
np.argsort(np.argsort(x))
gives array([2, 0, 1], dtype=int64)
as expected.
You can use the spool
command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool
can change the file that's being written to, so you can have several queries writing to different files just by putting spool
commands between them:
spool "\path\to\spool1.txt"
select /*csv*/ * from employees;
spool "\path\to\spool2.txt"
select /*csv*/ * from locations;
spool off;
You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set
command, though some of those do not translate to SQL Developer.
Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.
A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.
Whilst there are several good answers here, I must point out that it is not good practice to display system exception messages on error pages (which is what I am assuming you want to do). You may inadvertently reveal things you do not wish to do so to malicious users. For example Sql Server exception messages are very verbose and can give the user name, password and schema information of the database when an error occurs. That information should not be displayed to an end user.
I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.
See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578
So, when using foreach
if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.
/**
* Filter all `selected` items
*
* @link https://laravel.com/docs/7.x/collections#method-filter
*/
$selected = $collection->filter(function($value, $key) {
return $value->selected;
})->toArray();
.aspx
uses a full lifecycle (Init
, Load
, PreRender
) and can respond to button clicks etc.
An .ashx
has just a single ProcessRequest
method.
I just added the existing framework folder manually into the project navigator. Worked for me.
If you are using WebApi, HttpResponseMessage is a more elegant way to do it
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}
The problem with your attempt at the psql
command line is the direction of the slashes:
newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql # correct
To be clear, psql
commands start with a backslash, so you should have put \i
instead. What happened as a result of your typo is that psql
ignored everything until finding the first \
, which happened to be followed by db
, and \db
happens to be the psql
command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.
Further, it seems that psql
expects the filepath
argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).
It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.
Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin
suggests a .backup
extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin
seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql
\i
command as shown above.
import re
def email():
email = raw_input("enter the mail address::")
match = re.search(r'[\w.-]+@[\w.-]+.\w+', email)
if match:
print "valid email :::", match.group()
else:
print "not valid:::"
email()
In your function check for the keycode 8 (backspace) or 46 (delete)
Yes:
<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>
The select()
function from dplyr is powerful for subsetting columns. See ?select_helpers
for a list of approaches.
In this case, where you have a common prefix and sequential numbers for column names, you could use num_range
:
library(dplyr)
df1 <- data.frame(first = 0, col1 = 1, col2 = 2, col3 = 3, col4 = 4)
df1 %>%
select(num_range("col", c(1, 4)))
#> col1 col4
#> 1 1 4
More generally you can use the minus sign in select()
to drop columns, like:
mtcars %>%
select(-mpg, -wt)
Finally, to your question "is there an easy way to create a workable vector of column names?" - yes, if you need to edit a list of names manually, use dput
to get a comma-separated, quoted list you can easily manipulate:
dput(names(mtcars))
#> c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am",
#> "gear", "carb")
You should override toString()
method in your Dog
class. which will be called when you use this object in sysout.
This will give you the result you're giving as an example:
SELECT DISTINCT a, b
FROM pairs
According to this page https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html it is only available if (Enabled only in a UIWebView with the allowsInlineMediaPlayback property set to YES.) I understand in Mobile Safari this is YES on iPad and NO on iPhone and iPod Touch.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
Here is my updated code. It works fine and it can help you.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
function go(loc) {
document.getElementById('calendar').src = loc;
}
</script>
</head>
<body>
<iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>
<form method="post">
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
<input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
</form>
</body>
</html>
Riya,
Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:
// add @ to the string to allow split over multiple lines
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance.
The substring starts at a specified character position. great";
// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
.Where(x => x.Length > 0).Select(x => x.Trim());
// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
Console.WriteLine(subword);
}
enjoy...
This will get you the generic link:
selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();
If you want to have it specify a parameter then you will have to test for each one:
...
int i = 1;
selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...
The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.
Please excuse if the code is not perfect, I have not tested myself.
You can use just:
Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)
then after encoding you'll receive text 'MjE4Nqk5'
Check your Elastic version.
I had these problem because I was looking at the incorrect version's documentation.