The other answers here provide the bits in big-endian order ('\x01'
becomes '00000001'
)
In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:
def bits_little_endian_from_bytes(s):
return ''.join(bin(ord(x))[2:].rjust(8,'0')[::-1] for x in s)
And for the other direction:
def bytes_from_bits_little_endian(s):
return ''.join(chr(int(s[i:i+8][::-1], 2)) for i in range(0, len(s), 8))
A better way to solve it is to start small.
Let's start with 1 bit. Which can either be 1
or 0
. That's 2 values, or 10
in binary.
Now 2 bits, which can either be 00
, 01
, 10
or 11
That's 4 values, or 100
in binary... See the pattern?
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
window.location.reload() or just location.reload()
My favorite version is the inline version:
${"variableName"} = 12;
$className->{"propertyName"};
$className->{"methodName"}();
StaticClass::${"propertyName"};
StaticClass::{"methodName"}();
You can place variables or expressions inside the brackets too!
Here are the links for Windows, Mac and Linux. Latest revision of 18.x, 17.x, 16.x, 15.x, 14.x, 13.x, 12.x, 11.x, 10.x, 9.x, 8.x and 7.x versions.
Update: Download Latest and Old NDK releases from Android official site.
Android NDK, Revision 18b (January 2019)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 17c (June 2018)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 16b (December 2017)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 15c (July 2017)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 14b (March 2017)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 13b (October 2016)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 12b (June 2016)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 11c (March 2016)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK, Revision 10e (May 2015)
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK r9d
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK r8e
Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit
Android NDK r7c
I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint
Server:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
Client
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
it also have all the needed information for simple client/server applications.
Just convert the server and use some simple protocol to call a function from python.
P.S: i'm sure there are a lot of better options, it's just a simple one if you want...
If you are getting this error on Python 2.7 you can now get the Microsoft Visual C++ Compiler for Python 2.7 as a stand alone download.
If you are on 3.3 or later you need to install Visual Studio 2010 express which is available for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express
If you are 3.3 or later and using a 64 bit version of python you need to install the Microsoft SDK 7.1 that ships a 64 bit compiler and follow the directions here Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
Just add background-attachment to your code
body {
background-position: center;
background-image: url(../images/images5.jpg);
background-attachment: fixed;
}
Actually, there are some situations which the throw
statment will not preserve the StackTrace information. For example, in the code below:
try
{
int i = 0;
int j = 12 / i; // Line 47
int k = j + 1;
}
catch
{
// do something
// ...
throw; // Line 54
}
The StackTrace will indicate that line 54 raised the exception, although it was raised at line 47.
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
at Program.WithThrowIncomplete() in Program.cs:line 54
at Program.Main(String[] args) in Program.cs:line 106
In situations like the one described above, there are two options to preseve the original StackTrace:
Calling the Exception.InternalPreserveStackTrace
As it is a private method, it has to be invoked by using reflection:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
I has a disadvantage of relying on a private method to preserve the StackTrace information. It can be changed in future versions of .NET Framework. The code example above and proposed solution below was extracted from Fabrice MARGUERIE weblog.
Calling Exception.SetObjectData
The technique below was suggested by Anton Tykhyy as answer to In C#, how can I rethrow InnerException without losing stack trace question.
static void PreserveStackTrace (Exception e)
{
var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ;
var mgr = new ObjectManager (null, ctx) ;
var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;
e.GetObjectData (si, ctx) ;
mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData
mgr.DoFixups () ; // ObjectManager calls SetObjectData
// voila, e is unmodified save for _remoteStackTraceString
}
Although, it has the advantage of relying in public methods only it also depends on the following exception constructor (which some exceptions developed by 3rd parties do not implement):
protected Exception(
SerializationInfo info,
StreamingContext context
)
In my situation, I had to choose the first approach, because the exceptions raised by a 3rd-party library I was using didn't implement this constructor.
restart was not enough! The only way to solve the problem is by the following:
You have to kill the service which run at that port.
at cmd, run as admin, then type :
netstat -aon | find /i "listening"
Then, you will get a list with the active service, search for the port that is running at 4200n and use the process id which is the last column to kill it by
: taskkill /F /PID 2652
I've done it this way in the past, JsFiddle:
CSS:
.radio-option {
cursor: pointer;
height: 23px;
width: 23px;
background: url(../images/checkbox2.png) no-repeat 0px 0px;
}
.radio-option.click {
background: url(../images/checkbox1.png) no-repeat 0px 0px;
}
HTML:
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
jQuery:
<script>
$(document).ready(function() {
$('.radio-option').click(function () {
$(this).not(this).removeClass('click');
$(this).toggleClass("click");
});
});
</script>
If you want the output to be
array([1.6e-01, 9.9e-01, 3.6e-04])
the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:
def my_round(value, N):
exponent = np.ceil(np.log10(value))
return 10**exponent*np.round(value*10**(-exponent), N)
For a general solution handling 0
and negative values as well, you can do something like this:
def my_round(value, N):
value = np.asarray(value).copy()
zero_mask = (value == 0)
value[zero_mask] = 1.0
sign_mask = (value < 0)
value[sign_mask] *= -1
exponent = np.ceil(np.log10(value))
result = 10**exponent*np.round(value*10**(-exponent), N)
result[sign_mask] *= -1
result[zero_mask] = 0.0
return result
Updated answer
Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing
property which is implemented with a prefix for each browser
-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
This means that the 2px difference we mentioned earlier does not exist..
example at http://www.jsfiddle.net/gaby/WaxTS/5/
note: On IE it works from version 8 and upwards..
Original
if you reset their borders then the select
element will always be 2 pixels less than the input
elements..
File
> Import
> General
> Existing Projects into workspace
.
Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish
. This should work just fine.
Try like
$('.printMe').click(function(){
window.print();
});
or if you want to print selected area try like
$('.printMe').click(function(){
$("#outprint").print();
});
http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php
SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.
Loading and playing a wav is simple (crude example):
http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php
#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();
Streaming an ogg music file is also simple:
#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
return -1; // error
music.play();
Traditionally, if you only want to change the variable in your terminal windows, set it in .bashrc
file, which is sourced each time a new terminal is opened. .profile
file is not sourced each time you open a new terminal.
See the difference between .profile and .bashrc in question: What's the difference between .bashrc, .bash_profile, and .environment?
.bashrc
should solve your problem. However, it is not the proper solution since you are using Ubuntu. See the relevant Ubuntu help page "Session-wide environment variables". Thus, no wonder that .profile
does not work for you. I use Ubuntu 12.04 and xfce. I set up my .profile
and it is simply not taking effect even if I log out and in. Similar experience here. So you may have to use .pam_environment
file and totally forget about .profile
, and .bashrc
. And NOTE that .pam_environment
is not a script file.
SET collation_connection = 'utf8_general_ci';
then for your databases
ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
MySQL sneaks swedish in there sometimes for no sensible reason.
You can edit your readme.md with instructions to install your laravel app in other environment like this:
## Create folders
```
#!terminal
cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache
```
## Folder permissions
```
#!terminal
sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R
```
## Install dependencies
```
#!terminal
composer install
```
What helped for me, was to put the following line in the ready function:
$(document).ready(function()
{
..
...
// codes works on all bootstrap modal windows in application
$('.modal').on('hidden.bs.modal', function(e)
{
$(this).removeData();
}) ;
...
..
});
When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.
I hope this will help you as well!
you want this?
employees.ForEach(emp =>
{
collection.AddRange(emp.Departments.Where(dept => { dept.SomeProperty = null; return true; }));
});
You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.
One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton
Alan Murta has a complete implementation of a polygon clipper GPC.
Edit:
Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.
PyParsing does a great job. The PyParsing wiki was killed so here is another location where there are examples of the use of PyParsing (example link). One reason for investing a little time with pyparsing is that he has also written a very brief very well organized O'Reilly Short Cut manual that is also inexpensive.
Having said that, I use BeautifulSoup a lot and it is not that hard to deal with the entities issues, you can convert them before you run BeautifulSoup.
Goodluck
@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:
public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}
The <prev>
-tag might be an XML-tag.
After close examining, not 300k lines but there are around 3-4 CSS properties that you need to override:
.navbar-collapse.collapse {
display: block!important;
}
.navbar-nav>li, .navbar-nav {
float: left !important;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px !important;
}
.navbar-right {
float: right!important;
}
And with this your menu won't collapse.
EXPLANATION
The four CSS properties do the respective:
The default .collapse
property in bootstrap hides the right-side of the menu for tablets(landscape) and phones and instead a toggle button is displayed to hide/show it. Thus this property overrides the default and persistently shows those elements.
For the right-side menu to appear on the same line along with the left-side, we need the left-side to be floating left.
This property is present by default in bootstrap but not on tablet(portrait) to phone resolution. You can skip this one, it's likely to not affect your overall navbar.
This keeps the right-side menu to the right while the inner elements (li
) will follow the property 2. So we have left-side float left and right-side float right which brings them into one line.
UPDATE: this is a bug in spring see here
the application properties outside of your jar must be in one of the following places, then everything should work.
21.2 Application property files
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdir of the current directory.
The current directory
A classpath /config package
The classpath root
so e.g. this should work, when you dont want to specify cmd line args and you dont use spring.config.location in your base app.props:
d:\yourExecutable.jar
d:\application.properties
or
d:\yourExecutable.jar
d:\config\application.properties
see spring external config doc
Update: you may use \@Configuration together with \@PropertySource. according to the doc here you can specify resources anywhere. you should just be careful, when which config is loaded to make sure your production one wins.
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
You'll need to scrape the resulting page, but you can view the most recent cache page using this URL:
http://webcache.googleusercontent.com/search?q=cache:www.something.com/path
Google information is put in the first div in the body tag.
Open Search Dialog Search-> Search...
or use Shortcut Ctrl + H.
I still go with the uppercase for const values, but this is more out of habit than for any particular reason.
Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb.
My conclusion: Go with the camel casing. Maybe I will change my style too ;-)
Edit:
That something smells hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?
There are cases when hungarian helps. Not that many nowadays, but they still exist.
check pyplot
docs. For completeness,
import numpy as np
import matplotlib.pyplot as plt
#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
How about this:
git log -1 $TAGNAME
OR
git log -1 origin/$TAGNAME
Try wrapping your dates in single quotes, like this:
'15-6-2005'
It should be able to parse the date this way.
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
.gitignore
is about ignoring other files. git is about files so this is about ignoring files. However as git works off files this file needs to be there as the mechanism to list the other file names.
If it were called .the_list_of_ignored_files
it might be a little more obvious.
An analogy is a list of to-do items that you do NOT want to do. Unless you list them somewhere is some sort of 'to-do' list you won't know about them.
You have to set a default value.
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';
... some work (set real values as you want)...
ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;
I have been through all the answers and tutorials over the internet but here are the basic steps to enable SSL (https) on localhost with XAMPP:
Run -> "C:\xampp\apache\makecert.bat" (double-click on windows) Fill passowords of your choice, hit Enter for everything BUT define "localhost"!!! Be careful when asked here:
Common Name (e.g. server FQDN or YOUR name) []:localhost
(Certificates are issued per domain name zone only!)
XAMPP -> Apache -> Config -> httpd.conf ("C:\xampp\apache\conf\httpd.conf")
LoadModule ssl_module modules/mod_ssl.so (remove # form the start of line)
XAMPP -> Apache -> Config -> php.ini ("C:\xampp\php\php.ini")
extension=php_openssl.dll (remove ; from the start of line)
Restart apache and chrome!
Check any problems or the status of your certificate:
Chrome -> F12 -> Security -> View Certificate
if you want to make color 50% transparent in kotlin,
val percentage = 50f/100 //50%
ColorUtils.setAlphaComponent(resources.getColor(R.color.whatEverColor), (percentage * 255).toInt())
Follow the following steps if you are using proxy server:
Hope this helps.
As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:
<p>Hello</p>
<p><?= _("World"); ?></p>
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
SELECT Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount,
Order_Details.TotalPrice
FROM Order_Products INNER JOIN
Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]
A call to EntityManager.flush();
will force the data to be persist in the database immediately as EntityManager.persist()
will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).
I try to avoid this check as much as possible.
Obviously doesn't need to be done for columns that can't hold null
.
If you're storing in a Nullable value type (int?
, etc.), you can just convert using as int?
.
If you don't need to differentiate between string.Empty
and null
, you can just call .ToString()
, since DBNull will return string.Empty
.
Now For AppCompatEditText
Note: We need to use app:backgroundTint instead of android:backgroundTint
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Underline color change"
app:backgroundTint="@color/blue_gray_light" />
The jQuery object has a selector property I saw when digging in its code yesterday. Don't know if it's defined in the docs are how reliable it is (for future proofing). But it works!
$('*').selector // returns *
Edit: If you were to find the selector inside the event, that information should ideally be part of the event itself and not the element because an element could have multiple click events assigned through various selectors. A solution would be to use a wrapper to around bind()
, click()
etc. to add events instead of adding it directly.
jQuery.fn.addEvent = function(type, handler) {
this.bind(type, {'selector': this.selector}, handler);
};
The selector is being passed as an object's property named selector
. Access it as event.data.selector
.
Let's try it on some markup (http://jsfiddle.net/DFh7z/):
<p class='info'>some text and <a>a link</a></p>?
$('p a').addEvent('click', function(event) {
alert(event.data.selector); // p a
});
Disclaimer: Remember that just as with live()
events, the selector property may be invalid if DOM traversal methods are used.
<div><a>a link</a></div>
The code below will NOT work, as live
relies on the selector property
which in this case is a.parent()
- an invalid selector.
$('a').parent().live(function() { alert('something'); });
Our addEvent
method will fire, but you too will see the wrong selector - a.parent()
.
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
PDF Hummus. see for http://pdfhummus.com/ - contains all required features for manipulation with PDF files except rendering.
I had some issues playing on Android Phone. After few tries I found out that when Data Saver is on there is no auto play:
There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.
See adeneo's answer, but don't forget encodeURIComponent
!
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvString);
Also, I needed to do "\r\n" not just "\n" for the row delimiter.
var csvString = csvRows.join("\r\n");
Revised fiddle: http://jsfiddle.net/7Q3c6/
its kind of hacky but it works well-ish
function close_frame(){
if(!window.should_close){
window.should_close=1;
}else if(window.should_close==1){
location.reload();
//or iframe hide or whatever
}
}
<iframe src="iframe_index.php" onload="close_frame()"></iframe>
then inside the frame
$('#close_modal_main').click(function(){
window.location = 'iframe_index.php?close=1';
});
and if you want to get fancy through a
if(isset($_GET['close'])){
die;
}
at the top of your frame page to make that reload unnoticeable
so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close
You can probably make a clever use of the DebugBreak() function.
You should delete the file: c:\users\_user_name_\.android\adbkey
a=[]
def showmatrix (a,m,n):
for i in range (m):
for j in range (n):
k=int(input("enter the number")
a.append(k)
print (a[i][j]),
print('\t')
def showtranspose(a,m,n):
for j in range(n):
for i in range(m):
print(a[i][j]),
print('\t')
a=((89,45,50),(130,120,40),(69,79,57),(78,4,8))
print("given matrix of order 4x3 is :")
showmatrix(a,4,3)
print("Transpose matrix is:")
showtranspose(a,4,3)
You can use async/await
for this. I would explain more, but there's nothing really to it. It's just a regular for
loop but I added the await
keyword before the construction of your Promise
What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.
// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld
So here's what that will look like ...
const someProcedure = async n =>_x000D_
{_x000D_
for (let i = 0; i < n; i++) {_x000D_
const t = Math.random() * 1000_x000D_
const x = await new Promise(r => setTimeout(r, t, i))_x000D_
console.log (i, x)_x000D_
}_x000D_
return 'done'_x000D_
}_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
See how we don't have to deal with that bothersome .then
call within our procedure? And async
keyword will automatically ensure that a Promise
is returned, so we can chain a .then
call on the returned value. This sets us up for great success: run the sequence of n
Promises, then do something important – like display a success/error message.
Let's consider your DOM as
<a>
<!-- some other icons and texts -->
<span>Close</span>
</a>
Now that you need to select parent tag 'a' based on <span>
text, then use
driver.findElement(By.xpath("//a[.//span[text()='Close']]"));
Explanation: Select the node based on its child node's value
Use .rsplit()
or .rpartition()
instead:
s.rsplit(',', 1)
s.rpartition(',')
str.rsplit()
lets you specify how many times to split, while str.rpartition()
only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.
Demo:
>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')
Both methods start splitting from the right-hand-side of the string; by giving str.rsplit()
a maximum as the second argument, you get to split just the right-hand-most occurrences.
Use pyplot.text()
(import matplotlib.pyplot as plt
)
import matplotlib.pyplot as plt
x=[1,2,3]
y=[9,8,7]
plt.plot(x,y)
for a,b in zip(x, y):
plt.text(a, b, str(b))
plt.show()
This code will send a GCM message to multiple registration IDs via PHP CURL.
// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)
$data = array('message' => 'Hello World!');
// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/
$ids = array('abc', 'def');
// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);
function sendPushNotification($data, $ids) {
// Insert real GCM API key from the Google APIs Console
// https://code.google.com/apis/console/
$apiKey = 'abc';
// Set POST request body
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
// Set CURL request headers
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
// Set request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set custom request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get the response back as string instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set JSON post data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// Actually send the request
$result = curl_exec($ch);
// Handle errors
if (curl_errno($ch)) {
echo 'GCM error: ' . curl_error($ch);
}
// Close curl handle
curl_close($ch);
// Debug GCM response
echo $result;
}
I know this is old. But yeah. I prefer much shorter solution, than Giona answer
[contenteditable] {
border-bottom: 1px solid transparent;
&:focus {outline: none; border-bottom: 1px dashed #000;}
}
To set flashdata you need to redirect controller function
$this->session->set_flashdata('message_name', 'This is test message');
//redirect to some function
redirect("controller/function_name");
//echo in view or controller
$this->session->flashdata('message_name');
Method A is recommended by httpclient developer community.
Please refer http://www.mail-archive.com/[email protected]/msg02455.html for more details.
The easiest solution is a "dummy" checkbox plus hidden input if you are using jquery:
<input id="id" type="hidden" name="name" value="1/0">
<input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id"
name="dummy-name" value="1/0" checked="checked/blank">
Set the value to the current 1/0 value to start with for BOTH inputs, and checked=checked if 1. The input field (active) will now always be posted as 1 or 0. Also the checkbox can be clicked more than once before submission and still work correctly.
I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.
https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js
If you have 2 routes that perform the same action you can do the following to keep it DRY.
var express = require("express"),
app = express.createServer();
function fooRoute(req, res, next) {
res.end("Foo Route\n");
}
app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);
app.listen(3000);
In the accepted answer the ConcurrentBag is not required. Here's an implementation without it:
var tasks = myCollection.Select(GetData).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select(t => t.Result);
Any of the "// some pre stuff" and "// some post stuff" can go into the GetData implementation (or another method that calls GetData)
Aside from being shorter, there's no use of an "async void" lambda, which is an anti pattern.
Something like this should work:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
IoC is a generic term meaning that rather than having the application call the implementations provided by a library (also know as toolkit), a framework calls the implementations provided by the application.
DI is a form of IoC, where implementations are passed into an object through constructors/setters/service lookups, which the object will 'depend' on in order to behave correctly.
IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.
DI frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in the implementations.
IoC containers are DI frameworks that can work outside of the programming language. In some you can configure which implementations to use in metadata files (e.g. XML) which are less invasive. With some you can do IoC that would normally be impossible like inject an implementation at pointcuts.
See also this Martin Fowler's article.
I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.
I just had the situation that I wanted this only for lines exceeding \linewidth
, that is: Squeezing long lines slightly.
Since it took me hours to figure this out, I would like to add it here.
I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g.
multline
of themathtools
package). So use it conscious.
In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.
\usepackage{environ} % provides \BODY
\usepackage{etoolbox} % provides \ifdimcomp
\usepackage{graphicx} % provides \resizebox
\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation
\RenewEnviron{equation}{
\settowidth{\myl}{$\BODY$} % calculate width and save as \myl
\origequation
\ifdimcomp{\the\linewidth}{>}{\the\myl}
{\ensuremath{\BODY}} % True
{\resizebox{\linewidth}{!}{\ensuremath{\BODY}}} % False
\origendequation
}
This might seem stupid to some people but it got me. I was getting this error and the problem for me was that I was trying to use static cells but then dynamically add more stuff. If you are calling this method your cells need to be dynamic prototypes. Select the cell in storyboard and under the Attributes inspector, the very first thing says 'Content' and you should select dynamic prototypes not static.
You may find the following windows command line useful in tracking down the offending jar file. it creates an index of all the class files in all the jars in the folder. Execute from within the lib folder of your deployed app, then search the index.txt file for the offending class.
for /r %X in (*.jar) do (echo %X & jar -tf %X) >> index.txt
Currently, there is no cross browser, script-free way of styling a native date picker.
As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.
I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".
It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.
While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
Technically what you are looking for is the unset value in combination with the shorthand property all:
The unset CSS keyword resets a property to its inherited value if it inherits from its parent, and to its initial value if not. In other words, it behaves like the inherit keyword in the first case, and like the initial keyword in the second case. It can be applied to any CSS property, including the CSS shorthand all.
.customClass {
/* specific attribute */
color: unset;
}
.otherClass{
/* unset all attributes */
all: unset;
/* then set own attributes */
color: red;
}
You can use the initial value as well, this will default to the initial browser value.
.otherClass{
/* unset all attributes */
all: initial;
/* then set own attributes */
color: red;
}
As an alternative:
If possible it is probably good practice to encapsulate the class or id in a kind of namespace:
.namespace .customClass{
color: red;
}
<div class="namespace">
<div class="customClass"></div>
</div>
because of the specificity of the selector this will only influence your own classes
It is easier to accomplish this in "preprocessor scripting languages" like SASS with nesting capabilities:
.namespace{
.customClass{
color: red
}
}
There are two things that could be happening:
READ_EXTERNAL_STORAGE
permission to your AndroidManifest.xml
Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.
First approach refers:
std::sort(numbers.begin(), numbers.end(), std::greater<>());
You may use the first approach because of getting more efficiency than second.
The first approach's time complexity less than second one.
Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html
You may want to mention which version of .NET you are using and your memory size.
You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Messing with mapping is borderline moving into real ORM land. Instead of fighting with it and keeping Dapper in its true simple (fast) form, just modify your SQL slightly like so:
var sql = @"select top 1 person_id as PersonId,FirstName,LastName from Person";
Instead of Str(RequestID)
, try convert(varchar(38), RequestID)
in kotlin its quite easy, using extensions methods of toMediaType, asRequestBody and toRequestBody here's an example:
here I am posting a couple of normal fields along with a pdf file and an image file using multipart
this is API declaration using retrofit:
@Multipart
@POST("api/Lesson/AddNewLesson")
fun createLesson(
@Part("userId") userId: RequestBody,
@Part("LessonTitle") lessonTitle: RequestBody,
@Part pdf: MultipartBody.Part,
@Part imageFile: MultipartBody.Part
): Maybe<BaseResponse<String>>
and here is how to actually call it:
api.createLesson(
userId.toRequestBody("text/plain".toMediaType()),
lessonTitle.toRequestBody("text/plain".toMediaType()),
startFromRegister.toString().toRequestBody("text/plain".toMediaType()),
MultipartBody.Part.createFormData(
"jpeg",
imageFile.name,
imageFile.asRequestBody("image/*".toMediaType())
),
MultipartBody.Part.createFormData(
"pdf",
pdfFile.name,
pdfFile.asRequestBody("application/pdf".toMediaType())
)
For any object array with header and data.jsfiddle
https://jsfiddle.net/AmrendraKumar/9ac75Lg0/2/
<table id="myTable" border='1|1'></table>
<script>
const userObjectArray = [{
name: "Ajay",
age: 27,
height: 5.10,
address: "Bangalore"
}, {
name: "Vijay",
age: 24,
height: 5.10,
address: "Bangalore"
}, {
name: "Dinesh",
age: 27,
height: 5.10,
address: "Bangalore"
}];
const headers = Object.keys(userObjectArray[0]);
var tr1 = document.createElement('tr');
var htmlHeaderStr = '';
for (let i = 0; i < headers.length; i++) {
htmlHeaderStr += "<th>" + headers[i] + "</th>"
}
tr1.innerHTML = htmlHeaderStr;
document.getElementById('myTable').appendChild(tr1);
for (var j = 0; j < userObjectArray.length; j++) {
var tr = document.createElement('tr');
var htmlDataString = '';
for (var k = 0; k < headers.length; k++) {
htmlDataString += "<td>" + userObjectArray[j][headers[k]] + "</td>"
}
tr.innerHTML = htmlDataString;
document.getElementById('myTable').appendChild(tr);
}
</script>
Change Copy Pods Resources for the target from:
"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-resources.sh"
to:
"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-frameworks.sh"
Have you tried calling knockout's clean node method on your DOM element to dispose of the in memory bound objects?
var element = $('#elementId')[0];
ko.cleanNode(element);
Then applying the knockout bindings again on just that element with your new view models would update your view binding.
Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).
A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc
). Memory allocated from the heap will remain allocated until one of the following occurs:
free
'dIf all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.
Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).
You can find more information about the heap in this article.
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation()
returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.
What you need to do is to modify the interface, so that it is asynchronous:
interface IIO
{
Task DoOperationAsync(); // note: no async here
}
class IOImplementation : IIO
{
public async Task DoOperationAsync()
{
// perform the operation here
}
}
This way, the user will see that the operation is async
and they will be able to await
it. This also pretty much forces the users of your code to switch to async
, but that's unavoidable.
Also, I assume using StartNew()
in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task()
is even worse, that won't even work, because you don't Start()
the Task
.)
Well, std::string
is a class, const char *
is a pointer. Those are two different things. It's easy to get from string
to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string
.
My recommendation: Functions that take constant strings and don't modify them should always take const char *
as an argument. That way, they will always work - with string literals as well as with std::string
(via an implicit c_str()
).
Yesterday, I am able to share the folders from my host OS Macbook (high Sierra) to Guest OS Windows 10
Original Answer
Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:
For now, right click on it, select Properties, the Compatibility tab, and select Windows 8 compatibility there. Much easier than using the compatibility troubleshooting I did initially.
It worked for me so I thought of sharing with everyone too.
Sure. Just walk through the $_POST
array:
foreach ($_POST as $key => $value) {
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
What causes a "broken pipe", and more importantly, is it possible to recover from that state?
It is caused by something causing the connection to close. (It is not your application that closed the connection: that would have resulted in a different exception.)
It is not possible to recover the connection. You need to open a new one.
If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption?
Yes it is. Once you've received that exception, the socket won't ever work again. Closing it is is the only sensible thing to do.
Is there ever a time when this
IOException
would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?
No. (Or at least, not without subverting proper behavior of the OS'es network stack, the JVM and/or your application.)
Is it wise to always call
SocketChannel.isConnected()
before attempting aSocketChannel.write()
...
In general, it is a bad idea to call r.isXYZ()
before some call that uses the (external) resource r
. There is a small chance that the state of the resource will change between the two calls. It is a better idea to do the action, catch the IOException
(or whatever) resulting from the failed action and take whatever remedial action is required.
In this particular case, calling isConnected()
is pointless. The method is defined to return true
if the socket was connected at some point in the past. It does not tell you if the connection is still live. The only way to determine if the connection is still alive is to attempt to use it; e.g. do a read or write.
folder = "ABC"
tries to run a command named folder
with arguments =
and "ABC"
. The format of command in bash is:
command arguments separated with space
while assignment is done with:
variable=something
[ -f $newfoldername/Primetime.eyetv]
, [
is a command (test
)
and -f
and $newfoldername/Primetime.eyetv]
are two arguments. It
expects a third argument (]
) which it can't find (arguments must be
separated with space) and thus will show error.[-f $newfoldername/Primetime.eyetv]
tries to run a command [-f
with argument $newfoldername/Primetime.eyetv]
Generally for cases like this, paste your code in shellcheck and see the feedback.
The code below show you how to set ImageView from a url string, using RxAndroid. First, add RxAndroid library 2.0
dependencies {
// RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.0'
// Utilities
compile 'org.apache.commons:commons-lang3:3.5'
}
now use setImageFromUrl to set image.
public void setImageFromUrl(final ImageView imageView, final String urlString) {
Observable.just(urlString)
.filter(new Predicate<String>() {
@Override public boolean test(String url) throws Exception {
return StringUtils.isNotBlank(url);
}
})
.map(new Function<String, Drawable>() {
@Override public Drawable apply(String s) throws Exception {
URL url = null;
try {
url = new URL(s);
return Drawable.createFromStream((InputStream) url.getContent(), "profile");
} catch (final IOException ex) {
return null;
}
}
})
.filter(new Predicate<Drawable>() {
@Override public boolean test(Drawable drawable) throws Exception {
return drawable != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Drawable>() {
@Override public void accept(Drawable drawable) throws Exception {
imageView.setImageDrawable(drawable);
}
});
}
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
Another option:
Replace the string delimiter with a single character, then split on that character.
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');
If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n
highest elements are:
(-avgDists).argsort()[:n]
Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you can read from the tail of the argsort to find the n
highest elements:
avgDists.argsort()[::-1][:n]
Both methods are O(n log n) in time complexity, because the argsort
call is the dominant term here. But the second approach has a nice advantage: it replaces an O(n) negation of the array with an O(1) slice. If you're working with small arrays inside loops then you may get some performance gains from avoiding that negation, and if you're working with huge arrays then you can save on memory usage because the negation creates a copy of the entire array.
Note that these methods do not always give equivalent results: if a stable sort implementation is requested to argsort
, e.g. by passing the keyword argument kind='mergesort'
, then the first strategy will preserve the sorting stability, but the second strategy will break stability (i.e. the positions of equal items will get reversed).
Example timings:
Using a small array of 100 floats and a length 30 tail, the view method was about 15% faster
>>> avgDists = np.random.rand(100)
>>> n = 30
>>> timeit (-avgDists).argsort()[:n]
1.93 µs ± 6.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
1.64 µs ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
1.64 µs ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
For larger arrays, the argsort is dominant and there is no significant timing difference
>>> avgDists = np.random.rand(1000)
>>> n = 300
>>> timeit (-avgDists).argsort()[:n]
21.9 µs ± 51.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
21.7 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
21.9 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Please note that the comment from nedim below is incorrect. Whether to truncate before or after reversing makes no difference in efficiency, since both of these operations are only striding a view of the array differently and not actually copying data.
Just check
in MacOS
File directory = new File("/Users/sivo03/eclipse-workspace/For4DC/AutomationReportBackup/"+dir);
File directoryApache = new File("/Users/sivo03/Automation/apache-tomcat-9.0.22/webapps/AutomationReport/"+dir);
and same we use in windows
File directory = new File("C:\\Program Files (x86)\\Jenkins\\workspace\\BrokenLinkCheckerALL\\AutomationReportBackup\\"+dir);
File directoryApache = new File("C:\\Users\\Admin\\Downloads\\Automation\\apache-tomcat-9.0.26\\webapps\\AutomationReports\\"+dir);
use double backslash instead of single frontslash
so no need any converter tool just use find and replace
"C:\Documents and Settings\Manoj\Desktop" to "C:\\Documents and Settings\\Manoj\\Desktop"
I got here looking for a solution for JavaScript displayed in the browser and although not directly related with a database...
In my case I copied and pasted some text I found on the internet into a JavaScript file and saved it with Windows Notepad.
When the page that uses that JavaScript file output the strings there were question marks (like the ones shown in the question) instead of the special characters like accented letters, etc.
I opened the file using Notepad++
. Right after opening the file I saw that the character encoding was set as ANSI
as you can see (mouse cursor on footer) in the following screenshot:
To solve the issue, click the Encoding
menu in Notepad++
and select Encode in UTF-8
. You should be good to go. :)
Keep template column inside DataGrid.Columns. This helped me resolve this issue.
Ref: DataGridTemplateColumn : Items collection must be empty before using ItemsSource.
You can do by the following ways
this.your_form.getRawValue()['formcontrolname]
this.your_form.value['formcontrolname]
Guessing you probably just want to format the output date? then this is what you are after
SELECT *, DATE_FORMAT(date,'%d/%m/%Y') AS niceDate
FROM table
ORDER BY date DESC
LIMIT 0,14
Or do you actually want to sort by Day before Month before Year?
Here is my solution... FWIW
package com.example.PrefTest;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
public class Preferences extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager.setDefaultValues(Preferences.this, R.xml.preferences,
false);
initSummary(getPreferenceScreen());
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceGroup) {
PreferenceGroup pGrp = (PreferenceGroup) p;
for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
initSummary(pGrp.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
if (p.getTitle().toString().toLowerCase().contains("password"))
{
p.setSummary("******");
} else {
p.setSummary(editTextPref.getText());
}
}
if (p instanceof MultiSelectListPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}
Golang/go-swagger example: https://github.com/go-swagger/go-swagger/issues/1416
// swagger:parameters opid
type XRequestIdHeader struct {
// in: header
// required: true
XRequestId string `json:"X-Request-Id"`
}
...
// swagger:operation POST /endpoint/ opid
// Parameters:
// - $ref: #/parameters/XRequestIDHeader
It depends on when the self executing anonymous function is running. It is possible that it is running before window.document
is defined.
In that case, try adding a listener
window.addEventListener('load', yourFunction, false);
// ..... or
window.addEventListener('DOMContentLoaded', yourFunction, false);
yourFunction () {
// some ocde
}
Update: (after the update of the question and inclusion of the code)
Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head
element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM
Hi same problem i have solved you can try this
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK
// SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client.setSslSocketFactory(sslSocketFactory);
client.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return new OkClient(client);
}
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
if params[:one] && params[:two]
... do something ...
elsif params[:one]
... do something ...
end
You could try the following:
select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId
You have to rebuild the package and tell npm to update it's binary too. Try:
npm rebuild bcrypt --update-binary
@robertklep answered a relative question with this command, look.
Only rebuild haven't solved my problem, this works fine in my application.
Hope it helps!
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
I like ggplot
too.
Here's one example:
df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),
nation = c('China', 'USA', 'China', 'USA'),
value = c(4.0, 5.0, 6.0, 5.5))
ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')
You might find the Semantic Versioning Specification useful.
In addition to above answers suggesting (1) the modification of the configuration files pg_hba.conf and (2) postgresql.conf and (3) restarting the PostgreSQL service, some Windows computers might also require incoming TCP traffic to be allowed on the port (usually 5432
).
To do this, you would need to open Windows Firewall and add an inbound rule for the port (e.g. 5432).
Head to Control Panel\System and Security\Windows Defender Firewall > Advanced Settings > Actions (right tab) > Inbound Rules > New Rule… > Port > Specific local ports and type in the port your using, usually 5432 > (defaults settings for the rest and type any name you'd like)
Now, try connecting again from pgAdmin on the client computer. Restarting the service is not required.
I was getting the issue 'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp'
on the TeamCity build server.
I changed the "Update Mode" of the Nuget Installer build step from solution file to packages.config and NuGet.exe to the latest version (I had 3.5.0) and it worked !!
Promise returned from $http
can not be binded directly (I dont exactly know why).
I'm using wrapping service that works perfectly for me:
.factory('DocumentsList', function($http, $q){
var d = $q.defer();
$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
and bind to it in controller:
function Ctrl($scope, DocumentsList) {
$scope.Documents = DocumentsList;
...
}
UPDATE!:
In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises
The reason why Ng-Bind is better because,
When Your page is not Loaded or when your internet is slow or when your website loaded half, then you can see these type of issues (Check the Screen Shot with Read mark) will be triggered on Screen which is Completly weird. To avoid such we should use Ng-bind
First of all check to see if your PHP installation supports CLI. Type: php -v
. You can execute PHP from the command line in 2 ways:
php yourfile.php
php -r 'print("Hello world");'
Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.
Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.
Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search">
as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.
Here is the needed Bootstrap markup.
<div class="position-relative">
<i class="fa fa-search position-absolute"></i>
<input class="form-control" type="search">
</div>
...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:
i {
font-size: 1rem;
color: #333;
top: .75rem;
left: .75rem
}
input {
padding-left: 2.5rem;
}
You may have to fiddle with the values for top, left, and padding-left.
How about:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
You can use:
objects_all=Class.objects.filter(filter_condition="")
This will return a query set even if it gets one object. If you need exactly one object use:
obj=Class.objects.get(conditon="")
throw $e->getMessage();
You try to throw a string
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
A solution would be to declare your key as nvarchar(20)
.
There is a subtle difference between running FOR
from the command line and from a batch file. In a batch file, you need to put two %
characters in front of each variable reference.
From a command line:
FOR %i IN (*) DO ECHO %i
From a batch file:
FOR %%i IN (*) DO ECHO %%i
This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5
in this case) will be? Then I can try to provide a more complete answer.
Sub setCondFormat()
Range("B3").Select
With Range("B3:H63")
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
End With
End With
End With
End Sub
Note: this is tested in Excel 2010.
Edit: Updated code based on comments.
I've successfully implemented ReCaptcha in the following way.
note: this is in VB, but can easily be converted
1] First grab a copy of the reCaptcha library
2] Then build a custom ReCaptcha HTML Helper
''# fix SO code coloring issue.
<Extension()>
Public Function reCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString
Dim captchaControl = New Recaptcha.RecaptchaControl With {.ID = "recaptcha",
.Theme = "clean",
.PublicKey = "XXXXXX",
.PrivateKey = "XXXXXX"}
Dim htmlWriter = New HtmlTextWriter(New IO.StringWriter)
captchaControl.RenderControl(htmlWriter)
Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString)
End Function
3] From here you need a re-usable server side validator
Public Class ValidateCaptchaAttribute : Inherits ActionFilterAttribute
Private Const CHALLENGE_FIELD_KEY As String = "recaptcha_challenge_field"
Private Const RESPONSE_FIELD_KEY As String = "recaptcha_response_field"
Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
If IsNothing(filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)) Then
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = True
Return
End If
Dim captchaChallengeValue = filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)
Dim captchaResponseValue = filterContext.HttpContext.Request.Form(RESPONSE_FIELD_KEY)
Dim captchaValidtor = New RecaptchaValidator() With {.PrivateKey = "xxxxx",
.RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
.Challenge = captchaChallengeValue,
.Response = captchaResponseValue}
Dim recaptchaResponse = captchaValidtor.Validate()
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = recaptchaResponse.IsValid
MyBase.OnActionExecuting(filterContext)
End Sub
Now that you have your re-usable code... all you need to do is add the captcha to your View.
<%: Html.reCaptcha %>
And when you post the form to your controller...
''# Fix SO code coloring issues
<ValidateCaptcha()>
<AcceptVerbs(HttpVerbs.Post)>
Function Add(ByVal CaptchaIsValid As Boolean, ByVal [event] As Domain.Event) As ActionResult
If Not CaptchaIsValid Then ModelState.AddModelError("recaptcha", "*")
'#' Validate the ModelState and submit the data.
If ModelState.IsValid Then
''# Post the form
Else
''# Return View([event])
End If
End Function
Don't use ==
in PHP. It will not do what you expect. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.
For example '1e3' == '1000'
returns true. You should use ===
instead.
Keep it simple, silly! ;)
Simple OR logic...
function checkDuplicatesInArray($array){
$duplicates=FALSE;
foreach($array as $k=>$i){
if(!isset($value_{$i})){
$value_{$i}=TRUE;
}
else{
$duplicates|=TRUE;
}
}
return ($duplicates);
}
Regards!
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
It means that there have been other commits pushed to the remote repository that differ from your commits. You can usually solve this with a
git pull
before you push
Ultimately, "fast-forward" means that the commits can be applied directly on top of the working tree without requiring a merge.
Passing dictionary as argument it will convert strings which can be converted to float and will leave others
def covertDict_float(data):
for i in data:
if data[i].split(".")[0].isdigit():
try:
data[i] = float(data[i])
except:
continue
return data
As @KyssTao has been saying, help(dates.num2date)
says that the x
has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102
is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).
Use datestr2num
instead (see help(dates.datestr2num)
):
new_x = dates.datestr2num(date) # where date is '01/02/1991'
This combination worked for me:
<EditText ... >
android:longClickable="false"
android:cursorVisible="false"
android:focusableInTouchMode="false"
</EditText>
What about the official JDBC 4.0 compatible JDBC driver from Microsoft?
Array.new(n){[*"0".."9"].sample}.join
,
where n=8
in your case.
Generalized: Array.new(n){[*"A".."Z", *"0".."9"].sample}.join
, etc.
Update:
As of jQuery 1.6+ you should use prop()
instead of attr()
in this case.
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
Original Answer:
If you want to select by the value of the option, REGARDLESS of its position (this example assumes you have an ID for your select):
var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);
You do not need to "unselect". That happens automatically when you select another.
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
First of, please think long and hard if you really want to disable the Home
button or any other button for that matter (e.g. the Back
button), this is not something that should be done (at least most of the times, this is a bad design). I can speak only for myself, but if I downloaded an app that doesn't let me do something like clicking an OS button, the next thing I do is uninstall that app and leave a very bad review. I also believe that your app will not be featured on the App Store.
Now...
Notice that MX Player
is asking permission to draw on top of other applications:
Since you cannot override the Home
button on Android
device (at least no in the latest OS versions). MX Player
draws itself on top of your launcher when you "lock" the app and clicks on the Home
button.
To see an example of that is a bit more simple and straight forward to understand, you can see the Facebook Messenger App.
As I was asked to provide some more info about MX Player Status Bar
and Navigation Bar
"overriding", I'm editing my answer to include these topics too.
First thing first, MX Player is using Immersive Full-Screen Mode (DevBytes Video) on KitKat
.
Android 4.4 (API Level 19) introduces a new SYSTEM_UI_FLAG_IMMERSIVE flag for setSystemUiVisibility() that lets your app go truly "full screen." This flag, when combined with the SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN flags, hides the navigation and status bars and lets your app capture all touch events on the screen.
When immersive full-screen mode is enabled, your activity continues to receive all touch events. The user can reveal the system bars with an inward swipe along the region where the system bars normally appear. This clears the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag (and the SYSTEM_UI_FLAG_FULLSCREEN flag, if applied) so the system bars become visible. This also triggers your View.OnSystemUiVisibilityChangeListener, if set. However, if you'd like the system bars to automatically hide again after a few moments, you can instead use the SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag. Note that the "sticky" version of the flag doesn't trigger any listeners, as system bars temporarily shown in this mode are in a transient state.
Second: Hiding the Status Bar
Third: Hiding the Navigation Bar
Please note that although using immersive full screen is only for KitKat
, hiding the Status Bar
and Navigation Bar
is not only for KitKat
.
I don't have much to say about the 2nd and 3rd, You get the idea I believe, it's a fast read in any case. Just make sure you pay close attention to View.OnSystemUiVisibilityChangeListener.
I added a Gist that explains what I meant, it's not complete and needs some fixing but you'll get the idea. https://gist.github.com/Epsiloni/8303531
Good luck implementing this, and have fun!
You are not specifying a language or framework, but the following header is used for file downloads:
"Content-Disposition: attachment; filename=abc.csv"
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
That works for me
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
#1- Run this to configure the region once and for all:
aws configure set region us-east-1 --profile admin
Change admin
next to the profile if it's different.
Change us-east-1
if your region is different.
#2- Run your command again:
aws ecs list-container-instances --cluster default
H = "Hello"
if type(H) is list or type(H) is tuple:
## Do Something.
else
## Do Something.
There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()
C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
Volume in drive C has no label.
Volume Serial Number is 46A0-BB64
Directory of c:\ABC\SEM 2\testfiles
13/02/2013 10:20 PM <DIR> .
13/02/2013 10:20 PM <DIR> ..
13/02/2013 10:20 PM 0 all.txt
1 File(s) 0 bytes
2 Dir(s) 78,929,309,696 bytes free
C:\Users\Gnibbler>
In swift 4.0
For Delay of 1 second after default launch time...
RunLoop.current.run(until: Date(timeIntervalSinceNow : 1.0))
SELECT @myDate - DAY(@myDate) + 1
C++11 gives you a lot of new options with random
. The canonical paper on this topic would be N3551, Random Number Generation in C++11
To see why using rand()
can be problematic see the rand() Considered Harmful presentation material by Stephan T. Lavavej given during the GoingNative 2013 event. The slides are in the comments but here is a direct link.
I also cover boost
as well as using rand
since legacy code may still require its support.
The example below is distilled from the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,10)
interval, with other engines and distributions commented out (see it live):
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
int main()
{
std::random_device rd;
//
// Engines
//
std::mt19937 e2(rd());
//std::knuth_b e2(rd());
//std::default_random_engine e2(rd()) ;
//
// Distribtuions
//
std::uniform_real_distribution<> dist(0, 10);
//std::normal_distribution<> dist(2, 2);
//std::student_t_distribution<> dist(5);
//std::poisson_distribution<> dist(2);
//std::extreme_value_distribution<> dist(0,2);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(e2))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
output will be similar to the following:
0 ****
1 ****
2 ****
3 ****
4 *****
5 ****
6 *****
7 ****
8 *****
9 ****
The output will vary depending on which distribution you choose, so if we decided to go with std::normal_distribution with a value of 2
for both mean and stddev e.g. dist(2, 2)
instead the output would be similar to this (see it live):
-6
-5
-4
-3
-2 **
-1 ****
0 *******
1 *********
2 *********
3 *******
4 ****
5 **
6
7
8
9
The following is a modified version of some of the code presented in N3551
(see it live) :
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
std::default_random_engine & global_urng( )
{
static std::default_random_engine u{};
return u ;
}
void randomize( )
{
static std::random_device rd{};
global_urng().seed( rd() );
}
int main( )
{
// Manufacture a deck of cards:
using card = int;
std::array<card,52> deck{};
std::iota(deck.begin(), deck.end(), 0);
randomize( ) ;
std::shuffle(deck.begin(), deck.end(), global_urng());
// Display each card in the shuffled deck:
auto suit = []( card c ) { return "SHDC"[c / 13]; };
auto rank = []( card c ) { return "AKQJT98765432"[c % 13]; };
for( card c : deck )
std::cout << ' ' << rank(c) << suit(c);
std::cout << std::endl;
}
Results will look similar to:
5H 5S AS 9S 4D 6H TH 6D KH 2S QS 9H 8H 3D KC TD 7H 2D KS 3C TC 7D 4C QH QC QD JD AH JC AC KD 9D 5C 2H 4H 9C 8C JH 5D 4S 7C AD 3S 8S TS 2C 8D 3H 6C JS 7S 6S
Boost
Of course Boost.Random is always an option as well, here I am using boost::random::uniform_real_distribution:
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
int main()
{
boost::random::mt19937 gen;
boost::random::uniform_real_distribution<> dist(0, 10);
std::map<int, int> hist;
for (int n = 0; n < 10000; ++n) {
++hist[std::floor(dist(gen))];
}
for (auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*') << '\n';
}
}
rand()
If you must use rand()
then we can go to the C FAQ for a guides on How can I generate floating-point random numbers? , which basically gives an example similar to this for generating an on the interval [0,1)
:
#include <stdlib.h>
double randZeroToOne()
{
return rand() / (RAND_MAX + 1.);
}
and to generate a random number in the range from [M,N)
:
double randMToN(double M, double N)
{
return M + (rand() / ( RAND_MAX / (N-M) ) ) ;
}
Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
Here are my working example
@RequestMapping(value = "/api/v1/files/upload", method =RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files) {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<String> tempFileNames = new ArrayList<>();
String tempFileName;
FileOutputStream fo;
try {
for (MultipartFile file : files) {
tempFileName = "/tmp/" + file.getOriginalFilename();
tempFileNames.add(tempFileName);
fo = new FileOutputStream(tempFileName);
fo.write(file.getBytes());
fo.close();
map.add("files", new FileSystemResource(tempFileName));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
String response = restTemplate.postForObject(uploadFilesUrl, requestEntity, String.class);
} catch (IOException e) {
e.printStackTrace();
}
for (String fileName : tempFileNames) {
File f = new File(fileName);
f.delete();
}
return new ResponseEntity<Object>(HttpStatus.OK);
}
It's working fine try this.Link
UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
[top presentViewController:secondView animated:YES completion: nil];
You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.
Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split
As an alternative, if there's not a specific reason to use Math.random()
, use Random.nextInt()
:
import java.util.Random;
Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.
I think you haven't messed up yet. Try:
git reset HEAD^
This will bring the dir to state before you've made the commit, HEAD^
means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).
myInt=10
myList=[tmpList/myInt for tmpList in range(10,100,10)]
You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:
switch(day) {
case Day.MONDAY:
// Something..
break;
case Day.FRIDAY:
// Something friday
break;
}
Make sure that you use the actual enum values instead of EnumType.EnumValue
Eclipse points out this mistake though..
It looks to me like your publish profile is not being used, and doing some default packaging. The Microsoft Web Publish targets do all what you are doing above, it selects the correct targets based on the config.
I got mine to work no problem from TeamCity MSBuild step, but I did specify an explicit path to the profile, you just have to call it by name with no .pubxml (e.g. FileSystemDebug). It will be found so long as in the standard folder, which yours is.
Example:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe ./ProjectRoot/MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=FileSystemDebug
Note this was done using the Visual Studio 2012 versions of the Microsoft Web Publish targets, normally located at "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web". Check out the deploy folder for the specific deployment types targets that are used
I do not work with google android but I think you'll find it's not that hard to get this working. If you read the relevant bit of the java tutorial you'll see that a registered cookiehandler gets callbacks from the HTTP code.
So if there is no default (have you checked if CookieHandler.getDefault()
really is null?) then you can simply extend CookieHandler, implement put/get and make it work pretty much automatically. Be sure to consider concurrent access and the like if you go that route.
edit: Obviously you'd have to set an instance of your custom implementation as the default handler through CookieHandler.setDefault()
to receive the callbacks. Forgot to mention that.
I was facing the same issue while using the integrated terminal in VS Code editor. Restarting VS Code after changing the node version using nvm fixed the issue for me.
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
I tried the following one but didn't work;
<span style="display: none;" id="doneimg">
<img alt="done" title="The process has been complated successfully..." src="@Url.Content("~/Content/App_Icons/icos/tick_icon.gif")" />
</span>
<script type="text/javascript">
//$(document).ready(function () {
$("#doneimg").bind("load", function () { $(this).fadeIn('slow'); });
//});
</script>
bu the following one worked just fine;
<script type="text/javascript">
$(document).ready(function () {
$('#doneimg').fadeIn("normal");
});
</script>
<span style="display: none;" id="doneimg">
<img alt="done" title="The process has been complated successfully..." src="@Url.Content("~/Content/App_Icons/icos/tick_icon.gif")" />
</span>
The problem with your code is in the line:
for(i in length(namevector))
You need to ask yourself: what is length(namevector)
? It's one number. So essentially you're saying:
for(i in 11)
df[,i] <- NA
Or more simply:
df[,11] <- NA
That's why you're getting an error. What you want is:
for(i in namevector)
df[,i] <- NA
Or more simply:
df[,namevector] <- NA
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
In C# 7 we now have Pattern Matching so you can do something like:
switch (age)
{
case 50:
ageBlock = "the big five-oh";
break;
case var testAge when (new List<int>()
{ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):
ageBlock = "octogenarian";
break;
case var testAge when ((testAge >= 90) & (testAge <= 99)):
ageBlock = "nonagenarian";
break;
case var testAge when (testAge >= 100):
ageBlock = "centenarian";
break;
default:
ageBlock = "just old";
break;
}
Bash, like other shells, is just a tool for coordinating other commands. Typically you would try to use standard UNIX commands, but you can of course use Bash to invoke anything, including your own compiled programs, other shell scripts, Python and Perl scripts etc.
In this case, there are a couple of ways to do it.
If you want to read a file, and write it to another file, doing search/replace as you go, use sed:
sed 's/abc/XYZ/g' <infile >outfile
If you want to edit the file in place (as if opening the file in an editor, editing it, then saving it) supply instructions to the line editor 'ex'
echo "%s/abc/XYZ/g
w
q
" | ex file
Example is like vi
without the fullscreen mode. You can give it the same commands you would at vi
's :
prompt.
If you want get "insert statement" for your table you can try the following code.
SELECT
CONCAT(
GROUP_CONCAT(
CONCAT(
'INSERT INTO `your_table` (`field_1`, `field_2`, `...`, `field_n`) VALUES ("',
`field_1`,
'", "',
`field_2`,
'", "',
`...`,
'", "',
`field_n`,
'")'
) SEPARATOR ';\n'
), ';'
) as `QUERY`
FROM `your_table`;
As a result, you will have insers statement:
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_11, value_12, ... , value_1n);
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_21, value_22, ... , value_2n);
/...................................................../
INSERT INTO your_table
(field_1
, field_2
, ...
, field_n
) VALUES (value_m1, value_m2, ... , value_mn);
, where m - number of records in your_table
If you don't want to bother with weird expansions from bash you can do this
me$ FOO="BAR \x2A BAR" # 2A is hex code for *
me$ echo -e $FOO
BAR * BAR
me$
Explanation here why using -e option of echo makes life easier:
Relevant quote from man here:
SYNOPSIS
echo [SHORT-OPTION]... [STRING]...
echo LONG-OPTION
DESCRIPTION
Echo the STRING(s) to standard output.
-n do not output the trailing newline
-e enable interpretation of backslash escapes
-E disable interpretation of backslash escapes (default)
--help display this help and exit
--version
output version information and exit
If -e is in effect, the following sequences are recognized:
\\ backslash
...
\0NNN byte with octal value NNN (1 to 3 digits)
\xHH byte with hexadecimal value HH (1 to 2 digits)
For the hex code you can check man ascii page (first line in octal, second decimal, third hex):
051 41 29 ) 151 105 69 i
052 42 2A * 152 106 6A j
053 43 2B + 153 107 6B k
IMHO the best solution is the @Kevin Stone directive, but I had to upgrade it to work in every conditions (f.e. select, textarea), and this one is working for sure:
angular.module('app').directive('ngInitial', function($parse) {
return {
restrict: "A",
compile: function($element, $attrs) {
var initialValue = $attrs.value || $element.val();
return {
pre: function($scope, $element, $attrs) {
$parse($attrs.ngModel).assign($scope, initialValue);
}
}
}
}
});
A good resource start off point would be MSDN as your looking into a microsoft product
I also had this error.
My IIS Website has a Default Website with three (3) application directories below it.
I had each of my 3 application directories configured correctly to use .NET Framework v2.0 in the Application Pools.
However, the Default Website never was configured. I didn't think it was necessary since all of my apps were contained within it.
My IIS Server's default configuration is .NET Framework v4.0, so I changed that to .NET v2.0:
After I did that, I no longer received the same error message.
Now, I see this:
I hope this information helps others.
It's part of the .NET Framework 4.7
.
As long as you don't target the above framework or higher (or .NET Core 2.0
/ .NET Standard 2.0
), you'll need to reference ValueTuple
. Do this by adding the System.ValueTuple
NuGet Package
To get a type that implements io.Reader
from a []byte
slice, you can use bytes.NewReader
in the bytes
package:
r := bytes.NewReader(byteData)
This will return a value of type bytes.Reader
which implements the io.Reader
(and io.ReadSeeker
) interface.
Don't worry about them not being the same "type". io.Reader
is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.
AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.
Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.
To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.
Pretty much everything can be transported through TCP though.
(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)
Try:
strng = ""
for i in range(97,123):
strng = strng + chr(i)
print(strng)
You can use the XML Instance Generator which is part of the Sun/Oracle Multi-Schema Validator.
It's README.txt states:
Sun XML Generator is a Java tool to generate various XML instances from several kinds of schemas. It supports DTD, RELAX Namespace, RELAX Core, TREX, and a subset of W3C XML Schema Part 1. [...]
This is a command-line tool that can generate both valid and invalid instances from schemas. It can be used for generating test cases for XML applications that need to conform to a particular schema.
Download and unpack xmlgen.zip
from the msv download page and run the following command to get detailed usage instructions:
java -jar xmlgen.jar -help
The tool appears to be released under a BSD license; the source code is accessible from here
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
Goto:
project>Properties>Android> select: google APIs Android 4.0.3
Click Icon:
Android Virtual Device Manager>Edit> Slect box in Tabget>Google APIs APIsLevel15
and select Built-in: is WQVGA400 > Edit AVD > Start
This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)
if (capital && capital.length < 1) {do your stuff}
You can change it in you php-configuration on your webserver.
Search in php.ini
for
session.gc_maxlifetime()
The value is set in Seconds.
This worked for me.
formula
in the first cell.Enter
.Ctrl + Shift + down_arrow
. This will select the last cell in the column used on the worksheet.Ctrl + D
. This will fill copy the formula in the remaining cells.Add few points on top of apesa's excellent post:
1) You can use command below to check the ip address mysql server is listening
netstat -nlt | grep 3306
sample result:
tcp 0 0 xxx.xxx.xxx.xxx:3306 0.0.0.0:* LISTEN
2) Use FLUSH PRIVILEGES
to force grant tables to be loaded if for some reason the changes not take effective immediately
GRANT ALL ON *.* TO 'user'@'localhost' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
GRANT ALL ON *.* TO 'user'@'%' IDENTIFIED BY 'passwd' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
user == the user u use to connect to mysql ex.root
passwd == the password u use to connect to mysql with
3) If netfilter firewall is enabled (sudo ufw enable
) on mysql server machine, do the following to open port 3306 for remote access:
sudo ufw allow 3306
check status using
sudo ufw status
4) Once a remote connection is established, it can be verified in either client or server machine using commands
netstat -an | grep 3306
netstat -an | grep -i established
You can use @Qualifier
along with @Autowired
. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier
For Example in following case it is necessary provide a qualifier
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
EDIT:
In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
@RequiredArgsConstructor
public Payroll {
@Qualifier("employee") private final Person person;
}
provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):
# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
This was recently introduced in latest lombok 1.18.4.
NOTE
If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)
public Payroll {
@Autowired @Qualifier("employee") private final Person person;
}
or
public Payroll {
private final Person person;
@Autowired
@Qualifier("employee")
public void setPerson(Person person) {
this.person = person;
}
}
If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
Set your database connection to UTF8:
if($handle = @mysql_connect(DB_HOST, DB_USER, DB_PASS)){
//set to utf8 encoding
mysql_set_charset('utf8',$handle);
}
If you want to convert all elements of a
to a single numeric vector and length(a)
is greater than 1 (OK, even if it is of length 1), you could unlist
the object first and then convert.
as.numeric(unlist(a))
# [1] 10 38 66 101 129 185 283 374
Bear in mind that there aren't any quality controls here. Also, X$Days
a mighty odd name.
<ul class="names" id="names_list">
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>
</ul>
$(document).ready(function(){
var a=0;
var ac;
var ac2;
$(".names li").click(function(){
var b=0;
if(a==0)
{
var accc="#"+ac2;
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
$(this).css({
"background":"#d3b730",
"color":"#000",
});
ac=$(this).attr('class');
ac2=$(this).attr('id');
a=1;
}
else{
var accc="#"+ac2;
//alert(accc);
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
a=0;
ac=$(this).attr('class');
ac2=$(this).attr('id');
$(this).css({
"background":"#d3b730",
"color":"#000",
});
}
});
Delete you AVD and create another. Maybe isn't the perfect thing to do, but it's the fastest.
Here is a more efficient version which uses on
for all contenteditables. It's based off the top answers here.
$('body').on('focus', '[contenteditable]', function() {
const $this = $(this);
$this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
const $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
The project is here: https://github.com/balupton/html5edit
Here is a complete list--I believe: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
To get the namespace in its namespace format, e.g. {myNameSpace}
, you can do the following:
root = tree.getroot()
ns = re.match(r'{.*}', root.tag).group(0)
This way, you can use it later on in your code to find nodes, e.g using string interpolation (Python 3).
link = root.find(f"{ns}link")
From the diff man page:
-q
Report only whether the files differ, not the details of the differences.
-r
When comparing directories, recursively compare any subdirectories found.
Example command:
diff -qr dir1 dir2
Example output (depends on locale):
$ ls dir1 dir2
dir1:
same-file different only-1
dir2:
same-file different only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2
For those wanting the box-shadow on the col-*
container itself and not on the .container
, you can add another div
just inside the col-*
element, and add the shadow to that. This element will not have the padding, and therefor not interfere.
The first image has the box-shadow
on the col-*
element. Because of the 15px padding on the col
element, the shadow is pushed to the outside of the div
element rather than on the visual edges of it.
<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
<div class="thumbnail">
{!! HTML::image('images/sampleImage.png') !!}
</div>
</div>
The second image has a wrapper div
with the box-shadow
on it. This will place the box-shadow
on the visual edges of the element.
<div class="col-md-4">
<div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
<div class="thumbnail">
{!! HTML::image('images/sampleImage.png') !!}
</div>
</div>
</div>
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
you can use this for example
$array = json_decode($string,true)
but validate the Json before. You can validate from http://jsonviewer.stack.hu/
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
Try "py" instead of "python" from command line:
C:\Users\Cpsa>py
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
If you want to pass an app-instance to others in Node-Typescript :
Option 1:
With the help of import
(when importing)
//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';
const routing = (app: Application) => {
app.use('/api/admin/category', categoryRoute)
app.use('/api/admin/course', courseRoute)
}
export { routing }
Then import it and pass app:
import express, { Application } from 'express';
const app: Application = express();
import('./routes').then(m => m.routing(app))
Option 2: With the help of class
// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';
const app: Application = express();
const rotues = new Routes(app)
...
Here we will access the app in the constructor of Routes Class
// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';
class Routes {
constructor(private app: Application) {
this.apply();
}
private apply(): void {
this.app.use('/api/admin/category', categoryRoute)
this.app.use('/api/admin/course', courseRoute)
}
}
export { Routes }
(I'm not completely happy with the answers so far, so here is my attempt...)
I think that Kevin Wright's comment ("You can make a Promise and it's up to you to keep it. When someone else makes you a promise you must wait to see if they honour it in the Future") summarizes it pretty well, but some explanation can be useful.
Futures and promises are pretty similar concepts, the difference is that a future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once). The Java 8 CompletableFuture and the Guava SettableFuture can be thought of as promises, because their value can be set ("completed"), but they also implement the Future interface, therefore there is no difference for the client.
The result of the future will be set by "someone else" - by the result of an asynchronous computation. Note how FutureTask - a classic future - must be initialized with a Callable or Runnable, there is no no-argument constructor, and both Future and FutureTask are read-only from the outside (the set methods of FutureTask are protected). The value will be set to the result of the computation from the inside.
On the other hand, the result of a promise can be set by "you" (or in fact by anybody) anytime because it has a public setter method. Both CompletableFuture and SettableFuture can be created without any task, and their value can be set at any time. You send a promise to the client code, and fulfill it later as you wish.
Note that CompletableFuture is not a "pure" promise, it can be initialized with a task just like FutureTask, and its most useful feature is the unrelated chaining of processing steps.
Also note that a promise does not have to be a subtype of future and it does not have to be the same object. In Scala a Future object is created by an asynchronous computation or by a different Promise object. In C++ the situation is similar: the promise object is used by the producer and the future object by the consumer. The advantage of this separation is that the client cannot set the value of the future.
Both Spring and EJB 3.1 have an AsyncResult class, which is similar to the Scala/C++ promises. AsyncResult does implement Future but this is not the real future: asynchronous methods in Spring/EJB return a different, read-only Future object through some background magic, and this second "real" future can be used by the client to access the result.
For those who are experiencing this issue for my test project .NET Core 2.0
in the Visual Studio 2017 Community (v15.3 3)
. I also had this bug using JetBrains ReSharper Ultimate 2017.2 Build 109.0.20170824.131346
- there is a bug I posted.
JetBrains advised to create a new test project from scratch to reproduce it. When I did that and got tests working OK, I found the reason causing the issue:
*.csproj
file:Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}
"
When I did that - tests started working fine.