Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
In my case, I use "sortedArrayUsingComparator" to sort an array. Look at the below code.
contactArray = [[NSArray arrayWithArray:[contactSet allObjects]] sortedArrayUsingComparator:^NSComparisonResult(ContactListData *obj1, ContactListData *obj2) {
NSString *obj1Str = [NSString stringWithFormat:@"%@ %@",obj1.contactName,obj1.contactSurname];
NSString *obj2Str = [NSString stringWithFormat:@"%@ %@",obj2.contactName,obj2.contactSurname];
return [obj1Str compare:obj2Str];
}];
Also my object is,
@interface ContactListData : JsonData
@property(nonatomic,strong) NSString * contactName;
@property(nonatomic,strong) NSString * contactSurname;
@property(nonatomic,strong) NSString * contactPhoneNumber;
@property(nonatomic) BOOL isSelected;
@end
I was wondering that too, you could try what I learned on this post.
I used:
function highlightSelection() {_x000D_
var userSelection = window.getSelection();_x000D_
for(var i = 0; i < userSelection.rangeCount; i++) {_x000D_
highlightRange(userSelection.getRangeAt(i));_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function highlightRange(range) {_x000D_
var newNode = document.createElement("span");_x000D_
newNode.setAttribute(_x000D_
"style",_x000D_
"background-color: yellow; display: inline;"_x000D_
);_x000D_
range.surroundContents(newNode);_x000D_
}
_x000D_
<html>_x000D_
<body contextmenu="mymenu">_x000D_
_x000D_
<menu type="context" id="mymenu">_x000D_
<menuitem label="Highlight Yellow" onclick="highlightSelection()" icon="/images/comment_icon.gif"></menuitem>_x000D_
</menu>_x000D_
<p>this is text, select and right click to high light me! if you can`t see the option, please use this<button onclick="highlightSelection()">button </button><p>
_x000D_
you could also try it here: http://henriquedonati.com/projects/Extension/extension.html
xc
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.
sed '/pattern/ { N; s/.*\n//; q }; d'
It mostly depends on the (other) activity in the database. Operations like this effectively freeze the entire database for other sessions. Another consideration is the datamodel and the presence of constraints,triggers, etc.
My first approach is always: create a (temp) table with a structure similar to the target table (create table tmp AS select * from target where 1=0), and start by reading the file into the temp table. Then I check what can be checked: duplicates, keys that already exist in the target, etc.
Then I just do a "do insert into target select * from tmp" or similar.
If this fails, or takes too long, I abort it and consider other methods (temporarily dropping indexes/constraints, etc)
add this in web.config file
<configuration>
<appSettings>
<add key="ConnectionString" value="Your connection string which contains database id and password"/>
</appSettings>
</configuration>
.cs file
public ConnectionObjects()
{
string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
}
Hope this helps.
You should pre authenticate the token apis "/oauth/token"
extend ResourceServerConfigurerAdapter
and override configure function
to do this.
eg:
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/oauth/token").permitAll().
anyRequest().authenticated();
Here's a nice answer from the FAQ on the scipy.org website:
What advantages do NumPy arrays offer over (nested) Python lists?
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
and make sure there is no parent tags with position: relative in it
Include your IP address in your host file (C:\Windows\System32\drivers\etc\host) for the respective server:
Sample Entry:
10.100.101.102 server1.us.vijay.com Vijay's Server
The accepted answer definitely works, but somehow miss an important point.
The OP is asking for a dictionary sorted by it's keys
this is just not really possible and not what OrderedDict
is doing.
OrderedDict is maintaining the content of the dictionary in insertion order. First item inserted, second item inserted, etc.
>>> d = OrderedDict()
>>> d['foo'] = 1
>>> d['bar'] = 2
>>> d
OrderedDict([('foo', 1), ('bar', 2)])
>>> d = OrderedDict()
>>> d['bar'] = 2
>>> d['foo'] = 1
>>> d
OrderedDict([('bar', 2), ('foo', 1)])
Hencefore I won't really be able to sort the dictionary inplace, but merely to create a new dictionary where insertion order match key order. This is explicit in the accepted answer where the new dictionary is b.
This may be important if you are keeping access to dictionaries through containers. This is also important if you itend to change the dictionary later by adding or removing items: they won't be inserted in key order but at the end of dictionary.
>>> d = OrderedDict({'foo': 5, 'bar': 8})
>>> d
OrderedDict([('foo', 5), ('bar', 8)])
>>> d['alpha'] = 2
>>> d
OrderedDict([('foo', 5), ('bar', 8), ('alpha', 2)])
Now, what does mean having a dictionary sorted by it's keys ? That makes no difference when accessing elements by keys, this only matter when you are iterating over items. Making that a property of the dictionary itself seems like overkill. In many cases it's enough to sort keys() when iterating.
That means that it's equivalent to do:
>>> d = {'foo': 5, 'bar': 8}
>>> for k,v in d.iteritems(): print k, v
on an hypothetical sorted by key dictionary or:
>>> d = {'foo': 5, 'bar': 8}
>>> for k, v in iter((k, d[k]) for k in sorted(d.keys())): print k, v
Of course it is not hard to wrap that behavior in an object by overloading iterators and maintaining a sorted keys list. But it is likely overkill.
Given this piece of HTML code:
<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>
We can use this JavaScript:
function checkTabPress(e) {
'use strict';
var ele = document.activeElement;
if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
console.log(ele.href);
}
}
document.addEventListener('keyup', function (e) {
checkTabPress(e);
}, false);
I have bound an event listener to the document
element for the keyUp
event, which triggers a function to check if the Tab key was pressed (or technically, released).
The function checks the currently focused element and whether the NodeName
is a
. If so, it enters the if
block and, in my case, writes the value of the href
property to the JavaScript console.
Here's a jsFiddle
I totally agree with @jemmons:
But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.
//SUSPICIOUS EXAMPLE: __weak MyObject *weakSelf = self; [[SomeOtherObject alloc] initWithCompletion:^{ //By the time this gets called, "weakSelf" might be nil because it's not retained! [weakSelf doSomething]; }];
To overcome this problem one can define a strong reference over the weakSelf
inside the block:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
MyObject *strongSelf = weakSelf;
[strongSelf doSomething];
}];
You are not passing the array as copy. It is only a pointer pointing to the address where the first element of the array is in memory.
An ES6 version of the code provided by @user1012181:
const epochs = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
const getDuration = (timeAgoInSeconds) => {
for (let [name, seconds] of epochs) {
const interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
};
const timeAgo = (date) => {
const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
const {interval, epoch} = getDuration(timeAgoInSeconds);
const suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
};
Edited with @ibe-vanmeenen suggestions. (Thanks!)
This definitely requires regex:
Copy into Ruby IRB:
var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
url.match(VID_REGEX)[1]
See for all test cases: https://gist.github.com/blairanderson/b264a15a8faaac9c6318
Use CONCAT_WS().
SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users
WHERE firstlast = "Bob Michael Jones";
The first argument is the separator for the rest of the arguments.
In Windows we need to run $git difftool --tool-help
command to see the various options like:
'git difftool --tool=<tool>' may be set to one of the following:
vimdiff
vimdiff2
vimdiff3
The following tools are valid, but not currently available:
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff
Some of the tools listed above only work in a windowed
environment. If run in a terminal-only session, they will fail.
and we can add any of them(for example winmerge) like
$ git difftool --tool=winmerge
For configuring notepad++ to see files before committing:
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
and using $ git commit
will open the commit information in notepad++
In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below
val MY_CONSTANT = "Constants"
And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.
companion object{
const val MY_CONSTANT = "Constants"
}
You can use the ADB via a terminal to pass the file From Desktop to Emulator.
adb push <file-source-local> <destination-path-remote>
You can also copy file from emulator to Desktop
adb pull <file-source-remote> <destination-path>
How ever you can also use the Android Device Monitor to access files. Click on the Android Icon which can be found in the toolbar itself. It'll take few seconds to load. Once it's loaded, you can see a tab named "File Explorer". Now you could pull/push files from there.
IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.
After building the project right click on the project Debug > “Debug Configurations”, as shown below
In the “debugger” tab, ensure the “GDB command file” now points to your “.gdbinit” file. Else, input the path to your “.gdbinit” configuration file :
Click “Apply” and “Debug”. A native DOS command line should be launched as shown below
Solution
Angular2 developed on the ground of modern technologies like TypeScript and ES6.
So you can just do let copy = Object.assign({}, myObject)
.
Object assign - nice examples.
For nested objects :
let copy = JSON.parse(JSON.stringify(myObject))
It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)
public class UIutils {
private Activity mActivity;
public UIutils(Activity activity){
mActivity = activity;
}
public void showPhoto(Uri photoUri){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(photoUri, "image/*");
mActivity.startActivity(intent);
}
}
Then to use it just do this:
imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));
I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.
Use merge
, which is inner join by default:
pd.merge(df1, df2, left_index=True, right_index=True)
Or join
, which is left join by default:
df1.join(df2)
Or concat
, which is outer join by default:
pd.concat([df1, df2], axis=1)
Samples:
df1 = pd.DataFrame({'a':range(6),
'b':[5,3,6,9,2,4]}, index=list('abcdef'))
print (df1)
a b
a 0 5
b 1 3
c 2 6
d 3 9
e 4 2
f 5 4
df2 = pd.DataFrame({'c':range(4),
'd':[10,20,30, 40]}, index=list('abhi'))
print (df2)
c d
a 0 10
b 1 20
h 2 30
i 3 40
#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
a b c d
a 0 5 0 10
b 1 3 1 20
#default left join
df4 = df1.join(df2)
print (df4)
a b c d
a 0 5 0.0 10.0
b 1 3 1.0 20.0
c 2 6 NaN NaN
d 3 9 NaN NaN
e 4 2 NaN NaN
f 5 4 NaN NaN
#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
a b c d
a 0.0 5.0 0.0 10.0
b 1.0 3.0 1.0 20.0
c 2.0 6.0 NaN NaN
d 3.0 9.0 NaN NaN
e 4.0 2.0 NaN NaN
f 5.0 4.0 NaN NaN
h NaN NaN 2.0 30.0
i NaN NaN 3.0 40.0
Future version of node will allow you to fork a process and pass messages to it and Ryan has stated he wants to find some way to also share file handlers, so it won't be a straight forward Web Worker implementation.
At this time there is not an easy solution for this but it's still very early and node is one of the fastest moving open source projects I've ever seen so expect something awesome in the near future.
I just found a solution for this.
for those who are not satisfied with the given answers can try this approach with flexbox
CSS
.myFlexContainer {
display: flex;
width: 100%;
}
.myFlexChild {
width: 100%;
display: flex;
/*
* set this property if this is set to column by other css class
* that is used by your target element
*/
flex-direction: row;
/*
* necessary for our goal
*/
flex-wrap: wrap;
height: 500px;
}
/* the element you want to put at the bottom */
.myTargetElement {
/*
* will not work unless flex-wrap is set to wrap and
* flex-direction is set to row
*/
align-self: flex-end;
}
HTML
<div class="myFlexContainer">
<div class="myFlexChild">
<p>this is just sample</p>
<a class="myTargetElement" href="#">set this to bottom</a>
</div>
</div>
@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:
(true) ? 1 : 0
Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \
line-continuation symbol at the end of a line and Ruby will be happy:
(true) \
? 1 \
: 0
This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.
It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:
(true) ?
1 :
0
I think that leads to really hard to read code as the conditional test and/or results get longer.
I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..
' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.
Why have you put brackets around
true
?
Consider the OP's example:
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
Wrapping the conditional test helps make it more readable because it visually separates the test:
<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>
Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:
<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
: question.question
%>
Or, more written more idiomatically:
<% question = if (question.size > 20)
question.question.slice(0, 20) + "..."
else
question.question
end
%>
It'd be easy to argument that readability suffers badly from question.question
too.
The correct way to go from C:\...\Admin
to D:\Docs\Java
drive, is the following command :
cd /d d:\Docs\Java
If you're somewhere random on your D:\
drive, and you want to go to the root of your drive, you can use this command :
cd d:\
If you're somewhere random on your D:\
drive, and you want to go to a specific folder on your drive, you can use this command :
cd d:\Docs\Java
If you're on a different drive, and you want to go to the root of your D:\
drive, you can use this command :
cd /d d:\
If you're on a different drive, and you want to go to a specific folder on your D:
drive, you can use this command :
cd /d d:\Docs\Java
If you're on a different drive, and you want to go to the last open folder of you D:
drive, you can use this command :
cd /d d:
As a shorthand for cd /d d:
, you can also use this command :
d:
... also for Debian GNU/Linux 6.0 :)
export PATH=$PATH:/var/lib/gems/1.8/bin
If you have multiple markers you can use this simple solution to close a previously opened marker when clicking a new marker:
var infowindow = new google.maps.InfoWindow({
maxWidth: (window.innerWidth - 160),
content: content
});
marker.infowindow = infowindow;
var openInfoWindow = '';
marker.addListener('click', function (map, marker) {
if (openInfoWindow) {
openInfoWindow.close();
}
openInfoWindow = this.infowindow;
this.infowindow.open(map, this);
});
Below code is work well in my project Swift5. try load url by WKWebView below:
private func loadURL(urlString: String) {
let url = URL(string: urlString)
guard let urlToLoad = url else { fatalError("Cannot find any URL") }
// Cookies configuration
var urlRequest = URLRequest(url: urlToLoad)
if let cookies = HTTPCookieStorage.shared.cookies(for: urlToLoad) {
let headers = HTTPCookie.requestHeaderFields(with: cookies)
for header in headers { urlRequest.addValue(header.value, forHTTPHeaderField: header.key) }
}
webview.load(urlRequest)
}
Just for future needs.
In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window
to make it work.
<Grid Name="myGrid" Height="437.274">
<TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>
Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.
And by the way,
UPDATE: As of Bootstrap 3.0, the input-*
classes described below for setting the width of input elements were removed. Instead use the col-*
classes to set the width of input elements. Examples are provided in the documentation.
In Bootstrap 2.3, you'd use the input classes for setting the width.
<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?
Do a find for "Control sizing" for examples in the documentation.
But for height I think you'd still use the rows attribute.
According to MSDN, it's 260 characters. It includes "<NUL>"
-the invisible terminating null character, so the actual length is 259.
But read the article, it's a bit more complicated.
if you want to pass multiple parameters then you can create model instead of passing multiple parameters.
in case you dont want to pass any parameter then you can skip as well in it, and your code will look neat and clean.
If using virtualenv, look for the build
directory under your environments root.
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.
A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.
And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.
Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.
Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.
Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).
Here is a one liner doing the work:
const camelCaseIt = string => string.toLowerCase().trim().split(/[.\-_\s]/g).reduce((string, word) => string + word[0].toUpperCase() + word.slice(1));
It splits the lower-cased string based on the list of characters provided in the RegExp [.\-_\s]
(add more inside the []!) and returns a word array . Then, it reduces the array of strings to one concatenated string of words with uppercased first letters. Because the reduce has no initial value, it will start uppercasing first letters starting with the second word.
If you want PascalCase, just add an initial empty string ,'')
to the reduce method.
Not only Inside methods, it can be used inside classes also.
class Calculator
{
public static int Sum(int x,int y) => x + y;
public static Func<int, int, int> Add = (x, y) => x + y;
public static Action<int,int> DisplaySum = (x, y) => Console.WriteLine(x + y);
}
you can just use post
to post your json.
values := map[string]string{"username": username, "password": password}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))
Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This is intended as a drop-in replacement for unistd.h on Windows.
* Please add functionality as neeeded.
* https://stackoverflow.com/a/826027/1202830
*/
#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */
#define srandom srand
#define random rand
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
//#define X_OK 1 /* execute permission - unsupported in windows*/
#define F_OK 0 /* Test for existence. */
#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */
#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* unistd.h */
Other answers are old, could not get a good answer.
Below example is for object literals, helps how both can complement each other, and how it cannot complement each other (therefore difference):
var obj1 = { a: 1, b: { b1: 1, b2: 'b2value', b3: 'b3value' } };
// overwrite parts of b key
var obj2 = {
b: {
...obj1.b,
b1: 2
}
};
var res2 = Object.assign({}, obj1, obj2); // b2,b3 keys still exist
document.write('res2: ', JSON.stringify (res2), '<br>');
// Output:
// res2: {"a":1,"b":{"b1":2,"b2":"b2value","b3":"b3value"}} // NOTE: b2,b3 still exists
// overwrite whole of b key
var obj3 = {
b: {
b1: 2
}
};
var res3 = Object.assign({}, obj1, obj3); // b2,b3 keys are lost
document.write('res3: ', JSON.stringify (res3), '<br>');
// Output:
// res3: {"a":1,"b":{"b1":2}} // NOTE: b2,b3 values are lost
Several more small examples here, also for array & object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
When an error occurs, the execution will continue on the next line without interrupting the script.
You must specify that the friend is a template function:
MyClass<T>& operator+=<>(const MyClass<T>& classObj);
See this C++ FAQ Lite answer for details.
You are looking for the update method
dic0.update( dic1 )
print( dic0 )
gives
{'dic0': 0, 'dic1': 1}
Add following NuGet packages to your project:
Microsoft.WindowsAPICodePack-Shell
by MicrosoftMicrosoft.WindowsAPICodePack-Core
by Microsoftusing Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
string filePath = @"C:\temp\example.docx";
var file = ShellFile.FromFilePath(filePath);
// Read and Write:
string[] oldAuthors = file.Properties.System.Author.Value;
string oldTitle = file.Properties.System.Title.Value;
file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
file.Properties.System.Title.Value = "Example Title";
// Alternate way to Write:
ShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();
propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
propertyWriter.Close();
Important:
The file must be a valid one, created by the specific assigned software. Every file type has specific extended file properties and not all of them are writable.
If you right-click a file on desktop and cannot edit a property, you wont be able to edit it in code too.
Example:
Author
or Title
property.So just make sure to use some try
catch
Further Topic: MSDN: Implementing Property Handlers
You can install the Microsoft Report Viewer 2012 Runtime and change your references so they point to the ones installed by the runtime.
http://www.microsoft.com/en-gb/download/details.aspx?id=35747
I have installed the runtime without it asking for SQL Server 2012. Before installing try uninstalling any previous versions of report viewer.
str.matches(regex)
behaves like Pattern.matches(regex, str)
which attempts to match the entire input sequence against the pattern and returns
true
if, and only if, the entire input sequence matches this matcher's pattern
Whereas matcher.find()
attempts to find the next subsequence of the input sequence that matches the pattern and returns
true
if, and only if, a subsequence of the input sequence matches this matcher's pattern
Thus the problem is with the regex. Try the following.
String test = "User Comments: This is \t a\ta \ntest\n\n message \n";
String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find()); //true
String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2)); //true
Thus in short, the (\\W)*(\\S)*
portion in your first regex matches an empty string as *
means zero or more occurrences and the real matched string is User Comments:
and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W
matches a non word character, ie [^a-zA-Z0-9_]
and the first character is T
, a word character.
You may use this simple plugin:
(function ($) {
$.fn.replaceClass = function (pFromClass, pToClass) {
return this.removeClass(pFromClass).addClass(pToClass);
};
}(jQuery));
Usage:
$('.divFoo').replaceClass('colored','blackAndWhite');
Before:
<div class="divFoo colored"></div>
After:
<div class="divFoo blackAndWhite"></div>
Note: you may use various space separated classes.
a.button a:hover
means "a link that's being hovered over that is a child of a link with the class button
".
Go instead for a.button:hover
.
Below code will count Message from 0 to 137 each 0.3 second replacing previous number.
Number of symbol to backstage = number of digits.
stream = sys.stdout
for i in range(137):
stream.write('\b' * (len(str(i)) + 10))
stream.write("Message : " + str(i))
stream.flush()
time.sleep(0.3)
One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.
In their book The Practice of Programming (which is well worth reading), Kernighan and Pike discuss this problem, and they solve it by using snprintf()
to create the string with the correct buffer size for passing to the scanf()
family of functions. In effect:
int scanner(const char *data, char *buffer, size_t buflen)
{
char format[32];
if (buflen == 0)
return 0;
snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
return sscanf(data, format, buffer);
}
Note, this still limits the input to the size provided as 'buffer'. If you need more space, then you have to do memory allocation, or use a non-standard library function that does the memory allocation for you.
Note that the POSIX 2008 (2013) version of the scanf()
family of functions supports a format modifier m
(an assignment-allocation character) for string inputs (%s
, %c
, %[
). Instead of taking a char *
argument, it takes a char **
argument, and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf()
function fails to satisfy all the conversion specifications, then all the memory it allocated for %ms
-like conversions is freed before the function returns.
IoC/DI is a design concept, but unfortunately it's often taken as a concept that applies to certain languages (or typing systems). I'd love to see dependency injection containers become far more popular in Python. There's Spring, but that's a super-framework and seems to be a direct port of the Java concepts without much consideration for "The Python Way."
Given Annotations in Python 3, I decided to have a crack at a full featured, but simple, dependency injection container: https://github.com/zsims/dic . It's based on some concepts from a .NET dependency injection container (which IMO is fantastic if you're ever playing in that space), but mutated with Python concepts.
Execution Timeout is 90 seconds for .NET
Framework 1.0 and 1.1, 110 seconds otherwise.
If you need to change defult settings you need to do it in your web.config
under <httpRuntime>
<httpRuntime executionTimeout = "number(in seconds)"/>
But Remember:
This time-out applies only if the debug attribute in the compilation element is False.
Have look at in detail about compilation Element
Have look at this document about httpRuntime Element
hasOwnProperty() is a nice property to validate object keys. Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true
The correct syntax is:
import sampleModule = require('modulename');
or
import * as sampleModule from 'modulename';
Then compile your TypeScript with --module commonjs
.
If the package doesn't come with an index.d.ts
file and its package.json
doesn't have a "typings"
property, tsc
will bark that it doesn't know what 'modulename'
refers to. For this purpose you need to find a .d.ts
file for it on http://definitelytyped.org/, or write one yourself.
If you are writing code for Node.js you will also want the node.d.ts
file from http://definitelytyped.org/.
I use GenMyModel, first released in 2013. It's a real UML modeler, not a drawing tool. Your diagrams are UML-compliant, generate code and can be exported as UML/XMI files. It's web-based and free so it matches your criteria.
The C Programming Language (K&R) would have you check for null == ptr to avoid an accidental assignment.
To anyone else who finds this older question, you can now download all old versions.
Xcode
-> Preferences
-> Components
(Click on Simulators tab).
Install all the versions you want/need.
To show all installed simulators:
Target -> In dropdown "deployment target" choose the installed version with lowest version nr.
You should now see all your available simulators in the dropdown.
I use GUIDs as random keys for database type operations.
The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..
Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).
import base64
import uuid
# get a UUID - URL safe, Base64
def get_a_uuid():
r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
return r_uuid.replace('=', '')
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
sort file | sponge file
This is in the following Fedora package:
moreutils : Additional unix utilities
Repo : fedora
Matched from:
Filename : /usr/bin/sponge
First you have to include library like:
using System.Runtime.Serialization.Json;
DataContractJsonSerializer desc = new DataContractJsonSerializer(typeof(BlogSite));
string json = "{\"Description\":\"Share knowledge\",\"Name\":\"zahid\"}";
using (var ms = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(json)))
{
BlogSite b = (BlogSite)desc.ReadObject(ms);
Console.WriteLine(b.Name);
Console.WriteLine(b.Description);
}
You are almost there. (note change in the return value of FindWindow declaration). I'd recommend using RegisterWindowMessage in this case so you don't have to worry about the ins and outs of WM_USER.
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
public void button1_Click(object sender, EventArgs e)
{
// this would likely go in a constructor because you only need to call it
// once per process to get the id - multiple calls in the same instance
// of a windows session return the same value for a given string
uint id = RegisterWindowMessage("MyUniqueMessageIdentifier");
IntPtr WindowToFind = FindWindow(null, "Form1");
Debug.Assert(WindowToFind != IntPtr.Zero);
SendMessage(WindowToFind, id, IntPtr.Zero, IntPtr.Zero);
}
And then in your Form1 class:
class Form1 : Form
{
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
private uint _messageId = RegisterWindowMessage("MyUniqueMessageIdentifier");
protected override void WndProc(ref Message m)
{
if (m.Msg == _messageId)
{
// do stuff
}
base.WndProc(ref m);
}
}
Bear in mind I haven't compiled any of the above so some tweaking may be necessary.
Also bear in mind that other answers warning you away from SendMessage
are spot on. It's not the preferred way of inter module communication nowadays and genrally speaking overriding the WndProc
and using SendMessage/PostMessage
implies a good understanding of how the Win32 message infrastructure works.
But if you want/need to go this route I think the above will get you going in the right direction.
use the below commands to install oracle java8 through terminal
Step -1) Visit Oracle JDK download page, look for RPM version
Step -2) Download oracle java 8 using the below command wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.rpm
Step -3) Install the java8 using below command sudo yum localinstall jdk-8u121-linux-x64.rpm Now the JDK should be installed at /usr/java/jdk1.8.0_121 Step -4) Remove the downloaded .rpm file to utilize the space. rm jdk-8u121-linux-x64.rpm
Step -5) Verify the java by using command java -version
Step -6) If the CentOS has multiple JDK installed, you can use the alternatives command to set the default java sudo alternatives --config java
Step -7)Optional set JAVA_HOME Environment variables. copy the path of jdk install i.e /usr/java/jdk1.8.0_121 use below command to export java home export JAVA_HOME=/usr/java/jdk1.8.0_121 export PATH=$PATH:$JAVA_HOME
int
is a primitive type that represent an integer. whereas Integer
is an Object that wraps int
. The Integer
object gives you more functionality, such as converting to hex, string, etc.
You can also use OOP concepts with Integer
. For example, you can use Integer for generics (i.e. Collection
).<Integer>
This query will use index if you have it for signup_date
field
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)
With Jquery... You can add class to html elements like this:
$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');
nameclassorid no point or # at the beginning
There are a lot of answers here suggesting something like [value=""]
but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:
$("input[id^='something'][value='']")
but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were
$("input[id^='something']").not("[value!='']")
and
$("input[id^='something']:not([value!=''])")
but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.
Into Preferences > Settings - Users
File : Preferences.sublime-settings
Write this :
"show_encoding" : true,
It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3
I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.
In the end, I had to do a "manual" conversion:
List<ListItem> items = new ArrayList<ListItem>();
for (ListItem item: itemsArray) {
items.add(item);
}
I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.
Using Form Model (Reactive Forms)
--- Html code--
<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
<mat-select placeholder="Category" formControlName="patientCategory">
<mat-option>--</mat-option>
<mat-option *ngFor="let category of patientCategories" [value]="category">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
----ts code ---
ngOnInit() {
this.patientCategory = this.fb.group({
patientCategory: [null, Validators.required]
});
const toSelect = "Your Default Value";
this.patientCategory.get('patientCategory').setValue(toSelect);
}
With out form Model
--- html code --
<mat-form-field>
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>
---- ts code -- selected = 'option1'; Here take care about type of the value assigning
First, I get the high side of the char. After, get the low side. Convert all of things in HexString and put the prefix.
int hs = (int) c >> 8;
int ls = hs & 0x000F;
String highSide = Integer.toHexString(hs);
String lowSide = Integer.toHexString(ls);
lowSide = Integer.toHexString(hs & 0x00F0);
String hexa = Integer.toHexString( (int) c );
System.out.println(c+" = "+"\\u"+highSide+lowSide+hexa);
You can try these some steps:
Stop Mysql Service 1st
sudo /etc/init.d/mysql stop
Login as root without password
sudo mysqld_safe --skip-grant-tables &
After login mysql terminal you should need execute commands more:
use mysql;
UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';
flush privileges;
sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown
After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04
Another option is to use uniqueResultOptional() method, which gives you Optional in result:
String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());
Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();
Here's @Daniel Vérité's function with progress reporting functionality. It reports progress in three ways:
_
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{public}',
progress_seq text default NULL
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
DECLARE
currenttable text;
columnscount integer;
foundintables text[];
foundincolumns text[];
begin
currenttable='';
columnscount = (SELECT count(1)
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE')::integer;
PERFORM setval(progress_seq::regclass, columnscount);
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE'
LOOP
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
) INTO rowctid;
IF rowctid is not null THEN
RETURN NEXT;
foundintables = foundintables || tablename;
foundincolumns = foundincolumns || columnname;
RAISE NOTICE 'FOUND! %, %, %, %', schemaname,tablename,columnname, rowctid;
END IF;
IF (progress_seq IS NOT NULL) THEN
PERFORM nextval(progress_seq::regclass);
END IF;
IF(currenttable<>tablename) THEN
currenttable=tablename;
IF (progress_seq IS NOT NULL) THEN
RAISE NOTICE 'Columns left to look in: %; looking in table: %', currval(progress_seq::regclass), tablename;
EXECUTE 'COPY (SELECT unnest(string_to_array(''Current table (column ' || columnscount-currval(progress_seq::regclass) || ' of ' || columnscount || '): ' || tablename || '\n\nFound in tables/columns:\n' || COALESCE(
(SELECT string_agg(c1 || '/' || c2, '\n') FROM (SELECT unnest(foundintables) AS c1,unnest(foundincolumns) AS c2) AS t1)
, '') || ''',''\n''))) TO ''c:\WINDOWS\temp\' || progress_seq || '.txt''';
END IF;
END IF;
END LOOP;
END;
$$ language plpgsql;
Important Note: Alert of Future Deprecation.
As of iOS 9.0, the API functions description for:
AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)
includes the following note:
This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or
AudioServicesPlaySystemSoundWithCompletion instead.
The right way to go will be using any of these two:
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)
or
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
//your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}
remember to
import AVFoundation
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
So.. I was also looking into this matter and saw that most of the answers here are asking to fade the container element, not the actual background-image. Then a hack crossed my mind. We can give multiple background right? what if we overlay other color and make it transparent, like code below-
background: url("//unsplash.it/500/400") rgb(255, 255, 255, 0.5) no-repeat center;
This code actually works stand alone. Try it. We gave a bg image and asked other white color with transparency on top of the image and Voila. TIP- we can give different colors and transparencies to get different filter kind of effect.
No, there is no inline function in java. Yes, you can use a public static method anywhere in the code when placed in a public class. The java compiler may do inline expansion on a static or final method, but that is not guaranteed.
Typically such code optimizations are done by the compiler in combination with the JVM/JIT/HotSpot for code segments used very often. Also other optimization concepts like register declaration of parameters are not known in java.
Optimizations cannot be forced by declaration in java, but done by compiler and JIT. In many other languages these declarations are often only compiler hints (you can declare more register parameters than the processor has, the rest is ignored).
Declaring java methods static, final or private are also hints for the compiler. You should use it, but no garantees. Java performance is dynamic, not static. First call to a system is always slow because of class loading. Next calls are faster, but depending on memory and runtime the most common calls are optimized withinthe running system, so a server may become faster during runtime!
One very very important difference. Since Observable is just a function, it does not have any state, so for every new Observer, it executes the observable create code again and again. This results in:
The code is run for each observer . If its a HTTP call, it gets called for each observer
This causes major bugs and inefficiencies
BehaviorSubject (or Subject ) stores observer details, runs the code only once and gives the result to all observers .
Ex:
JSBin: http://jsbin.com/qowulet/edit?js,console
// --- Observable ---_x000D_
let randomNumGenerator1 = Rx.Observable.create(observer => {_x000D_
observer.next(Math.random());_x000D_
});_x000D_
_x000D_
let observer1 = randomNumGenerator1_x000D_
.subscribe(num => console.log('observer 1: '+ num));_x000D_
_x000D_
let observer2 = randomNumGenerator1_x000D_
.subscribe(num => console.log('observer 2: '+ num));_x000D_
_x000D_
_x000D_
// ------ BehaviorSubject/ Subject_x000D_
_x000D_
let randomNumGenerator2 = new Rx.BehaviorSubject(0);_x000D_
randomNumGenerator2.next(Math.random());_x000D_
_x000D_
let observer1Subject = randomNumGenerator2_x000D_
.subscribe(num=> console.log('observer subject 1: '+ num));_x000D_
_x000D_
let observer2Subject = randomNumGenerator2_x000D_
.subscribe(num=> console.log('observer subject 2: '+ num));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.3/Rx.min.js"></script>
_x000D_
Output :
"observer 1: 0.7184075243594013"
"observer 2: 0.41271850211336103"
"observer subject 1: 0.8034263165479893"
"observer subject 2: 0.8034263165479893"
Observe how using Observable.create
created different output for each observer, but BehaviorSubject
gave the same output for all observers. This is important.
Other differences summarized.
?????????????????????????????????????????????????????????????????????????????
? Observable ? BehaviorSubject/Subject ?
?????????????????????????????????????????????????????????????????????????????
? Is just a function, no state ? Has state. Stores data in memory ?
?????????????????????????????????????????????????????????????????????????????
? Code run for each observer ? Same code run ?
? ? only once for all observers ?
?????????????????????????????????????????????????????????????????????????????
? Creates only Observable ?Can create and also listen Observable?
? ( data producer alone ) ? ( data producer and consumer ) ?
?????????????????????????????????????????????????????????????????????????????
? Usage: Simple Observable with only ? Usage: ?
? one Obeserver. ? * Store data and modify frequently ?
? ? * Multiple observers listen to data ?
? ? * Proxy between Observable and ?
? ? Observer ?
?????????????????????????????????????????????????????????????????????????????
open div
then put
style="width:100% ; margin:0px auto;"
image
tag (or) content
close div
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
This is the example for where I have removed the character - from the String.
Start to look at the execution plans to see the differences in how the SQl Server will interpret them. You can also use Profiler to actually run the queries multiple times and get the differnce.
I would not expect these to be so horribly different, where you can get get real, large performance gains in using joins instead of subqueries is when you use correlated subqueries.
EXISTS is often better than either of these two and when you are talking left joins where you want to all records not in the left join table, then NOT EXISTS is often a much better choice.
In my case, I had already generated an APK file using the command ionic cordova build android --prod
and I needed to get the SHA-1 fingerprint for the already existing APK file. Here's how I got it by running the following command in the App directory:
keytool -list -printcert -jarfile app-debug.apk
So, I basically ran the above command in the following app location:
C:\myApp\platforms\android\app\build\outputs\apk\debug>keytool -list -printcert -jarfile app-debug.apk
This gave me the SHA1 fingerprint as: 7B:6B:AD:...
Hope this helps someone!
At first sight, yield return is a .NET sugar to return an IEnumerable.
Without yield, all the items of the collection are created at once:
class SomeData
{
public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas()
{
return new List<SomeData> {
new SomeData(),
new SomeData(),
new SomeData()
};
}
}
Same code using yield, it returns item by item:
class SomeData
{
public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas()
{
yield return new SomeData();
yield return new SomeData();
yield return new SomeData();
}
}
The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.
The yield operator allows the creation of items as it is demanded. That's a good reason to use it.
I think what you need might be simply:
\d( \w)?
Note that your regex would have worked too if it was written as \d \w|\d
instead of \d|\d \w
.
This is because in your case, once the regex matches the first option, \d
, it ceases to search for a new match, so to speak.
The simplest way is: HTML:
<header>
<h1>Website</h1>
</header>
CSS:
header{
position: sticky;
top: 0;
}
$mylabel.text( $mylabel.text().replace('-', '') );
Since text()
gets the value, and text( "someValue" )
sets the value, you just place one inside the other.
Would be the equivalent of doing:
var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );
EDIT:
I hope I understood the question correctly. I'm assuming $mylabel
is referencing a DOM element in a jQuery object, and the string is in the content of the element.
If the string is in some other variable not part of the DOM, then you would likely want to call the .replace()
function against that variable before you insert it into the DOM.
Like this:
var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );
or a more verbose version:
var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );
const rotations = ([l, ...ls], right=[]) =>_x000D_
l ? [[l, ...ls, ...right], ...rotations(ls, [...right, l])] : []_x000D_
_x000D_
const permutations = ([x, ...xs]) =>_x000D_
x ? permutations(xs).flatMap((p) => rotations([x, ...p])) : [[]]_x000D_
_x000D_
console.log(permutations("cat"))
_x000D_
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
The following article helped me to combine two plots generated by ggplot2 on a single row:
Multiple graphs on one page (ggplot2) by Cookbook for R
And here is what the code may look like in this case:
p1 <-
ggplot() + aes(mns)+ geom_histogram(aes(y=..density..), binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1) + geom_density(alpha=.2)
p2 <-
ggplot() + aes(mns)+ geom_histogram( binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1)
multiplot(p1,p2,cols=2)
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values inside the started activity, you must call the get[type]Extra()
on the same intent:
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra()
instead etc.
Now you can use your parameters like you normally would.
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
A Stack is a LIFO (Last In First Out) data structure. The push and pop operations are simple. Push puts something on the stack, pop takes something off. You put onto the top, and take off the top, to preserve the LIFO order.
edit -- corrected from FIFO, to LIFO. Facepalm!
to illustrate, you start with a blank stack
|
then you push 'x'
| 'x'
then you push 'y'
| 'x' 'y'
then you pop
| 'x'
This code worked for me:
private static String getJarPath() throws IOException, URISyntaxException {
File f = new File(LicensingApp.class.getProtectionDomain().().getLocation().toURI());
String jarPath = f.getCanonicalPath().toString();
String jarDir = jarPath.substring( 0, jarPath.lastIndexOf( File.separator ));
return jarDir;
}
I assume the original question included how does Express use this environment variable.
Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error
, to avoid leaking implementation details to the world.
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
This is a variant of the list comprehension answer given by @psun.
By switching the output value, you can actually extract the matching pattern from the list comprehension (something not possible with the any()
approach by @Lauritz-v-Thaulow)
extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'http://.../foo.doc'
print [extension for extension in extensionsToCheck if(extension in url_string)]
['.doc']`
You can furthermore insert a regular expression if you want to collect additional information once the matched pattern is known (this could be useful when the list of allowed patterns is too long to write into a single regex pattern)
print [re.search(r'(\w+)'+extension, url_string).group(0) for extension in extensionsToCheck if(extension in url_string)]
['foo.doc']
If you're calling native apps, you need to worry about [Environment]::CurrentDirectory
not about PowerShell's $PWD
current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.
In a script, you can do this:
$CWD = [Environment]::CurrentDirectory
Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
## Your script code calling a native executable
Pop-Location
# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD
There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.
Two notes about the reason why this is not set by PowerShell automatically:
$PWD
present working directory, but there's only one process, and only one Environment.$PWD
isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:
[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem
Bind-address XXX.XX.XX.XXX in /etc/my.cnf
comment line:
or
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
quit;
add firewall rule:
iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT
How about:
String.prototype.strcmp = function(s) {
if (this < s) return -1;
if (this > s) return 1;
return 0;
}
Then, to compare s1 with 2:
s1.strcmp(s2)
Strange that this project hasn't been mentioned: AndroidFFmpeg from Appunite
It has quite detailed step-by-step instructions to copy/paste to command line, for lazy people like me ))
In my case updating Microsoft.CodeDom.Providers.DotNetCompilerPlatform
and Microsoft.Net.Compilers
caused the problem.
Deleting bin
, obj
, and packages
folders and restarting Visual Studio 2015 solved the problem for me.
It can be better if you set the a element in this way
display:block;
and then by css sprites set your over background
Edit: check this example out http://jsfiddle.net/steweb/dTwtk/
You get the index number of the row in the datagridview using northwind database employees tables as an example:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString();
string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: "
+ cellValue.ToString());
}
}
}
the result will show you index number of record and the contents of the second table column in datagridview:
You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++) {
var start;
if (i < r) {
start = c;
} else {
start = 0;
myArray.push([]);
}
for (var j = start; j < cols; j++) {
myArray[i].push(0);
}
}
The easiest way to use it is as following:
currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");
where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date
output: Sun Apr 14 16:11:48 EEST 2013
Notes: HH vs hh - HH refers to 24h time format - hh refers to 12h time format
Call plt.show()
after plt.savefig(fig)
and your problem should be solved.
Children inherit opacity. It'd be weird and inconvenient if they didn't.
You can use a translucent PNG file for your background image, or use an RGBa (a for alpha) color for your background color.
Example, 50% faded black background:
<div style="background-color:rgba(0, 0, 0, 0.5);">_x000D_
<div>_x000D_
Text added._x000D_
</div>_x000D_
</div>
_x000D_
Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml
<properties>
...
<jackson.version>2.5.2</jackson.version>
</properties>
<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
my old version was '2.2.3'
This will print all the keys and values on localStorage:
ES6:
for (let i=0; i< localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage[key];
console.log(`localStorage ${key}: ${value}`);
}
SELECT ID, Col1, Col2, Col3,
(SELECT MIN(Col) FROM (VALUES (Col1), (Col2), (Col3)) AS X(Col)) AS TheMin
FROM Table
You can create a jQuery object from a JSON object:
$.getJSON(url, data, function(json) {
$(json).each(function() {
/* YOUR CODE HERE */
});
});
You are just creating your array incorrectly. You could use http_build_query:
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
$fields_string = http_build_query($fields);
So, the entire code that you could use would be:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
%(letter) denotes the format type of the replacement text. %s specifies a string, %d an integer, and %c a char.
I found my own mistake, I did not add log file name:
ErrorLog /var/log/apache2
And this path:
Directory "/usr/share/doc/"
Did not contain website sources.
After I changed these two, all worked. Interestingly, apache did not issue any errors, just did not open my website silently on my Mac OS Sierra.
Try:
using System.Diagnostics;
ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
string processpathfilename;
string processmodulename;
if (modules.Count > 0) {
processpathfilename = modules[0].FileName;
processmodulename= modules[0].ModuleName;
} else {
throw new ExecutionEngineException("Something critical occurred with the running process.");
}
You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:
var lr = new LocalReport
{
ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
EnableExternalImages = true
};
lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
(
"PDF",
@"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
out mimeType,
out encoding,
out extension,
out streams,
out warnings
);
var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
var idx = 0;
while (File.Exists(saveAs))
{
idx++;
saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}
using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
stream.Write(renderedBytes, 0, renderedBytes.Length);
stream.Close();
}
lr.Dispose();
You can also add parameters: (lr.SetParameter())
, handle subreports: (lr.SubreportProcessing+=YourHandler)
, or pretty much anything you can think of.
The easiest solution I found for this so far is the Non-Sucking Service Manager
Usage would be
nssm install <servicename> "C:\Program Files\Java\jre7\java.exe" "-jar <path-to-jar-file>"
Use the built in "InternalServerError" method (available in ApiController):
return InternalServerError();
//or...
return InternalServerError(new YourException("your message"));
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
display: flex;_x000D_
flex-flow:column;_x000D_
height: 100%;_x000D_
background: white;_x000D_
}_x000D_
_x000D_
.child-top {_x000D_
flex: 0 1 auto;_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.child-bottom {_x000D_
flex: 1 1 auto;_x000D_
background: green;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child-top">_x000D_
This child has just a bit of content_x000D_
</div>_x000D_
<div class="child-bottom">_x000D_
And this one fills the rest_x000D_
</div>_x000D_
</div>
_x000D_
Take these two scenarios:
Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );
If opt
doesn't contain a value, the two are indeed equivalent. But if opt
does contain a value, how many Foo
objects will be created?
P.s.: of course in this example the difference probably wouldn't be measurable, but if you have to obtain your default value from a remote web service for example, or from a database, it suddenly becomes very important.
If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.
Have not run any benchmarks but I assume it is not the peak of efficiency.
static char ByteToAscii(const char *input) {
char singleChar, out;
memcpy(&singleChar, input, 2);
sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
return out;
}
int HexStringToAscii(const char *input, unsigned int length,
char **output) {
int mIndex, sIndex = 0;
char buffer[length];
for (mIndex = 0; mIndex < length; mIndex++) {
sIndex = mIndex * 2;
char b = ByteToAscii(&input[sIndex]);
memcpy(&buffer[mIndex], &b, 1);
}
*output = strdup(buffer);
return 0;
}
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
you can also put labels inside plot:
plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)
you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.
There are a lot excellent answers here, but I want to touch on something I didn't see mentioned: Object oriented design is about empowering objects.
You want to encapsulate all your rules, additional work and internal details inside an appropriate object. In this way other objects interacting with this one don't have to worry about it all. In fact, you want to go a step further and actively prevent other objects from bypassing these internals.
When you inherit from List
, all other objects can see you as a List. They have direct access to the methods for adding and removing players. And you'll have lost your control; for example:
Suppose you want to differentiate when a player leaves by knowing whether they retired, resigned or were fired. You could implement a RemovePlayer
method that takes an appropriate input enum. However, by inheriting from List
, you would be unable to prevent direct access to Remove
, RemoveAll
and even Clear
. As a result, you've actually disempowered your FootballTeam
class.
Additional thoughts on encapsulation... You raised the following concern:
It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count.
You're correct, that would be needlessly verbose for all clients to use you team. However, that problem is very small in comparison to the fact that you've exposed List Players
to all and sundry so they can fiddle with your team without your consent.
You go on to say:
It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam".
You're wrong about the first bit: Drop the word 'list', and it's actually obvious that a team does have players.
However, you hit the nail on the head with the second. You don't want clients calling ateam.Players.Add(...)
. You do want them calling ateam.AddPlayer(...)
. And your implemention would (possibly amongst other things) call Players.Add(...)
internally.
Hopefully you can see how important encapsulation is to the objective of empowering your objects. You want to allow each class to do its job well without fear of interference from other objects.
Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:
var someval = document.getElementById('something')
if (someval && someval.value <> '') {
I know for there's Fluid and Prism (there are others, that's the one I used to use) that let you load a website into what looks like a standalone app.
In Chrome, you can create desktop shortcuts for websites. (you do that from within Chrome, you can't/shouldn't package that with your app) Chrome Frame is different:
Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.
You'd need to have some sort of wrapper like that for your webapp, and then the rest is the web technologies you're used to. You can use HTML5 local storage to store data while the app is offline. I think you might even be able to work with SQLite.
I don't know how you would go about accessing OS specific features, though. What I described above has the same limitations as any "regular" website. Hopefully this gives you some sort of guidance on where to start.
In case the remote repository is not empty (this is the case if you are using IBM DevOps on hub.jazz.net) then you need to use the following sequence:
cd <localDir>
git init
git add -A .
git pull <url> master
git commit -m "message"
git remote add origin <url>
git push
EDIT 30th Jan 17: Please see comments below, make sure you are on the correct repo!
The first line of link below saved my day:
To add values to options from your project’s build settings, prepend the value list with $(inherited).
https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods#faq
Also, do not forget to insert this line at the beginning of your pod file:
platform :iOS, '5.0'
Multi-line strings are possible as of Swift 4.0, but there are some rules:
"""
."""
should also start on its own line.Other than that, you're good to go! Here's an example:
let longString = """
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three
quotes also on a line of their own.
Multi-line strings also let you write "quote marks"
freely inside your strings, which is great!
"""
See what's new in Swift 4 for more information.
The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsThe difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset
allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.
Read IFrames security summary.
As aditional information on @Quentin answer, and as he rightly says,
background
CSS property itself, is a shorthand for:
background-color
background-image
background-repeat
background-attachment
background-position
That's mean, you can group all styles in one, like:
background: red url(../img.jpg) 0 0 no-repeat fixed;
This would be (in this example):
background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none;
and all the others to the initial
state (as they are not being declared).
So, background:none;
is:
background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
Now, when you define only the color (in your case transparent
) then you are basically saying:
background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
I repeat, as @Quentin rightly says the default
transparent
and none
values in this case are the same, so in your example and for your original question, No, there's no difference between them.
But!.. if you say background:none
Vs background:red
then yes... there's a big diference, as I say, the first would set all properties to none/default
and the second one, will only change the color
and remains the rest in his default
state.
Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.
default
)Initial value the concatenation of the initial values of its longhand properties:
background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent
background
descriptions hereUpd2: Clarify better the background:none;
specification.
Use this:
#include <stdlib.h>
#include <string.h>
int main()
{
const char *d1 = "11";
int d1int = atoi(d1);
printf("d1 = %d\n", d1);
return 0;
}
etc.
I know this is late but it might be of some use:
echo "<pre>";
print_r($array);
echo "</pre>";
I couldn't find a neat way in the end so I went for create a directory called local_modules
and then added this bashscript to the package.json in scripts->preinstall
#!/bin/sh
for i in $(find ./local_modules -type d -maxdepth 1) ; do
packageJson="${i}/package.json"
if [ -f "${packageJson}" ]; then
echo "installing ${i}..."
npm install "${i}"
fi
done
You don't have a validator on the page. Add something like this to show the validation message.
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
As of docker-compose version 3 and later, you can just use the hostname
key:
version: '3'
services:
dns:
hostname: 'your-name'
If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
This worked for me. It's simple for simple objects.
class Person {_x000D_
constructor(firstName, lastName) {_x000D_
this.firstName = firstName;_x000D_
this.lastName = lastName;_x000D_
}_x000D_
getFullName() {_x000D_
return this.lastName + " " + this.firstName;_x000D_
}_x000D_
_x000D_
static class(obj) {_x000D_
return new Person(obj.firstName, obj.lastName);_x000D_
}_x000D_
}_x000D_
_x000D_
var person1 = {_x000D_
lastName: "Freeman",_x000D_
firstName: "Gordon"_x000D_
};_x000D_
_x000D_
var gordon = Person.class(person1);_x000D_
console.log(gordon.getFullName());
_x000D_
I was also searching for a simple solution, and this is what I came up with, based on all other answers and my research. Basically, class Person has another constructor, called 'class' which works with a generic object of the same 'format' as Person. I hope this might help somebody as well.
Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:
<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
<br /><br />
<input type="submit" />
You can't cast an IEnumerable<T> to a List<T>.
But you can accomplish this using LINQ:
var result = ((IEnumerable)myObject).Cast<object>().ToList();
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I found an a bit different solution of my problem regarding this context. Thought worth sharing.
Most of the example create readStreams
from file. But in my case readStream
has to be created from JSON
string coming from a message pool.
var jsonStream = through2.obj(function(chunk, encoding, callback) {
this.push(JSON.stringify(chunk, null, 4) + '\n');
callback();
});
// message.value --> value/text to write in write.txt
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");
//"close" event didn't work for me!
writeStream.on( 'close', function () {
console.log( "- done!" );
sftp.end();
}
);
//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
console.log( "- done!"
sftp.end();
}
);
// finally this worked for me!
jsonStream.on('data', function(data) {
var toString = Object.prototype.toString.call(data);
console.log('type of data:', toString);
console.log( "- file transferred" );
});
jsonStream.pipe( writeStream );
I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put
#include <Windows.h>
instead.
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
this solution have a fine work, on desktop and mobile.
<div id="navbar" class="navbar-collapse collapse" data-toggle="collapse" data-target=".navbar-collapse collapse">
There is a data structure called deque
or double ended queue which is faster and efficient than a list. You can use your list and convert it to deque and do the required transformations in it. You can also convert the deque back to list.
import collections
mylist = [0, 1, 2, 3, 4]
#make a deque from your list
de = collections.deque(mylist)
#you can remove from a deque from either left side or right side
de.popleft()
print(de)
#you can covert the deque back to list
mylist = list(de)
print(mylist)
Deque also provides very useful functions like inserting elements to either side of the list or to any specific index. You can also rotate or reverse a deque. Give it a try!
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
I just wanted to add something to the answer of @NMrt who already pointed out:
you could encounter this error if your client is running the wrong TLS version, for example if the server is only running TLS 1.2.
With Framework 4.7.2, if you do not explicitly configure the target framework in your web.config like this
<system.web>
<compilation targetFramework="4.7" />
<httpRuntime targetFramework="4.7" />
</system.web>
your system default security protocols will be ignored and something "lower" might be used instead. In my case Ssl3/Tls instead of Tls13.
You can fix this also in code by setting the SecurityProtocol (keeps other protocols working):
System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11;
System.Net.ServicePointManager.SecurityProtocol &= ~System.Net.SecurityProtocolType.Ssl3;
or even by adding registry keys to enable or disable strong crypto
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
This blog post pointed me to the right direction and explains the backgrounds better than I can:
Use UploadStringAsync
method:
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
//handle your error here
}
else
{
//post was successful, so do what you need to do here
}
};
webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);
You can adjust the spacing around matplotlib figures using the subplots_adjust() function:
import matplotlib.pyplot as plt
plt.plot(whatever)
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
This will work for both the figure on screen and saved to a file, and it is the right function to call even if you don't have multiple plots on the one figure.
The numbers are fractions of the figure dimensions, and will need to be adjusted to allow for the figure labels.
Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.
:line_num_start,line_num_end>
For example,
14,21> shifts line number 14 to 21 to one tab
Increase the '>' symbol for more tabs.
For example,
14,21>>> for three tabs
Here's how its done: ParentClass.prototype.myMethod();
Or if you want to call it in the context of the current instance, you can do:
ParentClass.prototype.myMethod.call(this)
Same goes for calling a parent method from child class with arguments:
ParentClass.prototype.myMethod.call(this, arg1, arg2, ..)
* Hint: use apply()
instead of call()
to pass arguments as an array.
Try something like this - it works for the cases you have mentioned.
select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:
dependencies {
// Remote binary dependency
compile 'net.schmizz:sshj:0.10.0'
}
You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.
Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html
public static List<T> GetRandomElements<T>(this IEnumerable<T> list, int elementsCount)
{
return list.OrderBy(arg => Guid.NewGuid()).Take(elementsCount).ToList();
}
Prinsen's answer is the best choice. But, to fix the issue where the columns don't collapse his code needs to be surrounded by a media check statement. This way these styles are only applied when the larger columns are active. Here is the updated complete answer.
HTML:
<div class="row display-table">
<div class="col-xs-12 col-sm-4 display-cell">
img
</div>
<div class="col-xs-12 col-sm-8 display-cell">
text
</div>
</div>
CSS:
@media (min-width: 768px){
.display-table{
display: table;
table-layout: fixed;
}
.display-cell{
display: table-cell;
vertical-align: middle;
float: none;
}
}
This doesn't come from me, but it got the job done regardless:
SELECT DATEADD(wk, -1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day previous week
SELECT DATEADD(wk, 0, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day current week
SELECT DATEADD(wk, 1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day next week
SELECT DATEADD(wk, 0, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day previous week
SELECT DATEADD(wk, 1, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day current week
SELECT DATEADD(wk, 2, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day next week
I found it here.
I created a simple IBDesignable. Use it however u like. Just make your UITextField confirm to this class.
import UIKit
@IBDesignable
class RoundTextField : UITextField {
@IBInspectable var cornerRadius : CGFloat = 0{
didSet{
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth : CGFloat = 0 {
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor : UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable var bgColor : UIColor? {
didSet {
backgroundColor = bgColor
}
}
@IBInspectable var leftImage : UIImage? {
didSet {
if let image = leftImage{
leftViewMode = .always
let imageView = UIImageView(frame: CGRect(x: 20, y: 0, width: 20, height: 20))
imageView.image = image
imageView.tintColor = tintColor
let view = UIView(frame : CGRect(x: 0, y: 0, width: 25, height: 20))
view.addSubview(imageView)
leftView = view
}else {
leftViewMode = .never
}
}
}
@IBInspectable var placeholderColor : UIColor? {
didSet {
let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName : placeholderColor!])
attributedPlaceholder = str
}
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 50, dy: 5)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 50, dy: 5)
}
}
A repeater inside a repeater
<div ng-repeat="step in steps">
<div ng-repeat="(key, value) in step">
{{key}} : {{value}}
</div>
</div>
<div>
<img class="crop" src="http://lorempixel.com/500/200"/>
</div>
<img src="http://lorempixel.com/500/200"/>
div {
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
.crop {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
height: auto;
width: auto;
}
Custom Buttons appear in their respective image colors. Setting the button type to "System" in the storyboard (or to UIButtonTypeSystem
in code), will render the button's image with the default tint color.
(tested on iOS9, Xcode 7.3)
Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();
ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes
I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
This is what I came op for a thread safe bounded blocking queue.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
public class BlockingBuffer<T>
{
private Object t_lock;
private Semaphore sema_NotEmpty;
private Semaphore sema_NotFull;
private T[] buf;
private int getFromIndex;
private int putToIndex;
private int size;
private int numItems;
public BlockingBuffer(int Capacity)
{
if (Capacity <= 0)
throw new ArgumentOutOfRangeException("Capacity must be larger than 0");
t_lock = new Object();
buf = new T[Capacity];
sema_NotEmpty = new Semaphore(0, Capacity);
sema_NotFull = new Semaphore(Capacity, Capacity);
getFromIndex = 0;
putToIndex = 0;
size = Capacity;
numItems = 0;
}
public void put(T item)
{
sema_NotFull.WaitOne();
lock (t_lock)
{
while (numItems == size)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
buf[putToIndex++] = item;
if (putToIndex == size)
putToIndex = 0;
numItems++;
Monitor.Pulse(t_lock);
}
sema_NotEmpty.Release();
}
public T take()
{
T item;
sema_NotEmpty.WaitOne();
lock (t_lock)
{
while (numItems == 0)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
item = buf[getFromIndex++];
if (getFromIndex == size)
getFromIndex = 0;
numItems--;
Monitor.Pulse(t_lock);
}
sema_NotFull.Release();
return item;
}
}
Yeah that's it without no further issues, to avoid raw string json this is it.
public ActionResult GetJson()
{
var json = System.IO.File.ReadAllText(
Server.MapPath(@"~/App_Data/content.json"));
return new ContentResult
{
Content = json,
ContentType = "application/json",
ContentEncoding = Encoding.UTF8
};
}
NOTE: please note that method return type of JsonResult
is not working for me, since JsonResult
and ContentResult
both inherit ActionResult
but there is no relationship between them.
<context:property-placeholder location="classpath*:spring/*.properties" />
If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above
<property name="locations" value ="config/springcontext.properties" />
this will be pointing to web-inf/classes/config/springcontext.properties
<context:annotation-config/> <!-- is used to activate the annotation for beans -->
<context:component-scan base-package="x.y.MyClass" /> <!-- is for the Spring IOC container to look for the beans in the base package. -->
The other important point to note is that context:component-scan
implicitly calls the context:annotation-config
to activate the annotations on beans. Well if you don't want context:component-scan
to implicitly activate annotations for you, you can go on setting the annotation-config element of the context:component-scan
to false
.
To summarize:
<context:annotation-config/> <!-- activates the annotations -->
<context:component-scan base-package="x.y.MyClass" /> <!-- activates the annotations + register the beans by looking inside the base-package -->
Open the svg using Inkscape.
Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/
done
all rect/circle have been converted to path
The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
Since the img is an inline element, Just use text-center
on it's container. Using mx-auto
will center the container (column) too.
<div class="row">
<div class="col-4 mx-auto text-center">
<img src="..">
</div>
</div>
By default, images are display:inline
. If you only want the center the image (and not the other column content), make the image display:block
using the d-block
class, and then mx-auto
will work.
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="..">
</div>
</div>
Use $n
(where n is a digit) to refer to captured subsequences in replaceFirst(...)
. I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.
Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}
Consider (\D+)
for the second group instead of (.*)
. *
is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d)
has nothing to match, before it can match to the final digit.
I've been looking around for some solutions for this simple decoration and I've found quite a few ones, some weird, some even with JS to calculate the height of the font and bla,bla,bla, then I've read the one on this post and read a comment from thirtydot speaking about fieldset
and legend
and I thought that was it.
I'm overriding those 2 elements styles, I guess you could copy the W3C standards for them and include it on your .middle-line-text
class (or whatever you want to call it) but this is what I did:
<fieldset class="featured-header">
<legend>Your text goes here</legend>
</fieldset>
<style>
.featured-header{
border-bottom: none;
border-left: none;
border-right: none;
text-align: center;
}
.featured-header legend{
-webkit-padding-start: 8px; /* It sets the whitespace between the line and the text */
-webkit-padding-end: 8px;
background: transparent; /** It's cool because you don't need to fill your bg-color as you would need to in some of the other examples that you can find (: */
font-weight: normal; /* I preffer the text to be regular instead of bold */
color: YOU_CHOOSE;
}
</style>
Here's the fiddle: http://jsfiddle.net/legnaleama/3t7wjpa2/
I've played with the border styles and it also works in Android ;) (Tested on kitkat 4.XX)
EDIT:
Following Bekerov Artur's idea which is a nice option too, I've changed the .png base64 image to create the stroke with an .SVG so you can render in any resolution and also change the colour of the element without any other software involved :)
/* SVG solution based on Bekerov Artur */
/* Flexible solution, scalable, adaptable and also color customizable*/
.stroke {
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='1px' height='1px' viewBox='0 0 1 1' enable-background='new 0 0 1 1' fill='%23ff6600' xml:space='preserve'><rect width='1' height='1'/></svg>");
background-repeat: repeat-x;
background-position: left;
text-align: center;
}
.stroke h3 {
background-color: #ffffff;
margin: 0 auto;
padding:0 10px;
display: inline-block;
font-size: 66px;
}
As stated by Luke you need to use a server side language, like php. This is a really simple php example:
<?php
if ($_GET['run']) {
# This code will run if ?run=true is set.
exec("/path/to/name.sh");
}
?>
<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>
Save this as myfilename.php
and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...
Your project needs to reference assembly System.Web.dll
. Server is an object of type HttpServerUtility
. Example:
HttpContext.Current.Server.MapPath(path);
There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.
git clone https://github.com/ORGANIZATION/repository.git
(clone the repository)
cd repository (navigate to the repository)
git fetch origin 2600f4f928773d79164964137d514b85400b09b2
git checkout FETCH_HEAD
This worked for me with log4j2 and xml parameters:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Properties>
<Property name="log-path">/some_path/logs/</Property>
<Property name="app-id">my_app</Property>
</Properties>
<Appenders>
<RollingFile name="file-log" fileName="${log-path}/${app-id}.log"
filePattern="${log-path}/${app-id}-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.jdbc.core" level="trace" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Logger>
<Root level="info" additivity="false">
<appender-ref ref="file-log" />
<appender-ref ref="console" />
</Root>
</Loggers>
</Configuration>
Result console and file log was:
JdbcTemplate - Executing prepared SQL query
JdbcTemplate - Executing prepared SQL statement [select a, b from c where id = ? ]
StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [my_id], value class [java.lang.String], SQL type unknown
Just copy/past
HTH
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
It work for me when I use extension and call within layoutSubviews() for update layout views immediately.
extension UITableViewCell {
func removeSeparator() {
separatorInset = UIEdgeInsetsMake(0, bounds.size.width, 0, 0)
}
}
override func layoutSubviews() {
super.layoutSubviews()
removeSeparator()
}
I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io
library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles
method and you can process each file.
You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi
Here's an example:
Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
while(it.hasNext()){
System.out.println(((File) it.next()).getName());
}
You can change null
and put a list of extentions if you wanna filter. Example: {".xml",".java"}
You can use fork()
and system()
so that your program doesn't have to wait until system()
returns.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[]){
int status;
// By calling fork(), a child process will be created as a exact duplicate of the calling process.
// Search for fork() (maybe "man fork" on Linux) for more information.
if(fork() == 0){
// Child process will return 0 from fork()
printf("I'm the child process.\n");
status = system("my_app");
exit(0);
}else{
// Parent process will return a non-zero value from fork()
printf("I'm the parent.\n");
}
printf("This is my main program and it will continue running and doing anything i want to...\n");
return 0;
}
I had this problem with bundles having incorrect path's to images and CssRewriteUrlTransform
not resolving relative parent paths ..
correctly (there was also problem with external resources like webfonts). That's why I wrote this custom transform (appears to do all of the above correctly):
public class CssRewriteUrlTransform2 : IItemTransform
{
public string Process(string includedVirtualPath, string input)
{
var pathParts = includedVirtualPath.Replace("~/", "/").Split('/');
pathParts = pathParts.Take(pathParts.Count() - 1).ToArray();
return Regex.Replace
(
input,
@"(url\(['""]?)((?:\/??\.\.)*)(.*?)(['""]?\))",
m =>
{
// Somehow assigning this to a variable is faster than directly returning the output
var output =
(
// Check if it's an aboslute url or base64
m.Groups[3].Value.IndexOf(':') == -1 ?
(
m.Groups[1].Value +
(
(
(
m.Groups[2].Value.Length > 0 ||
!m.Groups[3].Value.StartsWith('/')
)
) ?
string.Join("/", pathParts.Take(pathParts.Count() - m.Groups[2].Value.Count(".."))) :
""
) +
(!m.Groups[3].Value.StartsWith('/') ? "/" + m.Groups[3].Value : m.Groups[3].Value) +
m.Groups[4].Value
) :
m.Groups[0].Value
);
return output;
}
);
}
}
Edit: I didn't realize it, but I used some custom extension methods in the code. The source code of those is:
/// <summary>
/// Based on: http://stackoverflow.com/a/11773674
/// </summary>
public static int Count(this string source, string substring)
{
int count = 0, n = 0;
while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
{
n += substring.Length;
++count;
}
return count;
}
public static bool StartsWith(this string source, char value)
{
if (source.Length == 0)
{
return false;
}
return source[0] == value;
}
Of course it should be possible to replace String.StartsWith(char)
with String.StartsWith(string)
.
Here is a quote from Daniel Liang, author of 'Introduction to JAVA programming', on the subject of compilation:
"A program written in a high-level language is called a source program or source code. Because a computer cannot execute a source program, a source program must be translated into machine code for execution. The translation can be done using another programming tool called an interpreter or a compiler." (Daniel Liang, "Introduction to JAVA programming", p8).
...He Continues...
"A compiler translates the entire source code into a machine-code file, and the machine-code file is then executed"
When we punch in high-level/human-readable code this is, at first, useless! It must be translated into a sequence of 'electronic happenings' in your tiny little CPU! The first step towards this is compilation.
Simply put: a compile-time error happens during this phase, while a run-time error occurs later.
Remember: Just because a program is compiled without error does not mean it will run without error.
A Run-time error will occur in the ready, running or waiting part of a programs life-cycle while a compile-time error will occur prior to the 'New' stage of the life cycle.
Example of a Compile-time error:
A Syntax Error - how can your code be compiled into machine level instructions if they are ambiguous?? Your code needs to conform 100% to the syntactical rules of the language otherwise it cannot be compiled into working machine code.
Example of a run-time error:
Running out of memory - A call to a recursive function for example might lead to stack overflow given a variable of a particular degree! How can this be anticipated by the compiler!? it cannot.
And that is the difference between a compile-time error and a run-time error
My problem was that I was trying to create the relation table before other tables!
Only two steps:
Install the latest release "pandoc" from here:
Call the function pandoc
in the library(knitr)
library(knitr)
pandoc('input.md', format = 'latex')
Thus, you can convert your "input.md" into "input.pdf".