From the docs, to send HTML e-mail you want to use alternative content-types, like this:
from django.core.mail import EmailMultiAlternatives
subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt
:
Hello {{ username }} - your account is activated.
and an HTMLy one, stored under email.html
:
Hello <strong>{{ username }}</strong> - your account is activated.
You can then send an e-mail using both those templates by making use of get_template
, like this:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
plaintext = get_template('email.txt')
htmly = get_template('email.html')
d = Context({ 'username': username })
subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Running the command prompt or Powershell ISE as an administrator fixed this for me.
But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.
Other answerers have told you not to do it. But yes, you can do it. You can supply Thread.Abort()
as the delegate to be called by the Task's cancellation mechanism. Here is how you could configure this:
class HardAborter
{
public bool WasAborted { get; private set; }
private CancellationTokenSource Canceller { get; set; }
private Task<object> Worker { get; set; }
public void Start(Func<object> DoFunc)
{
WasAborted = false;
// start a task with a means to do a hard abort (unsafe!)
Canceller = new CancellationTokenSource();
Worker = Task.Factory.StartNew(() =>
{
try
{
// specify this thread's Abort() as the cancel delegate
using (Canceller.Token.Register(Thread.CurrentThread.Abort))
{
return DoFunc();
}
}
catch (ThreadAbortException)
{
WasAborted = true;
return false;
}
}, Canceller.Token);
}
public void Abort()
{
Canceller.Cancel();
}
}
disclaimer: don't do this.
Here is an example of what not to do:
var doNotDoThis = new HardAborter();
// start a thread writing to the console
doNotDoThis.Start(() =>
{
while (true)
{
Thread.Sleep(100);
Console.Write(".");
}
return null;
});
// wait a second to see some output and show the WasAborted value as false
Thread.Sleep(1000);
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted);
// wait another second, abort, and print the time
Thread.Sleep(1000);
doNotDoThis.Abort();
Console.WriteLine("Abort triggered at " + DateTime.Now);
// wait until the abort finishes and print the time
while (!doNotDoThis.WasAborted) { Thread.CurrentThread.Join(0); }
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted + " at " + DateTime.Now);
Console.ReadKey();
I found I had installed 32-bit Eclipse by mistake, and was trying to use it with a 64-bit JRE, which is why I got this error. To see whether you have 32 or 64 bit Eclipse installed, see this answer: https://stackoverflow.com/a/9578565/191761
I fixed it by doing
sudo chown root:staff -R /usr/local/share/zsh
in my case other directories inside share/ also have "staff" group assigned
Hibernate tries to insert data that violate underlying database integrity contraints.
There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).
Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering]
part).
JP, After checking your solution, I was still having issues in Firefox where it wouldn't preload the images before moving along with loading the page. I discovered this by putting some sleep(5)
in my server side script. I implemented the following solution based off yours which seems to solve this.
Basically I added a callback to your jQuery preload plugin, so that it gets called after all the images are properly loaded.
// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) { this.splice(i,1); }
}
};
// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
checklist = this.toArray();
this.each(function() {
$('<img>').attr({ src: this }).load(function() {
checklist.remove($(this).attr('src'));
if (checklist.length == 0) { callback(); }
});
});
};
Out of interest, in my context, I'm using this as follows:
$.post('/submit_stuff', { id: 123 }, function(response) {
$([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
// Update page with response data
});
});
Hopefully this helps someone who comes to this page from Google (as I did) looking for a solution to preloading images on Ajax calls.
or
is NOT the same as ||
. Use only ||
operator instead of the or
operator.
Here are some reasons. The:
or
operator has a lower precedence than ||
.or
has a lower precedence than the =
assignment operator.and
and or
have the same precedence, while &&
has a higher precedence than ||
.The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
just add --presets '@babel/preset-env'
e.g.
babel-node --trace-deprecation --presets '@babel/preset-env' ./yourscript.js
OR
in babel.config.js
module.exports = {
presets: ['@babel/preset-env'],
};
The !important
should only be used when you have selectors in your style sheet with conflicting specificity.
But even when you have conflicting specificity, it is better to create a more specific selector for the exception. In your case it's better to have a class
in your HTML which you can use to create a more specific selector which doesn't need the !important
rule.
td.a-semantic-class-name { height: 100px; }
I personally never use !important
in my style sheets. Remember that the C in CSS is for cascading. Using !important
will break this.
I use moment for all my time manipulation/display needs (both client side, and node.js if you use it), if you just need a simple format the answers above will do, if you are looking for something a bit more complex, moment is the way to go IMO.
You can use node File System command fs.stat to check if dir exists and fs.mkdir to create a directory with callback, or fs.mkdirSync to create a directory without callback, like this example:
//first require fs
const fs = require('fs');
// Create directory if not exist (function)
const createDir = (path) => {
// check if dir exist
fs.stat(path, (err, stats) => {
if (stats.isDirectory()) {
// do nothing
} else {
// if the given path is not a directory, create a directory
fs.mkdirSync(path);
}
});
};
Using bootstrap with a little bit of customization, the following seems to work for me:
I need 3 partitions in my container and I tried this:
CSS:
.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
padding-top: 20px;
border: 1px solid #cecece;
height: 100%;
}
.midnav {
padding: 0px;
}
HTML:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-md-2 sidenav text-left">Some content 1</div>
<div class="col-md-9 midnav text-left">Some content 2</div>
<div class="col-md-1 sidenav text-center">Some content 3</div>
</div>
</div>
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
Even easier you can just use Arrays, so you will get a String with the values of the array separated by a ","
String concat = Arrays.toString(myArray);
so you will end up with this: concat = "[a,b,c]"
Update
You can then get rid of the brackets using a sub-string as suggested by Jeff
concat = concat.substring(1, concat.length() -1);
so you end up with concat = "a,b,c"
if you want to use Kotlin:
val concat = myArray.joinToString(separator = ",") //"a,b,c"
The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?
You can use git blame
for this, it will anotate each line with a SHA1 and a date when it was changed. git blame
can also tell you when a certain line was deleted or where it was moved if you are interested in that.
If you are trying to find out, when a certain bug was introduced, git bisect
is a very powerfull tool. git bisect
will do a binary search on your history. You can use git bisect start
to start bisecting, then git bisect bad
to mark a commit where the bug is present and git bisect good
to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.
Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.
If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
For 100% viewport height use:
overflow: auto;
max-height: 100vh;
Simple Steps that I followed.
problem: I was trying to connect to an endpoint(https://%s.blob.core.windows.net) using a simple java class(main method).
So I was getting this certification issue as mentioned above, in the question.
Solution:
Get the certificate using a browser(chrome). To do this paste your endpoint URL in the browser and enter. Now you will see a lock icon, click on that -->certificate--> details --> copy to files--> download it.
open the cmd(i am using windows) as admin and then navigate to the directory where you have downloaded the .cer file.
3.(Optional)If you are using multiple JDK in the same machine then change your JDK version the same as you are using in your application.
keytool -import -alias mycertificate -keystore "C:\Program Files\Java\jdk-11.0.5\lib\security\cacerts" -file myurlcrt.cer
Give the default password: changeit
Trust this certificate: yes
And you are done.
Thanks!
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
The best solution is to use async Task
. You should avoid async void
for several reasons, one of which is composability.
If the method cannot be made to return Task
(e.g., it's an event handler), then you can use SemaphoreSlim
to have the method signal when it is about to exit. Consider doing this in a finally
block.
Both ItemListener
as well as ActionListener
, in case of JCheckBox
have the same behaviour.
However, major difference is ItemListener
can be triggered by calling the setSelected(true)
on the checkbox.
As a coding practice do not register both ItemListener
as well as ActionListener
with the JCheckBox
, in order to avoid inconsistency.
First open your SSH server with username and password and change to the default root user(User with all permissions) then follow the steps below,
crontab -l
now you will see the list of
all cronjobs.crontab -e
a file with all cron jobs will be
opened.min hr
dayofmonth month dayofweek pathtocronjobfile
and save the file.crontab: installing new
crontab
now again check the list of cronjobs your cron job will be
listed there.jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
get the latest version information from:
https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin
click on the latest version (or the one you'd like to use) and you'll see the the dependency info (as of 2019-05 it's 3.8.1):
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
you might want to use the version tag and the comment for your plugin tag.
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
if you like you can modify your pom to have the version information in the properties tag as outlined in another answer.
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
Check out DBGhost http://www.innovartis.co.uk/. I have used in an automated fashion for 2 years now and it works great. It allows our DB builds to happen much like a Java or C build happens, except for the database. You know what I mean.
Unfortunately it does not work in Chrome or Edge, but it does work in FireFox:
$(document)
// uncheck it when clicked
.on("click","input[type='radio']", function(){ $(this).prop("checked",false); })
// re-check it if value is changed to this input
.on("change","input[type='radio']", function(){ $(this).prop("checked",true); });
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/logout"
android:icon="@drawable/logout"
android:title="Log Out"
app:showAsAction="always"
/>
</menu>
This did the trick for me!
if your springfox version higher than 2.5, should be add WebSecurityConfiguration as below:
@Override
public void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests()
.antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}
There are many ways to filter for element ancestors.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
Beware, closest()
method includes element itself while checking for selector.
Alternatively, if you have a unique selector matching the $elem
, e.g #myElem
, you can use:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
.parentClass #myElem { /* CSS property set */ }
If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.
You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo
is also supported.
The following is a nice generic alternative to valueOf()
public static RandomEnum getEnum(String value) {
for (RandomEnum re : RandomEnum.values()) {
if (re.description.compareTo(value) == 0) {
return re;
}
}
throw new IllegalArgumentException("Invalid RandomEnum value: " + value);
}
To go back without refreshing the page, We can do in html like below javascript:history.back()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016
Step 1: Right button mouse > Select "Edit Top 200 Rows"
Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)
Step 3: Modify the query
Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)
If you use Python3x then string
is not the same type as for Python 2.x, you must cast it to bytes (encode it).
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
Also do not use variable names like string
or file
while those are names of module or function.
EDIT @Tom
Yes, non-ASCII text is also compressed/decompressed. I use Polish letters with UTF-8 encoding:
plaintext = 'Polish text: acelnószzACELNÓSZZ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
outfile_content = infile.read().decode('UTF-8')
print(outfile_content)
Another possibility: {{ URL::route('index') }}
I suppose you want to find 'simple' paths (a path is simple if no node appears in it more than once, except maybe the 1st and the last one).
Since the problem is NP-hard, you might want to do a variant of depth-first search.
Basically, generate all possible paths from A and check whether they end up in G.
Try making Internet Explorer your default browser temporarily.
You have to know that:
Assignment operators syntax is: variable = expression;
For this reason 1 += 2
-> 1 = 1 + 2
is not a valid syntax as the left operand isn't a variable. The error in this case is ReferenceError: invalid assignment left-hand side
.
x += y
is the short form for x = x + y
, where x
is the variable and x + y
the expression.
The result of the sum is 15.
sum = 0; sum = sum + 1; // 1 sum = sum + 2; // 3 sum = sum + 3; // 6 sum = sum + 4; // 10 sum = sum + 5; // 15
Other assignment operator shortcuts works the same way (relatively to the standard operations they refer to). .
I think it works with getLastInsertId()
if you use InnoDB Tables in your MySQL Database. You also can use $this->Model->id
What the browser does when you've got
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
Follow these simple steps :
1: In the Rmarkdown script run Knit(Ctrl+Shift+K) 2: Then after the html markdown is opened click Open in Browser(top left side) and the html is opened in your web browser 3: Then use Ctrl+P and save as PDF .
A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824
Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.
>>> hash("Look at me!!")
6941904779894686356
These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set
and dict
. In a list
, if you want to check if a value is in the list, with if x in values:
, Python needs to go through the whole list and compare x
with each value in the list values
. This can take a long time for a long list
. In a set
, Python keeps track of each hash, and when you type if x in values:
, Python will get the hash-value for x
, look that up in an internal structure and then only compare x
with the values that have the same hash as x
.
The same methodology is used for dictionary lookup. This makes lookup in set
and dict
very fast, while lookup in list
is slow. It also means you can have non-hashable objects in a list
, but not in a set
or as keys in a dict
. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.
Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>>
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299
This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.
Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.
Assuming your row number is in B1
, you can use INDIRECT
:
=INDIRECT("A" & B1)
This takes a cell reference as a string (in this case, the concatenation of A
and the value of B1
- 5), and returns the value at that cell.
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
The solution seems to be to add multiple @font-face
rules, for example:
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
By the way, it would seem Google Chrome doesn't know about the format("ttf")
argument, so you might want to skip that.
(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)
Also you can use ui-sref-active directive:
<ul>
<li ui-sref-active="active" class="item">
<a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
</li>
<!-- ... -->
</ul>
Or filters:
"stateName" | isState
& "stateName" | includedByState
I like to use Pirni (availble for free in Cydia on a jailbroken device), or there's also Pirni Pro now for a few bucks (http://en.wikipedia.org/wiki/Pirni). I've been using the pirni-derv script available for free on Google Code (http://code.google.com/p/pirni-derv/) mixed with Pirni and it's been working very well. I recommend it.
To Use Jquery in Angular2(4)
Follow these setps
install the Jquery and Juqry type defination
For Jquery Installation npm install jquery --save
For Jquery Type defination Installation npm install @types/jquery --save-dev
and then simply import the jquery
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
console.log($(window)); // jquery is accessible
}
Increasing column size with ALTER
will not lose any data:
alter table [progennet_dev].PROGEN.LE
alter column UR_VALUE_3 varchar(500)
As @Martin points out, remember to explicitly specify NULL | NOT NULL
So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.
What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.
I think the question here is how to find .bashrc file on Windows.
Since you are using Windows, you can simply use commands like
start .
OR
explorer .
to open the window with the root directory of your Git Bash installation where you'll find the .bashrc
file. You may need to create one if it doesn't exist.
You can use Windows tools like Notepad++ to edit the file instead of using Vim in your Bash window.
If an URL pattern starts with /
, then it's relative to the context root. The /Admin/*
URL pattern would only match pages on http://localhost:8080/EMS2/Admin/*
(assuming that /EMS2
is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*
, so your URL pattern never matches.
You need to prefix your URL patterns with /faces/Html
as well like so:
<url-pattern>/faces/Html/Admin/*</url-pattern>
You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html
path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml
.
Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping>
with multiple <url-pattern>
entries:
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>
If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.
I suggest you "Disable all break points":
Source:
using html5 data attribute...
try this
Html
Product price: $<span id="product_price">500</span>
<br>Total price: $500
<br>
<input type="button" data-quantity="2" value="2
Qty">
<input type="button" data-quantity="4" class="mnozstvi_sleva" value="4
Qty">
<br>Total
<input type="text" id="count" value="1">
JS
$(function(){
$('input:button').click(function () {
$('#count').val($(this).data('quantity') * $('#product_price').text());
});
});
Try with a CASE in this way :
SUM(CASE
WHEN PaymentType = "credit card"
THEN TotalAmount
ELSE 0
END) AS CreditCardTotal,
Should give what you are looking for ...
While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.
For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.
phantomjs.exe --web-security=no script.js
See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes
A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:
.clear { height: 50px; width: 25px; }
Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both;
attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:
.clear { clear: both; }
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
Do whatever you want as long as its minimal, consistent, and doesn't break any rules.
Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m
and p
prefixes to members and parameters, respectively, giving:
#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>
#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"
#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS
namespace lowercase_identifers
{
class separated_by_underscores
{
public:
void because_underscores_are() const
{
volatile int mostLikeSpaces = 0; // but local names are condensed
while (!mostLikeSpaces)
single_statements(); // don't need braces
for (size_t i = 0; i < 100; ++i)
{
but_multiple(i);
statements_do();
}
}
const complex_type& value() const
{
return mValue; // no conflict with value here
}
void value(const complex_type& pValue)
{
mValue = pValue ; // or here
}
protected:
// the more public it is, the more important it is,
// so order: public on top, then protected then private
template <typename Template, typename Parameters>
void are_upper_camel_case()
{
// gman was here
}
private:
complex_type mValue;
};
}
#endif
That. (And like I've said in comments, do not adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)
Try this
@Entity
@Table(name="tblperson")
public class Person {
public int id;
public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
this.otherInfo= otherInfo;
}
rest of attributes ...
}
@Entity
@Table(name="tblotherInfo")
public class OtherInfo {
private int id;
private Person person;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)
public College getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
rest of attributes ...
}
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}?
Working fiddle as promised: http://jsfiddle.net/teDQ2/
I had same issue with sqlite. My models.py looked all right. I did the following:
sqlite3 db.sqlite3
.tables
PRAGMA table_info(table_name);
Thru PRAGMA I was able to see that there was columns missing in the table failing. I dropped all tables in the app. Be careful because this will make lose your data in the tables.
DROP table table_name
.quit
Then do this:
python manage.py makemigrations your_app
python manage.py migrate your_app
python manage.py sqlmigrate your_app 0001
Then enter again to sqlite as follows and paste all the code you got from sqlimigrate:
sqlite3 db.sqlite3
As an example, this is what I pasted inside sqlite:
CREATE TABLE "adpet_ad" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(200) NOT NULL, "breed" varchar(30) NULL, "weight" decimal NULL, "age" integer NULL, "text" text NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "picture" BLOB NULL, "content_type" varchar(256) NULL, "name" varchar(100) NULL, "phone" varchar(31) NOT NULL, "gender_id" integer NULL REFERENCES "adpet_gender" ("id") DEFERRABLE INITIALLY DEFERRED, "owner_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "size_id" integer NULL REFERENCES "adpet_size" ("id") DEFERRABLE INITIALLY DEFERRED, "specie_id" integer NULL REFERENCES "adpet_specie" ("id") DEFERRABLE INITIALLY DEFERRED, "sterilized_id" integer NULL REFERENCES "adpet_sterilized" ("id") DEFERRABLE INITIALLY DEFERRED, "vaccinated_id" integer NULL REFERENCES "adpet_vaccinated" ("id") DEFERRABLE INITIALLY DEFERRED);
ALTER DATABASE name OWNER TO new_owner;
See the Postgresql manual's entry on this for more details.
I realize this doesn't directly apply from the title of the question, However some ways to deal with a variable range could be to select the range each time the code runs -- especially if you are interested in a user-selected range. If you are interested in that option, you can use the Application.InputBox (official documentation page here). One of the optional variables is 'type'. If the type is set equal to 8, the InputBox also has an excel-style range selection option. An example of how to use it in code would be:
Dim rng as Range
Set rng = Application.InputBox(Prompt:= "Please select a range", Type:=8)
Note:
If you assign the InputBox value to a none-range variable (without the Set
keyword), instead of the ranges, the values from the ranges will be assigned, as in the code below (although selecting multiple ranges in this situation may require the values to be assigned to a variant):
Dim str as String
str = Application.InputBox(Prompt:= "Please select a range", Type:=8)
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
After combining many answers and suggestion here, this is my final answer, which works well with flex
, which allows us to make columns with equal height, it also checks the last index, and you don't need to repeat the inner HTML. It doesn't use clearfix
:
<div ng-repeat="prod in productsFiltered=(products | filter:myInputFilter)" ng-if="$index % 3 == 0" class="row row-eq-height">
<div ng-repeat="i in [0, 1, 2]" ng-init="product = productsFiltered[$parent.$parent.$index + i]" ng-if="$parent.$index + i < productsFiltered.length" class="col-xs-4">
<div class="col-xs-12">{{ product.name }}</div>
</div>
</div>
It will output something like this:
<div class="row row-eq-height">
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
</div>
<div class="row row-eq-height">
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
<div class="col-xs-4">
<div class="col-xs-12">
Product Name
</div>
</div>
</div>
Use java.sql.Timestamp.toString if you want to get fractional seconds in text representation. The difference betwen Timestamp from DB and Java Date is that DB precision is nanoseconds while Java Date precision is milliseconds.
For the ones starting a rails app with existing database there is a cool gem called schema_to_scaffold
to generate a scaffold script.
it outputs:
rails g scaffold users fname:string lname:string bdate:date email:string encrypted_password:string
from your schema.rb
our your renamed schema.rb.
Check it
You have a string like this.
"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"
Then you can covert it to ArrayList via Gson like
var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()
Your HotelInfo class should like this.
import com.squareup.moshi.Json
data class HotelInfo(
@Json(name="cityName")
val cityName: String? = null,
@Json(name="id")
val id: Int? = null,
@Json(name="hotelId")
val hotelId: String? = null,
@Json(name="hotelName")
val hotelName: String? = null
)
Everything in the java.lang
package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util
package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
Follow the 3 step approach for a one or a few number of tags.
command: git rev-parse <tag name>
example: git rev-parse v0.1.0-Demo
example output: db57b63b77a6bae3e725cbb9025d65fa1eabcde
command: git tag -d <tag name>
example: git tag -d v0.1.0-Demo
example output: Deleted tag 'v0.1.0-Demo' (was abcde)
command: git tag -a <tag name> -m "appropriate message" <commit id>
example: git tag -a v0.1.0-full -m "renamed from v0.1.0-Demo" db57b63b77a6bae3e725cbb9025d65fa1eabcde
example output: Nothing or basically <No error>
Once the local git is ready with the tag name change, these changes can be pushed back to the origin for others to take these:
command: git push origin :<old tag name> <new tag name>
example: git push origin :v0.1.0-Demo v0.1.0-full
example output: <deleted & new tags>
By default Vagrant uses a generated private key to login, you can try this:
ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1
OperationContext.Current.RequestContext.RequestMessage
this context is accesible server side during processing of request. This doesn`t works for one-way operations
On my side I created a sub MyMsgBox replacing \n in the prompt by ControlChars.NewLine
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as @eumiro has pointed out in comments - strftime
IF you want to handle 'standard' JSON representation of the Date then better to use this pattern: "yyyy-MM-dd'T'HH:mm:ssX"
.
Notice the X
on the end. It will handle timezones in ISO 8601 standard, and ISO 8601 is exactly what produces this statement in Javascript new Date().toJSON()
Comparing to other answers it has some benefits:
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Answering your question as the examples also given previously:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
You may be looking for following code:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
Just set the y to be always on top. Need to conform with UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollView.contentOffset.y = 0.0
}
This will keep the Deceleration / Acceleration effect of the scrolling.
This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.
Fix :-
function FocusOnInput() {
var element = document.getElementById('txtContactMobileNo');
element.focus();
setTimeout(function () { element.focus(); }, 1);
}
And call FocusOnInput() on $(document).ready(function () {.....};
function isIosDevice(){
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
$iosDevice = array('iphone', 'ipod', 'ipad');
$isIos = false;
foreach ($iosDevice as $val) {
if(stripos($userAgent, $val) !== false){
$isIos = true;
break;
}
}
return $isIos;
}
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
David's answer is correct, but if it's still a little abstract, here are two examples:
You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:
void freeAndZero(void** ptr)
{
free(*ptr);
*ptr = 0;
}
void* ptr = malloc(...);
...
freeAndZero(&ptr);
In C++ to do the same, you might do:
template<class T> void freeAndZero(T* &ptr)
{
delete ptr;
ptr = 0;
}
int* ptr = new int;
...
freeAndZero(ptr);
When dealing with linked-lists - often simply represented as pointers to a next node:
struct Node
{
value_t value;
Node* next;
};
In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL
pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:
void insert(Node* &list)
{
...
if(!list) list = new Node(...);
...
}
There's an example in this question.
Or just use this in your View(Razor page)
@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))
I recommend that don't add date format in your model class
Come, let us recurse together.
def locations_of_substring(string, substring):
"""Return a list of locations of a substring."""
substring_length = len(substring)
def recurse(locations_found, start):
location = string.find(substring, start)
if location != -1:
return recurse(locations_found + [location], location+substring_length)
else:
return locations_found
return recurse([], 0)
print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]
No need for regular expressions this way.
I wish Visual Studio Code could handle:
#region Function Write-Log
Function Write-Log {
...
}
#endregion Function Write-Log
Right now Visual Studio Code just ignores it and will not collapse it. Meanwhile Notepad++ and PowerGUI handle this just fine.
Update: I just noticed an update for Visual Studio Code. This is now supported!
The problem is in the Eclipse Maven support, the related question is here.
Under Eclipse, the java.home
variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files
doesn't include the JDK so tools.jar
is not being found.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini
(before -vmargs
!):
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).
Use jQuery .siblings()
to select the matching sibling.
$(this).siblings('.bidbutton');
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
I know it's a very late answer but I'd like to share what I did as per this link:
I added the below code to the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
And this Advice Controller in order to get the version as model attribute:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class CommonControllerAdvice
{
@Autowired
BuildProperties buildProperties;
@ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}
If you use Kotlin, the next one is a good solution:
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val list = dataSnapshot.children.map { it.getValue(YourClass::class.java)!! }
Log.d("TAG", "Value is: $list")
}
In my case it was simply that I had a variable named the same as a function.
Example:
def cleanCache = functionReturningABoolean()
if( cleanCache ){
echo "Clean cache option is true, do not uninstall previous features / urls"
uninstallCmd = ""
// and we call the cleanCache method
cleanCache(userId, serverName)
}
...
and later in my code I have the function:
def cleanCache(user, server){
//some operations to the server
}
Apparently the Groovy language does not support this (but other languages like Java does).
I just renamed my function to executeCleanCache
and it works perfectly (or you can also rename your variable whatever option you prefer).
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
Thanks for the earlier reply.
I figured out the solutions using selenium 2.0 classes.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebTableExample
{
public static void main(String[] args)
{
WebDriver driver = new InternetExplorerDriver();
driver.get("http://localhost/test/test.html");
WebElement table_element = driver.findElement(By.id("testTable"));
List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
int row_num,col_num;
row_num=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
for(WebElement tdElement : td_collection)
{
System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.
2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.
One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install
, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.
This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.
So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.
What if you wanna update? Then in your dev environment run: composer update
, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.
3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.
While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.
Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;
public Get_Client_Repository()
: this(new CISOnlineSRVDEV.ServiceSoapClient())
{
}
public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
{
_ServiceSoapClient = serviceSoapClient;
}
public IEnumerable<IClient> GetClient(IClient client)
{
// **** Calling teh web service with passing in the clientId and returning a dataset
DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
client.ClientId,
client.AhcccsId,
client.LastName,
client.FirstName,
"");//client.BirthDate.ToString()); //TODO: NEED TO FIX
// USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
select new Client()
{
RbhaId = c[5].ToString(),
ClientId = c[2].ToString(),
AhcccsId = c[6].ToString(),
LastName = c[0].ToString(), // Add another field called Sex M/F c[4]
FirstName = c[1].ToString(),
BirthDate = c[3].ToDateTime() //extension helper ToDateTime()
}).ToList<IClient>();
return clients;
}
Then in the Controller I'm doing this
IClient client = (IClient)TempData["Client"];
// Instantiate and instance of the repository
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);
// Call the View up passing in the data from the list
return View(model);
Then in the View it is easy :
@model IEnumerable<CISOnlineMVC.DAL.IClient>
@{
ViewBag.Title = "CLIENT ALL INFORMATION";
}
<h2>CLIENT ALL INFORMATION</h2>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Client ID</th>
<th>DOB</th>
<th>Gender</th>
<th>RBHA ID</th>
<th>AHCCCS ID</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
</td>
<td>
@item.LastName
</td>
<td>
@item.FirstName
</td>
<td>
@item.ClientId
</td>
<td>
@item.BirthDate
</td>
<td>
Gender @* ADD in*@
</td>
<td>
@item.RbhaId
</td>
<td>
@item.AhcccsId
</td>
</tr>
}
</table>
In the AndroidManifest.xml
:
<activity android:name="com.your.package.ActivityName"
android:windowSoftInputMode="stateHidden" />
or try
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)??;
Please check this also
Don't forget to use parenthesis if you use this function after an AND
parameter
Like this:
WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%')
You can also use ViewPager.SimpleOnPageChangeListener
instead of ViewPager.OnPageChangeListener
and override only those methods you want to use.
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// optional
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
// optional
@Override
public void onPageSelected(int position) { }
// optional
@Override
public void onPageScrollStateChanged(int state) { }
});
Hope this help :)
Edit:
As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener)
is deprecated. Please check this url:- Android ViewPager API
If it is in the same class it is fine to trust the method.
It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.
It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.
Was the Tomcat running before you restarted it? Was there any other app listening on this port?
The exception is thrown because there was nobody listening on the command port (see <Server port="..."
in $tomcat_home/conf/server.xml
).
set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause
We should really stop advising the use of sudo
with pip install
. It's better to first try pip install --user
. If this fails then take a look at the top post here.
The reason you shouldn't use sudo
is as follows:
When you run pip with sudo
, you are running arbitrary Python code from the Internet as a root user, which is quite a big security risk. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine.
this works
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(soapResponse.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
System.out.println(sw.toString());
return sw.toString();
As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl
to tls
:
$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "[email protected]";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
When using tls
there's no need to grant access for less secure applications, just make sure, IMAP is enabled.
You need to add logic to assign random values to double[] array using randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray;
}
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray;
}
Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.
public static void main(String args[]) {
list();
print();
}
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7
Here's some code based on RFC 4122, section 4.4 (Algorithms for Creating a UUID from Truly Random or Pseudo-Random Number).
function createUUID() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
cout << "Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
cout << "Triangle area: " << Tri.getArea() << endl;
return 0;
}
Result: Rectangle area: 35 Triangle area: 17
We have seen how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.
I did not find any of the answers satisfactory. All the mentioned libraries have some problem or the other like Cairo dropping support for python 3.6 (they dropped Python 2 support some 3 years ago!). Also, installing the mentioned libraries on the Mac was a pain.
Finally, I found the best solution was svglib + reportlab. Both installed without a hitch using pip and first call to convert from svg to png worked beautifully! Very happy with the solution.
Just 2 commands do the trick:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
drawing = svg2rlg("my.svg")
renderPM.drawToFile(drawing, "my.png", fmt="PNG")
Are there any limitations with these I should be aware of?
from the terminal type:-
aws configure
then fill in your keys and region.
after this do next step use any environment. You can have multiple keys depending your account. Can manage multiple enviroment or keys
import boto3
aws_session = boto3.Session(profile_name="prod")
# Create an S3 client
s3 = aws_session.client('s3')
When you parse the JSON representation, it'll become a JavaScript array of objects.
Because of this, you can use the .length
property of the JavaScript array to see how many elements are contained, and use a for
loop to enumerate it.
You can actually accomplish this without JavaScript, using only JSF's rendered
attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:
<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
<f:selectItem itemValue="O" itemLabel="Originator" />
<f:selectItem itemValue="R" itemLabel="Role" />
<f:selectItem itemValue="E" itemLabel="Employee" />
<f:ajax event="change" execute="@this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
<h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
rendered="#{workflowProcEditBean.performedBy eq 'R'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.roles}" />
</h:selectOneMenu>
<h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
rendered="#{workflowProcEditBean.performedBy eq 'E'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.employees}" />
</h:selectOneMenu>
</h:panelGroup>
This is an old question, but if you have a non contiguous enum use a dictionary literal instead of an array:
typedef enum {
value1 = 0,
value2 = 1,
value3 = 2,
// beyond value3
value1000 = 1000,
value1001
} MyType;
#define NSStringFromMyType( value ) \
( \
@{ \
@( value1 ) : @"value1", \
@( value2 ) : @"value2", \
@( value3 ) : @"value3", \
@( value1000 ) : @"value1000", \
@( value1001 ) : @"value1001", \
} \
[ @( value ) ] \
)
In general, you can't do this in any straightforward fashion. time_point
is essentially just a duration
from a clock-specific epoch.
If you have a std::chrono::system_clock::time_point
, then you can use std::chrono::system_clock::to_time_t
to convert the time_point
to a time_t
, and then use the normal C functions such as ctime
or strftime
to format it.
Example code:
std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(tp);
std::tm timetm = *std::localtime(&time);
std::cout << "output : " << std::put_time(&timetm, "%c %Z") << "+"
<< std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch()).count() % 1000 << std::endl;
Is it not just a case of applying an appropriate class to each div?
For example:
.firstRowDiv { margin:0px 10px 10px 0px; }
.secondRowDiv { margin:0px 10px 0px 0px; }
This depends on if you know in advance which div to apply which class to.
Here is the really great article/differences provided by Amazon
Redis is a clear winner comparing with memcached.
Only one plus point for Memcached It is multithreaded and fast. Redis has lots of great features and is very fast, but limited to one core.
Great points about Redis, which are not supported in Memcached
i use $.each of jquery but you can make it with a for loop, an improvement is this:
//.ArraySort(array)
/* Sort an array
*/
ArraySort = function(array, sortFunc){
var tmp = [];
var aSorted=[];
var oSorted={};
for (var k in array) {
if (array.hasOwnProperty(k))
tmp.push({key: k, value: array[k]});
}
tmp.sort(function(o1, o2) {
return sortFunc(o1.value, o2.value);
});
if(Object.prototype.toString.call(array) === '[object Array]'){
$.each(tmp, function(index, value){
aSorted.push(value.value);
});
return aSorted;
}
if(Object.prototype.toString.call(array) === '[object Object]'){
$.each(tmp, function(index, value){
oSorted[value.key]=value.value;
});
return oSorted;
}
};
So now you can do
console.log("ArraySort");
var arr1 = [4,3,6,1,2,8,5,9,9];
var arr2 = {'a':4, 'b':3, 'c':6, 'd':1, 'e':2, 'f':8, 'g':5, 'h':9};
var arr3 = {a: 'green', b: 'brown', c: 'blue', d: 'red'};
var result1 = ArraySort(arr1, function(a,b){return a-b});
var result2 = ArraySort(arr2, function(a,b){return a-b});
var result3 = ArraySort(arr3, function(a,b){return a>b});
console.log(result1);
console.log(result2);
console.log(result3);
To checkout the branch via Jenkins scripts use:
stage('Checkout SCM') {
git branch: 'branchName', credentialsId: 'your_credentials', url: "giturlrepo"
}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.
Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart
.
I have solved it by fixing, the Alignment issue inside the same .yml file.
If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.
Now i am doing well.
Apart from the above answers, we can use asn1parse
to get the values
$ openssl asn1parse -i -in pub0.der -inform DER -offset 24
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :C9131430CCE9C42F659623BDC73A783029A23E4BA3FAF74FE3CF452F9DA9DAF29D6F46556E423FB02610BC4F84E19F87333EAD0BB3B390A3EFA7FB392E935065D80A27589A21CA051FA226195216D8A39F151BD0334965551744566AD3DAEB53EBA27783AE08BAAACA406C27ED8BE614518C8CD7D14BBE7AFEBE1D8D03374DAE7B7564CF1182A7B3BA115CD9416AB899C5803388EE66FA3676750A77AC870EDA027DC95E57B9B4E864A3C98F1BA99A4726C085178EA8FC6C549BE5EDF970CCB8D8F9AEDEE3F5CFDE574327D05ED04060B2525FB6711F1D78254FF59089199892A9ECC7D4E4950E0CD2246E1E613889722D73DB56B24E57F3943E11520776BC4F
265:d=1 hl=2 l= 3 prim: INTEGER :010001
Now, to get to this offset,we try the default asn1parse
$ openssl asn1parse -i -in pub0.der -inform DER
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING
We need to get to the BIT String part, so we add the sizes
depth_0_header(4) + depth_1_full_size(2 + 13) + Container_1_EOC_bit + BIT_STRING_header(4) = 24
This can be better visialized at: ASN.1 Parser, if you hover at tags, you will see the offsets
Another amazing resource: Microsoft's ASN.1 Docs
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
Another way of getting the results
SELECT * from table WHERE SUBSTRING(tester, 1, 8) <> 'username' or tester is null
I think this link will do your homework: http://ootips.org/uml-hasa.html
To understand the terms I remember an example in my early programming days:
If you have a 'chess board' object that contains 'box' objects that is composition because if the 'chess board' is deleted there is no reason for the boxes to exist anymore.
If you have a 'square' object that have a 'color' object and the square gets deleted the 'color' object may still exist, that is aggregation
Both of them are associations, the main difference is conceptual
You can try the following method(python3.6.2):
case one:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
response = make_response('<h1>hello world</h1>',301)
response.headers = headers
return response
case two:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
return '<h1>hello world</h1>',301,headers
I am using Flask .And if you want to return json,you can write this:
import json #
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return json.dumps(result),200,{'content-type':'application/json'}
from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return jsonify(result)
The only place it worked for me is when I place the scripts in public
folder where my index.html
resides and then placing these <script type="text/javascript" src="test/test.js"></script>
inside <body>
tag.
Use simple
ssh-keyscan hostname
to find if key(s) exists on both sites:
ssh-keyscan rc1.localdomain
[or@rc2 ~]$ ssh-keyscan rc1
# rc1 SSH-2.0-OpenSSH_5.3
rc1 ssh-rsa AAAAB3NzaC1yc2EAAAABI.......==
ssh-keyscan rc2.localdomain
[or@rc2 ~]$ ssh-keyscan rc2
# rac2 SSH-2.0-OpenSSH_5.3
rac2 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAys7kG6pNiC.......==
Mocking is an option here, although it would be hard, because loggers are generally private static final - so setting a mock logger wouldn't be a piece of cake, or would require modification of the class under test.
You can create a custom Appender (or whatever it's called), and register it - either via a test-only configuration file, or runtime (in a way, dependent on the logging framework). And then you can get that appender (either statically, if declared in configuration file, or by its current reference, if you are plugging it runtime), and verify its contents.
Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
For CentOS, run this:
sudo yum install libXext libSM libXrender
myList.ToList().Count == 0
. That's all
$('#navigation ul li').css({'display' : 'inline-block'});
It seems a typo there ...syntax mistake :))
Using Apache Commons IO.
import org.apache.commons.io.FileUtils;
//...
String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")
You can see de javadoc for the method for details.
If you change your time
column into row names, then you can use as.data.frame(as.table(mat))
for simple cases like this.
Example:
data <- c(0.1, 0.2, 0.3, 0.3, 0.4, 0.5)
dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
as.data.frame(as.table(mat))
time name Freq
1 0 C_0 0.1
2 0.5 C_0 0.2
3 1 C_0 0.3
4 0 C_1 0.3
5 0.5 C_1 0.4
6 1 C_1 0.5
In this case time and name are both factors. You may want to convert time back to numeric, or it may not matter.
windows cmd: This would work if you have all te jars in the same directory and execute the below command
for /r %i in (*) do ( jar tvf %i | find /I "search_string")
The solution is to change the DropDownStyle property to DropDownList. It will help.
Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:
Suppose you had a PL/SQL procedure like this to check for the existence of a location record:
PROCEDURE chk_location_exists
(
p_location_id IN location.gie_location_id%TYPE
)
AS
l_cnt INTEGER := 0;
BEGIN
SELECT COUNT(*)
INTO l_cnt
FROM location
WHERE gie_location_id = p_location_id;
IF l_cnt = 0
THEN
raise_application_error(
gc_entity_not_found,
'The associated location record could not be found.');
END IF;
END;
The raise_application_error allows you to raise a specific error code. In your package header, you can define:
gc_entity_not_found INTEGER := -20001;
If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.
Then on the client side, you can do something like this (this example is for C#):
/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;
And you can execute your code in a try/catch
try
{
// call the chk_location_exists SP
}
catch (Exception e)
{
if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
{
// create an EntityNotFoundException with message indicating that entity was not found in
// database; use the message of the OracleException, which will indicate the table corresponding
// to the entity which wasn't found and also the exact line in the PL/SQL code where the application
// error was raised
return new EntityNotFoundException(
"A required entity was not found in the database: " + e.Message);
}
}
Clean your project Remove the /obj folder (probably using publish and deploy? - there is a bug in it)
If you are using security annotation from the SensioFrameworkExtraBundle
, you can use a few expressions (that are defined in \Symfony\Component\Security\Core\Authorization\ExpressionLanguageProvider
):
@Security("is_authenticated()")
: to check that the user is authed and not anonymous@Security("is_anonymous()")
: to check if the current user is the anonymous user@Security("is_fully_authenticated()")
: equivalent to is_granted('IS_AUTHENTICATED_FULLY')
@Security("is_remember_me()")
: equivalent to is_granted('IS_AUTHENTICATED_REMEMBERED')
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
A more intuitive explanation would be :-
The square root of 100 is 10. Let's say a x b = 100, for various pairs of a and b.
If a == b, then they are equal, and are the square root of 100, exactly. Which is 10.
If one of them is less than 10, the other has to be greater. For example, 5 x 20 == 100. One is greater than 10, the other is less than 10.
Thinking about a x b, if one of them goes down, the other must get bigger to compensate, so the product stays at 100. They pivot around the square root.
The square root of 101 is about 10.049875621. So if you're testing the number 101 for primality, you only need to try the integers up through 10, including 10. But 8, 9, and 10 are not themselves prime, so you only have to test up through 7, which is prime.
Because if there's a pair of factors with one of the numbers bigger than 10, the other of the pair has to be less than 10. If the smaller one doesn't exist, there is no matching larger factor of 101.
If you're testing 121, the square root is 11. You have to test the prime integers 1 through 11 (inclusive) to see if it goes in evenly. 11 goes in 11 times, so 121 is not prime. If you had stopped at 10, and not tested 11, you would have missed 11.
You have to test every prime integer greater than 2, but less than or equal to the square root, assuming you are only testing odd numbers.
`
ctrl + w, w as mentioned can be used for navigating from pane to pane.
Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1
Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.
Use visual mode and then change it
1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require
You can add timeout function in jQuery (Show alert after 3 seconds):
$(document).ready(function($) {
setTimeout(function() {
alert("Hello");
}, 3000);
});
From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Erasing state when props change is an Anti Pattern
Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use
ParentComponent
of the ModalBody
will own the start_time
state. This is not my prefer approach in this case since i think the modal should own this state. start_time
state from your ModalBody
and use getInitialState
just like you have already done. To reset the start_time
state, you simply change the key from the ParentComponent
DateTime.FromFileTime
should do the trick:
PS C:\> [datetime]::FromFileTime(129948127853609000)
Monday, October 15, 2012 3:13:05 PM
Then depending on how you want to format it, check out standard and custom datetime format strings.
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM
If you want to integrate this into your one-liner, change your select
statement to this:
... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...
In v 5.8.38, I set the env file as the following:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=difficultCombination
MAIL_ENCRYPTION=ssl
MAIL_FROM_NAME=myWebappName
After doing php artisan config:clear
, it worked well on a shard server.
If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.
Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.
For Mac,
login to mysql server.
execute the following command:
SHOW VARIABLES LIKE "%version%";
I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).
However, I don't know how to change from local variables to global..
FindBugs also puts a red-x against files/packages to indicate static code analysis errors.
The other answers here are correct: Yes, your Ruby app (not your Ruby gem) should include Gemfile.lock
in the repo. To expand on why it should do this, read on:
I was under the mistaken notion that each env (development, test, staging, prod...) each did a bundle install
to build their own Gemfile.lock. My assumption was based on the fact that Gemfile.lock does not contain any grouping data, such as :test, :prod, etc. This assumption was wrong, as I found out in a painful local problem.
Upon closer investigation, I was confused why my Jenkins build showed fetching a particular gem (ffaker
, FWIW) successfully, but when the app loaded and required ffaker, it said file not found. WTF?
A little more investigation and experimenting showed what the two files do:
First it uses Gemfile.lock to go fetch all the gems, even those that won't be used in this particular env. Then it uses Gemfile to choose which of those fetched gems to actually use in this env.
So, even though it fetched the gem in the first step based on Gemfile.lock, it did NOT include in my :test environment, based on the groups in Gemfile.
The fix (in my case) was to move gem 'ffaker'
from the :development group to the main group, so all env's could use it. (Or, add it only to :development, :test, as appropriate)
I normally use another way to do the same
using System.Xml;
using System.Net;
using System.IO;
public static void CallWebService()
{
var _url = "http://xxxxxxxxx/Service1.asmx";
var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(
@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
<SOAP-ENV:Body>
<HelloWorld xmlns=""http://tempuri.org/""
SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<int1 xsi:type=""xsd:integer"">12</int1>
<int2 xsi:type=""xsd:integer"">32</int2>
</HelloWorld>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
Using Array.prototype.map()
const zip = (a, b) => a.map((k, i) => [k, b[i]]);
console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
Using Array.from()
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);
console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
Using Array.prototype.fill() and Array.prototype.map()
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);
console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/
Code here: https://github.com/logicbomb/lvlDragDrop
Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html
Here are the directives these rely on a UUID service which I've included below:
var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);
module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
return {
restrict: 'A',
link: function(scope, el, attrs, controller) {
console.log("linking draggable element");
angular.element(el).attr("draggable", "true");
var id = attrs.id;
if (!attrs.id) {
id = uuid.new()
angular.element(el).attr("id", id);
}
el.bind("dragstart", function(e) {
e.dataTransfer.setData('text', id);
$rootScope.$emit("LVL-DRAG-START");
});
el.bind("dragend", function(e) {
$rootScope.$emit("LVL-DRAG-END");
});
}
}
}]);
module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
return {
restrict: 'A',
scope: {
onDrop: '&'
},
link: function(scope, el, attrs, controller) {
var id = attrs.id;
if (!attrs.id) {
id = uuid.new()
angular.element(el).attr("id", id);
}
el.bind("dragover", function(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
});
el.bind("dragenter", function(e) {
// this / e.target is the current hover target.
angular.element(e.target).addClass('lvl-over');
});
el.bind("dragleave", function(e) {
angular.element(e.target).removeClass('lvl-over'); // this / e.target is previous target element.
});
el.bind("drop", function(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation(); // Necessary. Allows us to drop.
}
var data = e.dataTransfer.getData("text");
var dest = document.getElementById(id);
var src = document.getElementById(data);
scope.onDrop({dragEl: src, dropEl: dest});
});
$rootScope.$on("LVL-DRAG-START", function() {
var el = document.getElementById(id);
angular.element(el).addClass("lvl-target");
});
$rootScope.$on("LVL-DRAG-END", function() {
var el = document.getElementById(id);
angular.element(el).removeClass("lvl-target");
angular.element(el).removeClass("lvl-over");
});
}
}
}]);
UUID service
angular
.module('lvl.services',[])
.factory('uuid', function() {
var svc = {
new: function() {
function _p8(s) {
var p = (Math.random().toString(16)+"000000000").substr(2,8);
return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
}
return _p8() + _p8(true) + _p8(true) + _p8();
},
empty: function() {
return '00000000-0000-0000-0000-000000000000';
}
};
return svc;
});
How about
(from k in myList
where k.id > 35
select k).ToList().ForEach(k => k.Name = "Banana");
You can use default_scope to implement a default sort order http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
With reference to man ssh-keygen
, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.
In conclusion, a 2048 bit RSA key is currently the best choice.
Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.
To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.
Best way to achieve is to use a LinkedHashMap that maintains insertion order of elements. Following is an sample code:
public class Solution {
Map<Integer,Integer> cache;
int capacity;
public Solution(int capacity) {
this.cache = new LinkedHashMap<Integer,Integer>(capacity);
this.capacity = capacity;
}
// This function returns false if key is not
// present in cache. Else it moves the key to
// front by first removing it and then adding
// it, and returns true.
public int get(int key) {
if (!cache.containsKey(key))
return -1;
int value = cache.get(key);
cache.remove(key);
cache.put(key,value);
return cache.get(key);
}
public void set(int key, int value) {
// If already present, then
// remove it first we are going to add later
if(cache.containsKey(key)){
cache.remove(key);
}
// If cache size is full, remove the least
// recently used.
else if (cache.size() == capacity) {
Iterator<Integer> iterator = cache.keySet().iterator();
cache.remove(iterator.next());
}
cache.put(key,value);
}
}
One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py
file:
app = Flask(__name__, static_folder="your path to static")
Otherwise flask will not be able to detect static folder.
In your case, the error is that you're trying to generate an Error
instance. Error
in Swift 3 is a protocol that can be used to define a custom error. This feature is especially for pure Swift applications to run on different OS.
In iOS development the NSError
class is still available and it conforms to Error
protocol.
So, if your purpose is only to propagate this error code, you can easily replace
var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)
with
var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)
Otherwise check the Sandeep Bhandari's answer regarding how to create a custom error type
The following function will quickly (no sorting required) group tuples of any length by a key having any index:
# given a sequence of tuples like [(3,'c',6),(7,'a',2),(88,'c',4),(45,'a',0)],
# returns a dict grouping tuples by idx-th element - with idx=1 we have:
# if merge is True {'c':(3,6,88,4), 'a':(7,2,45,0)}
# if merge is False {'c':((3,6),(88,4)), 'a':((7,2),(45,0))}
def group_by(seqs,idx=0,merge=True):
d = dict()
for seq in seqs:
k = seq[idx]
v = d.get(k,tuple()) + (seq[:idx]+seq[idx+1:] if merge else (seq[:idx]+seq[idx+1:],))
d.update({k:v})
return d
In the case of your question, the index of key you want to group by is 1, therefore:
group_by(input,1)
gives
{'ETH': ('5238761','5349618','962142','7795297','7341464','5594916','1550003'),
'KAT': ('11013331', '9843236'),
'NOT': ('9085267', '11788544')}
which is not exactly the output you asked for, but might as well suit your needs.
Use the following code:
function hide {
document.getElementById('div').style.display = "none";
}
function show {
document.getElementById('div').style.display = "block";
}
Success!
After checking the log files and making sure the permissions on php_openssl.dll were correct, I googled the warning and found more things to try.
So I:
I'm not sure which of these fixed my problem, but it's definately fixed now! :)
I found these things to try on this page: http://php.net/manual/en/install.windows.extensions.php
Thanks for your help!
One big difference with python 3.4 + pycharm is that the dict() constructor produces a "syntax error" message if the number of keys exceeds 256.
I prefer using the dict literal now.
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
File > Workspace Settings > Build System > Legacy Build System
This worked for me. Xcode 10.0
There are two semantically correct solutions to this question:
I've tried a couple of plugins doing this and my favourite is jekyll-figure
.
jekyll-figure
One way to install jekyll-figure
is to add gem "jekyll-figure"
to your Gemfile in your plugins group.
Then run bundle install
from your terminal window.
jekyll-figure
Simply wrap your markdown in {% figure %}
and {% endfigure %}
tags.
You caption goes in the opening {% figure %}
tag, and you can even style it with markdown!
Example:
{% figure caption:"Le logo de **Jekyll** et son clin d'oeil à Robert Louis Stevenson" %}
![Le logo de Jekyll](/assets/images/2018-08-07-jekyll-logo.png)
{% endfigure %}
Now that your images and captions are semantically correct, you can apply CSS as you wish to:
figure
(for both image and caption)figure img
(for image only)figcaption
(for caption only)You'll need to create an image.html
file in your _includes
folder, and include it using Liquid in Markdown.
Create the image.html
document in your _includes folder :
<!-- _includes/image.html -->
<figure>
{% if include.url %}
<a href="{{ include.url }}">
{% endif %}
<img
{% if include.srcabs %}
src="{{ include.srcabs }}"
{% else %}
src="{{ site.baseurl }}/assets/images/{{ include.src }}"
{% endif %}
alt="{{ include.alt }}">
{% if include.url %}
</a>
{% endif %}
{% if include.caption %}
<figcaption>{{ include.caption }}</figcaption>
{% endif %}
</figure>
An image in /assets/images
with a caption:
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="jekyll-logo.png" <!-- image filename (placed in /assets/images) -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
An (external) image using an absolute URL: (change src=""
to srcabs=""
)
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
srcabs="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
A clickable image: (add url=""
argument)
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
url="https://jekyllrb.com" <!-- destination url -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
An image without a caption:
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
alt="Jekyll's logo" <!-- alt text -->
%}
Now that your images and captions are semantically correct, you can apply CSS as you wish to:
figure
(for both image and caption)figure img
(for image only)figcaption
(for caption only)If you would need to escape special characters like '_' (underscore), as it was in my case, and you are not willing/not able to define an ESCAPE clause, you may wish to enclose the special character with square brackets '[' and ']'.
This explains the meaning of the "weird" string '[[]' - it just embraces the '[' character with square brackets, effectively escaping it.
My use case was to specify the name of a stored procedure with underscores in it as a filter criteria for the Profiler. So I've put string '%name[_]of[_]a[_]stored[_]procedure%' in a TextData LIKE field and it gave me trace results I wanted to achieve.
Here is a good example from the documentation: LIKE (Transact-SQL) - Using Wildcard Characters As Literals
If you want the container to be started even if no user has performed a login (like the VirtualBox VM that I only start and don't want to login each time). Here are the steps I performed to for Ubuntu 16.04 LTS. As an example, I installed a oracle db container:
$ docker pull alexeiled/docker-oracle-xe-11g
$ docker run -d --name=MYPROJECT_oracle_db --shm-size=2g -p 1521:1521 -p 8080:8080 alexeiled/docker-oracle-xe-11g
$ vim /etc/systemd/system/docker-MYPROJECT-oracle_db.service
and add the following content:
[Unit]
Description=Redis container
Requires=docker.service
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker start -a MYPROJECT_oracle_db
ExecStop=/usr/bin/docker stop -t 2 MYPROJECT_oracle_db
[Install]
WantedBy=default.target
and enable the service at startup
sudo systemctl enable docker-MYPROJECT-oracle_db.service
For more informations https://docs.docker.com/engine/admin/host_integration/
For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I'm using 'call
' command instead of 'start
' in my batch files. My startWLS.cmd file then looks like:
call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd
After Ctrl+C(and 'Y' answer) cmd window is automatically closed.
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
Here is a simple solution in c# using recursion,
void Main()
{
string word = "abc";
WordPermuatation("",word);
}
void WordPermuatation(string prefix, string word)
{
int n = word.Length;
if (n == 0) { Console.WriteLine(prefix); }
else
{
for (int i = 0; i < n; i++)
{
WordPermuatation(prefix + word[i],word.Substring(0, i) + word.Substring(i + 1, n - (i+1)));
}
}
}
Since at least Spring 3, instead of using UriComponentsBuilder
to build the URL (which is a bit verbose), many of the RestTemplate
methods accept placeholders in the path for parameters (not just exchange
).
From the documentation:
Many of the
RestTemplate
methods accepts a URI template and URI template variables, either as aString
vararg, or asMap<String,String>
.For example with a
String
vararg:restTemplate.getForObject( "http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");
Or with a
Map<String, String>
:Map<String, String> vars = new HashMap<>(); vars.put("hotel", "42"); vars.put("room", "21"); restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}", String.class, vars);
If you look at the JavaDoc for RestTemplate
and search for "URI Template", you can see which methods you can use placeholders with.
This is my sample code for load static variable
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OnelinkConfig {
public static int MODULE_CODE;
public static int DEFAULT_PAGE;
public static int DEFAULT_SIZE;
@Autowired
public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
@Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
MODULE_CODE = code;
DEFAULT_PAGE = page;
DEFAULT_SIZE = size;
}
}
This may have been answered before: Python URLLib / URLLib2 POST.
Your server is likely performing a 302 redirect from http://myserver/post_service
to http://myserver/post_service/
. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url
to http://myserver/post_service/
.
Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {
$('table').each(function() {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to CSV");
$button.insertAfter($table);
$button.click(function() {
CSV.begin('table').download('Export.csv').go();
});
});
})
</script>
</head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
</body>
</html>
You can use this for check modify date of functions
and stored procedures
together ordered by date :
SELECT 'Stored procedure' as [Type] ,name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
UNION all
Select 'Function' as [Type],name, create_date, modify_date
FROM sys.objects
WHERE type = 'FN'
ORDER BY modify_date DESC
or :
SELECT type ,name, create_date, modify_date
FROM sys.objects
WHERE type in('P','FN')
ORDER BY modify_date DESC
-- this one shows type like : FN for function and P for stored procedure
Result will be like this :
Type | name | create_date | modify_date
'Stored procedure' | 'firstSp' | 2018-08-04 07:36:40.890 | 2019-09-05 05:18:53.157
'Stored procedure' | 'secondSp' | 2017-10-15 19:39:27.950 | 2019-09-05 05:15:14.963
'Function' | 'firstFn' | 2019-09-05 05:08:53.707 | 2019-09-05 05:08:53.707
The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.
Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.
I think the best first approach is to make sure to turn on detailed error messages via your web.config file, like this:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed"></httpErrors>
</system.webServer>
</configuration>
After doing this, you should get a more detailed error message from the server.
In my particular case, the more detailed error pointed out that my <defaultDocument>
section of the web.config file was not allowed at the folder level where I'd placed my web.config. It said
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "
I'm not seeing it here, so I'd like to add that on Debian/Ubuntu you may need to enable the extension after installing the relative package. So:
sudo apt-get install php-zip
sudo phpenmod zip
sudo service apache2 restart
you can stop using the shutdown.bat inside tomcat installation directory. Or you may click "stop" button at the servers view of eclipse. To get to the view select Window - Show View - Servers
Some time when we use Environ()
function we may get the Library or property not found error. Use VBA.Environ()
or VBA.Environ$()
to avoid the error.
If you want to add dynamically buttons try this:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 1; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText(" ");
layout.addView(btn);
}
}
<table>
<tbody>
<tr><td>{{data[0].foo}}</td></tr>
<tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
<tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
</tbody>
</table>
I think that this is valid :)
In your html file you write:
<div class="banner">
Center content
</div>
your css file you write:
.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}
works for me.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
First of all you should know the difference between a virtual and abstract method.
(see detailed explanation here)
$text = Get-Content $filePath | Out-String
The IO.File.ReadAllText
didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath
instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)
$text = Get-Content $filePath -Raw