You could rather do a upsert, this operation in MongoDB is utilized to save document into collection. If document matches query criteria then it will perform update operation otherwise it will insert a new document into collection.
something similar as below
db.employees.update(
{type:"FT"},
{$set:{salary:200000}},
{upsert : true}
)
With Lodash, you can do:
if(_.has(req,'documents')){
if (req.documents.length)
_.forEach(req.documents, function(document){
records.push(document);
});
} else {
}
if(_.has(req,'documents'))
is to check whether our request object has a property named documents
and if it has that prop, the next if (req.documents.length)
is to validate if it is not an empty array, so the other stuffs like forEach
can be proceeded.
Go to File > Sync Project with Gradles Files.
When every given bool
is True
, or when every given bool
is False
...
they all are equal to each other!
So, we just need to find two elements which evaluates to different bool
s
to know that there is at least one True
and at least one False
.
not bool(a)==bool(b)==bool(c)
I belive it short-circuits, cause AFAIK a==b==c
equals a==b and b==c
.
def _any_but_not_all(first, iterable): #doing dirty work
bool_first=bool(first)
for x in iterable:
if bool(x) is not bool_first:
return True
return False
def any_but_not_all(arg, *args): #takes any amount of args convertable to bool
return _any_but_not_all(arg, args)
def v_any_but_not_all(iterable): #takes iterable or iterator
iterator=iter(iterable)
return _any_but_not_all(next(iterator), iterator)
I wrote also some code dealing with multiple iterables, but I deleted it from here because I think it's pointless. It's however still available here.
Thanks for the earlier reply.
I figured out the solutions using selenium 2.0 classes.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebTableExample
{
public static void main(String[] args)
{
WebDriver driver = new InternetExplorerDriver();
driver.get("http://localhost/test/test.html");
WebElement table_element = driver.findElement(By.id("testTable"));
List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
int row_num,col_num;
row_num=1;
for(WebElement trElement : tr_collection)
{
List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
for(WebElement tdElement : td_collection)
{
System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
You might get better results if you try:
console.log(JSON.stringify(functor));
I am quoting this answer from official tensorflow docs https://www.tensorflow.org/api_guides/python/nn#Convolution For the 'SAME' padding, the output height and width are computed as:
out_height = ceil(float(in_height) / float(strides[1]))
out_width = ceil(float(in_width) / float(strides[2]))
and the padding on the top and left are computed as:
pad_along_height = max((out_height - 1) * strides[1] +
filter_height - in_height, 0)
pad_along_width = max((out_width - 1) * strides[2] +
filter_width - in_width, 0)
pad_top = pad_along_height // 2
pad_bottom = pad_along_height - pad_top
pad_left = pad_along_width // 2
pad_right = pad_along_width - pad_left
For the 'VALID' padding, the output height and width are computed as:
out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))
and the padding values are always zero.
Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is QueryPerformanceCounter
. Google it for more info. Try pushing the following into a class, call it CTimer
say, then you can make an instance somewhere global and just call .StartCounter
and .TimeElapsed
Option Explicit
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
This worked for me on OSX.
# allow variable to opened as files
from io import StringIO
# library to map other strange (accented) characters back into UTF-8
from unidecode import unidecode
# cleanse input file with Windows formating to plain UTF-8 string
with open(filename, 'rb') as fID:
uncleansedBytes = fID.read()
# decode the file using the correct encoding scheme
# (probably this old windows one)
uncleansedText = uncleansedBytes.decode('Windows-1252')
# replace carriage-returns with new-lines
cleansedText = uncleansedText.replace('\r', '\n')
# map any other non UTF-8 characters into UTF-8
asciiText = unidecode(cleansedText)
# read each line of the csv file and store as an array of dicts,
# use first line as field names for each dict.
reader = csv.DictReader(StringIO(cleansedText))
for line_entry in reader:
# do something with your read data
Adding new certificate resolved this issue for me. Properties page -> signing -> Click on Create test certificate
The shortcut key is ctrl+] to indentation and ctrl +[ to unindent
Javascript is pretty good at manipulating css.
document.body.style.cursor = *cursor-url*;
//OR
var elementToChange = document.getElementsByTagName("body")[0];
elementToChange.style.cursor = "url('cursor url with protocol'), auto";
or with jquery:
$("html").css("cursor: url('cursor url with protocol'), auto");
Firefox will not work unless you specify a default cursor after the imaged one!
Also remember that IE6 only supports .cur and .ani cursors.
If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:
// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);
working sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">
div {
height: 100px;
width: 1000px;
background-color: red;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";
</script>
</html>
You can use the continue
statement.
For example:
foreach(int number in numbers)
{
if(number < 0)
{
continue;
}
}
Just had the similar error when installing java 8 (jdk & jre) on a system already running Java 7.
Error: Registry key 'Software\JavaSoft\Java Runtime
Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll Error: Could not find Java SE Runtime Environment.
My environment was set up correctly (Path & java_home correctly defined), but the problem arises from the way pre-8 Java installers worked, which is that they used to copy the three executables (java.exe, javaw.exe & javaws.exe) to the Windows system directory. These remain unless overwritten by a new pre-8 installation.
However the Java 8 installer instead creates symbolic links in a new directory, C:\ProgramData\Oracle\Java\javapath, pointing to the actual JRE 8 location.
This means that you'll actually run the old 7 exes but use the new 8 DLLs.
So, the solution is simply to delete the 3 Java exes, as above, from the windows system directory.
If you are running 32-bit Java on a 64-bit Windows, the exes would be in Windows\SysWOW64, otherwise in Windows\System32.
This is the error that is returned when the Windows Firewall blocks the port (out-going). We have a strict web server so the outgoing ports are blocked by default. All I had to do was to create a rule to allow the TCP port number in wf.msc.
In DB2, using single quotes instead of your double quotes will work. So that could translate the same in Oracle..
SELECT CustomerName AS Customer, '' AS Contact
FROM Customers;
This links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
You'll want to use the specified market
protocol:
final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}
While using getPackageName()
from Context
or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.
There's also Michael Kaplan's SOON ("Shut One, Open New") add-in. You'd have to chain it, but it's one way to do this.
I can't say I've had much reason to ever want to do this programatically, since I'm programming for end users, and they are never using anything but the front end in the Access user interface, and there's no reason to regularly compact a properly-designed front end.
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json
You can switch to shell mode temporarily by:
:! <command>
such as
:! ls
I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.
npm install nodejs-base64-converter --save
var nodeBase64 = require('nodejs-base64-converter');
console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text
If your code is ES7 based (or upper versions):
channelArray.includes('three'); //will return true or false
If not, for example you are using IE with no babel transpile:
channelArray.indexOf('three') !== -1; //will return true or false
the indexOf
method will return the position the element has into the array, because of that we use !==
different from -1 if the needle is found at the first position.
You can review the stashed changes in VSCode with gitlen extension
2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
My suggestion is to run
openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin
under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.
U1: My guess is that you are not setting some other required options, like mode of operation (padding).
U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.
My suggestion:
$http({
method: 'DELETE',
url: '/roles/' + roleid,
data: {
user: userId
},
headers: {
'Content-type': 'application/json;charset=utf-8'
}
})
.then(function(response) {
console.log(response.data);
}, function(rejection) {
console.log(rejection.data);
});
Yes you can connect your android app to your PHP to grab results from your database. Use a webservice to connect to your backend script via ASYNC task and http post requests. Check this link for more information Connecting to MySQL
You should try it like this:
var result =
from priceLog in PriceLogList
group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
select new {
LogDateTime = dateGroup.Key,
AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
};
In addition to Thevs answer:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
it's jquery + jquery.json
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
according to NPM Doc
So it seems that by running npm install package_name
, the package dependency should be automatically added to package.json right?
copy paste pl sql developer in program files x86 and program files both. if client is installed in other partition/drive then copy pl sql developer to that drive also. and run from pl sql developer folder instead of desktop shortcut.
ultimate solution ! chill
You have to do it like this for now, i know not very efficient as you don't want to convert the object you receive from firebase.
this.af.database.list('/data/' + this.base64Email).subscribe(years => {
years.forEach(year => {
var localYears = [];
Object.keys(year).forEach(month => {
localYears.push(year[month])
});
year.months = localYears;
})
this.years = years;
});
you can use this:
HTML
<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />
support only .PDF and .XLS files
Class methods provide a "semantic sugar" (don't know if this term is widely used) - or "semantic convenience".
Example: you got a set of classes representing objects. You might want to have the class method all()
or find()
to write User.all()
or User.find(firstname='Guido')
. That could be done using module level functions of course...
Here is one using arrays and Java 8+
import java.util.Arrays;
import java.util.stream.IntStream;
public class HelloWorld {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
permutation(arr, new int[]{});
}
static void permutation(int[] arr, int[] prefix) {
if (arr.length == 0) {
System.out.println(Arrays.toString(prefix));
}
for (int i = 0; i < arr.length; i++) {
int i2 = i;
int[] pre = IntStream.concat(Arrays.stream(prefix), IntStream.of(arr[i])).toArray();
int[] post = IntStream.range(0, arr.length).filter(i1 -> i1 != i2).map(v -> arr[v]).toArray();
permutation(post, pre);
}
}
}
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
Try loading the website in another web browser such as Safari. Recently had this problem and for some reason, it worked after loading in a different browser.
Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read}
and all was fine.
Changing the NPM repo URL to HTTP works as a quick-fix, but I wanted to use HTTPS.
In my case, the proxy at my employer (ZScaler) was causing issues (as it acts as a MITM, causing certification verification issues)
I forgot I found a script that helps with this and Git (for cloning GitHub repos via HTTPS had the same issue) and forked it for my use
Basically, it does the following for git:
git config --global http.proxy http://gateway.zscaler.net:80/
git config --system http.proxy http://gateway.zscaler.net:80/
and for Node, it adds proxy=http://gateway.zscaler.net:80/
to the end of c:\Users\$USERNAME\npm\.npmrc
That solved the issue for me.
I don't think is a good practice to invade the GLOBAL space from modules, but in scenarios where could be strictly necessary to implement it:
Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});
It has to be considered the impact of this resource. Without proper naming of those constants, the risk of OVERWRITTING already defined global variables, is something real.
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
document.getElementById("id").innerHTML == "" || null
or
$("element").html() == "" || null
In first statement you define variable, which common for all of the objects (class static field).
In the second statement you define variable, which belongs to each created object (a lot of copies).
In your case you should use the first one.
Given this test file (test.txt)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
the following command will replace the first line to "newline text"
$ sed '1 c\
> newline text' test.txt
Result:
newline text
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
more information can be found here
http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/
You're looking for the --data-binary
argument:
curl -i -X POST host:port/post-file \
-H "Content-Type: text/xml" \
--data-binary "@path/to/file"
In the example above, -i
prints out all the headers so that you can see what's going on, and -X POST
makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @
symbol, so curl
knows to read from a file.
It looks like the files npm
uses to edit its config files are not created on a clean install, as npm
has a default option for each one. This is why you can still get options with npm config get <option>
: having those files only overrides the defaults, it doesn't create the options from scratch.
I had never touched my npm config
stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc
(on a Windows 8.1 machine with Git Bash
), yet I could run npm config get <something>
and, if it was a correct npm
option, it returned a value. When I ran npm config set <option> <value>
, the file ~/.npmrc
seemed to be created automatically, with the option & its value as the only non-commented-out line.
As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc
is deleted, too, and recreated if you set
anything else later.
In your case (assuming it is still the same over a year later), it looks like you never set the proxy
option in npm
. Therefore, as npm
's config
help page says, it is set to whatever your http_proxy
(case-insensitive) environment variable is. This means there is nothing to delete
, unless you want to "delete" your HTTP proxy, although you could set
the option or environment variable to something else and hope neither breaks your set-up somehow.
Divide $percentage
by 100 and multiply to $totalWidth
. Simple maths.
Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.
EDIT: my answer makes me think of the classic old man saying "when I was your age..."
You need to add the port number to every address you type in your browser when you have changed the default port from port 80.
For example: localhost:8000/cc .
A little edition here is that it should be 8080 in place of 8000. For example - http://localhost:8080/phpmyadmin/
When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body>
tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html>
tag is parsed), which as you have found will not work.
If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body>
tag :-)
EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.
You can accomplish this via method overloading.
public int doSomething(int arg1, int arg2)
{
return 0;
}
public int doSomething()
{
return doSomething(defaultValue0, defaultValue1);
}
By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.
<@include>
- The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
<jsp:include>
- The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Depending on your needs, you may either use
<@include>
or<jsp:include>
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Extract single value from JSON response Python
Try this
import json
import sys
#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
#print the resp
print (resp)
#extract an element in the response
print (resp['test1'])
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
HTML provide only input type="time"
If you are using bootstrap then you can use timepicker.
You can get code from this URL http://jdewit.github.io/bootstrap-timepicker
May be it will help you
I set the content-type in the MarshallingView in the ContentNegotiatingViewResolver bean. It works easily, clean and smoothly:
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
<property name="contentType" value="application/xml;charset=UTF-8" />
</bean>
</list>
</property>
You can reboot the device by sending the following broadcast:
$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
In Eclipse: right-click
on your project -> Export
-> JAR file
At last page with options (when there will be no Next
button active) you will see settings for Main class:
. You need to set here class with main
method which should be executed by default (like when JAR file will be double-clicked).
vertical-align
applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:
div > * {
vertical-align:middle; // Align children to middle of line
}
See: http://jsfiddle.net/dfmx123/TFPx8/1186/
NOTE: vertical-align
is relative to the current text line, not the full height of the parent div
. If you wanted the parent div
to be taller and still have the elements vertically centered, set the div
's line-height
property instead of its height
. Follow jsfiddle link above for an example.
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
For copy-paste into command line:
git checkout master ; remote=origin ; for brname in `git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\/]+\//,"",$1); print $1}'`; do git branch -D $brname ; git checkout -b $brname $remote/$brname ; done ; git checkout master
For more readibility:
git checkout master ;
remote=origin ;
for brname in `
git branch -r | grep $remote | grep -v master | grep -v HEAD
| awk '{gsub(/^[^\/]+\//,"",$1); print $1}'
`; do
git branch -D $brname ;
git checkout -b $brname $remote/$brname ;
done ;
git checkout master
I couldn't revert mine manually for some reason so here is how I ended up doing it.
We were using an incompatible version of Ruby inside of Terminal (Mac), but once we used RVM to switch to Ruby 2.1.2, Cocoapods came back.
Exceptions in recent versions of Java aren't expensive enough to make their avoidance important. Use the try/catch block people have suggested; if you catch the exception early in the process (i.e., right after the user has entered it) then you're not going to have the problem later in the process (because it'll be the right type anyway).
Exceptions used to be a lot more expensive than they are now; don't optimize for performance until you know the exceptions are actually causing a problem (and they won't, here.)
Paste this into the console and run the commands:
## How to update R in RStudio using installr package (for Windows)
## paste this into the console and run the commands
## "The updateR() command performs the following: finding the latest R version, downloading it, running the installer, deleting the installation file, copy and updating old packages to the new R installation."
## more info here: https://cran.r-project.org/web/packages/installr/index.html
install.packages("installr")
library(installr)
updateR()
## Watch for small pop up windows. There will be many questions and they don't always pop to the front.
## Note: It warns that it might work better in Rgui but I did it in Rstudio and it worked just fine.
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
It isn't possible to do it the way you've defined ldap_get
. However, if you define ldap_get
like this:
def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )
Now you can:
ldap_get( base_dn, filter, X )
But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).
The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.
var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");
function removeColumn(#){
// remove column #
}
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
This occurs due to the availability of the previous version of the Application, that is not installed on the device but its data is present in the device memory. So it fails to upgrade this uninstalled application data on the device
Try this :
Go to Device Settings ==> Apps(All Apps) ==> search your App OR search for 'client' ==> In App info screen , press the triple dots option on top right corner ==> select 'Uninstall for All Users' ==> a promt appears select 'OK'
It works for me every time this error occurs
SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM membership_dates md
output::
id entity_id start_date end_date days
1 1236 2018-01-16 00:00:00 2018-08-31 00:00:00 227
2 2876 2015-06-26 00:00:00 2019-06-30 00:00:00 1465
3 3880 1990-06-05 00:00:00 2018-07-04 00:00:00 10256
4 3882 1993-07-05 00:00:00 2018-07-04 00:00:00 9130
hope it helps someone in future
You can do a LEFT JOIN and assert the joined column is NULL.
Example:
SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL
It functions the same as a return for function with a specified parameter, except it returns nothing, as there is nothing to return and control is passed back to the calling method.
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
One of my favorites in C++ is the "public abstract concrete inline destructor":
class AbstractBase {
public:
virtual ~AbstractBase() = 0 {}; // PACID!
virtual void someFunc() = 0;
virtual void anotherFunc() = 0;
};
I stole this from Scott Meyers in Effective C++. It looks a bit weird to see a method that's both pure virtual (which generally means "abstract") and implemented inline, but it's the best and most concise way I've found to ensure that an object is polymorphically destructed.
This might be a little better:
td {
padding:2px 0;
}
you will get the time without specifying the date format. convert the string to date using Date
object
var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
working solution:
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
I have also this problem when I do with XCode project what is exported from cordova framework. Resolution : You have to create Apple-ID and Provisioining-profile by yourself. Because Xcode seems to be unable to create it for you.
This worked for me
$(function() {
$("#select option").each(function(i){
alert($(this).text() + " : " + $(this).val());
});
});
I have answered on this.
In my case, the problem was because of
Video Downloader professional
andAdBlock
In short, this problem occurs due to some google chrome plugins
An elegant way could be as follows -
ids = np.flip(np.argsort(avgDists))
This will give you indices of elements sorted in descending order. Now you can use regular slicing...
top_n = ids[:n]
I'm using Wand-py (an implementation of the Wand wrapper around ImageMagick) to import some pretty advanced SVGs and so far have seen great results! This is all the code it takes:
with wand.image.Image( blob=svg_file.read(), format="svg" ) as image:
png_image = image.make_blob("png")
I just discovered this today, and felt like it was worth sharing for anyone else who might straggle across this answer as it's been a while since most of these questions were answered.
NOTE: Technically in testing I discovered you don't even actually have to pass in the format parameter for ImageMagick, so with wand.image.Image( blob=svg_file.read() ) as image:
was all that was really needed.
EDIT: From an attempted edit by qris, here's some helpful code that lets you use ImageMagick with an SVG that has a transparent background:
from wand.api import library
import wand.color
import wand.image
with wand.image.Image() as image:
with wand.color.Color('transparent') as background_color:
library.MagickSetBackgroundColor(image.wand,
background_color.resource)
image.read(blob=svg_file.read(), format="svg")
png_image = image.make_blob("png32")
with open(output_filename, "wb") as out:
out.write(png_image)
Here is my solution using jQuery
<script type="text/javascript">
$('#mtoogle').toggle(
function () {
document.getElementById('playTune').pause();
},
function () {
document.getElementById('playTune').play();
}
);
</script>
And the working demo
I found myself having to read a string with NULL in it, so here is a solution that will read anything you throw at it. Although if you actually are dealing with NULL, you will need to deal with that at the hex level.
$ cat > read.dd.sh
read.dd() {
buf=
while read; do
buf+=$REPLY
done < <( dd bs=1 2>/dev/null | xxd -p )
printf -v REPLY '%b' $( sed 's/../ \\\x&/g' <<< $buf )
}
Proof:
$ . read.dd.sh
$ read.dd < read.dd.sh
$ echo -n "$REPLY" > read.dd.sh.copy
$ diff read.dd.sh read.dd.sh.copy || echo "File are different"
$
HEREDOC example (with ^J, ^M, ^I):
$ read.dd <<'HEREDOC'
> (TAB)
> (SPACES)
(^J)^M(^M)
> DONE
>
> HEREDOC
$ declare -p REPLY
declare -- REPLY=" (TAB)
(SPACES)
(^M)
DONE
"
$ declare -p REPLY | xxd
0000000: 6465 636c 6172 6520 2d2d 2052 4550 4c59 declare -- REPLY
0000010: 3d22 0928 5441 4229 0a20 2020 2020 2028 =".(TAB). (
0000020: 5350 4143 4553 290a 285e 4a29 0d28 5e4d SPACES).(^J).(^M
0000030: 290a 444f 4e45 0a0a 220a ).DONE
If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.
And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.
You can just write (a!=b)
This would work the same as way as a ^ b
.
This problem may also be seen during ViewModel
to EntityModel
mapping (by using AutoMapper
, etc.) and trying to include context.Entry().State
and context.SaveChanges()
such a using block as shown below would solve the problem. Please keep in mind that context.SaveChanges()
method is used two times instead of using just after if-block
as it must be in using block also.
public void Save(YourEntity entity)
{
if (entity.Id == 0)
{
context.YourEntity.Add(entity);
context.SaveChanges();
}
else
{
using (var context = new YourDbContext())
{
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges(); //Must be in using block
}
}
}
Hope this helps...
In one of the comments, you say:
Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object
If it's your code, figure out how you're getting None
when you expect a number and stop that from happening.
If it's someone else's code, find out the conditions under which it gives None
and determine a sensible value to use for that, with the usual conditional code:
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
...or even...
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
There's no reason to automatically use 0
here — solutions that depend on the "false"-ness of None
assume you will want this. The DEFAULT_VALUE
(if it even exists) completely depends on your code's purpose.
Please use a <pre>
tag
demo : http://jsfiddle.net/K83cK/
var data = {_x000D_
"data": {_x000D_
"x": "1",_x000D_
"y": "1",_x000D_
"url": "http://url.com"_x000D_
},_x000D_
"event": "start",_x000D_
"show": 1,_x000D_
"id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
A simple and easy way:
function remove-accents(p){
c='áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';s='aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';n='';for(i=0;i<p.length;i++){if(c.search(p.substr(i,1))>=0){n+=s.substr(c.search(p.substr(i,1)),1);} else{n+=p.substr(i,1);}} return n;
}
So do this:
remove-accents("Thís ís ân accêntéd phráse");
Output:
"This is an accented phrase"
As it turns out, my suspicions were right. The audience aud
claim in a JWT is meant to refer to the Resource Servers that should accept the token.
As this post simply puts it:
The audience of a token is the intended recipient of the token.
The audience value is a string -- typically, the base address of the resource being accessed, such as
https://contoso.com
.
The client_id
in OAuth refers to the client application that will be requesting resources from the Resource Server.
The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id
and client_secret
along with any user credentials that may be required. The Authorization Server validates the client using the client_id
and client_secret
and returns a JWT.
The JWT will contain an aud
claim that specifies which Resource Servers the JWT is valid for. If the aud
contains www.myfunwebapp.com
, but the client app tries to use the JWT on www.supersecretwebapp.com
, then access will be denied because that Resource Server will see that the JWT was not meant for it.
How about list.Find(x => x.Name == "height").Value = 20;
This works fine. I know its an old post, but just wondered why hasn't anyone suggested this? Is there a drawback in this code?
In version 1.28 of Visual Studio Code "files.exclude"
must be placed within a settings
node.
Resulting in a workspace file that looks like:
{
"settings": {
"files.exclude": {
"**/node_modules": true
}
}
}
In my case I faced that error while parsing an email. I got the attachment as base64 string and extract it via re.search. Eventually there was a strange additional substring at the end.
dHJhaWxlcgo8PCAvU2l6ZSAxNSAvUm9vdCAxIDAgUiAvSW5mbyAyIDAgUgovSUQgWyhcMDAyXDMz
MHtPcFwyNTZbezU/VzheXDM0MXFcMzExKShcMDAyXDMzMHtPcFwyNTZbezU/VzheXDM0MXFcMzEx
KV0KPj4Kc3RhcnR4cmVmCjY3MDEKJSVFT0YK
--_=ic0008m4wtZ4TqBFd+sXC8--
When I deleted --_=ic0008m4wtZ4TqBFd+sXC8--
and strip the string then parsing was fixed up.
So my advise is make sure that you are decoding a correct base64 string.
That is because in Python 3, they have replaced the print
statement with the print
function.
The syntax is now more or less the same as before, but it requires parens:
From the "what's new in python 3" docs:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
You can't change the height of the br
tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.
You can change the line height using the line-height
style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.
For completeness: Text blocks in HTML is usually done using the p
tag around text blocks. That way you can control the line height inside the p
tag, and also the spacing between the p
tags.
[1,3].inject([1,1,1,2,2,3]) do |memo,element|
memo.tap do |memo|
i = memo.find_index(e)
memo.delete_at(i) if i
end
end
You can split date month year from current date as follows:
DateTime todaysDate = DateTime.Now.Date;
Day:
int day = todaysDate.Day;
Month:
int month = todaysDate.Month;
Year:
int year = todaysDate.Year;
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
Specifically, you are not validating the user input for creditPlan
- if the user enters a value of anything else than "0","1","2" or "3"
, then none of the branches indicated will be executed (and creditPlan
will not be defaulted to zero as per your user prompt).
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else
statement).
I would however like to point out other potential improvements:
CreditPlan
appears to have a finite domain and is better suited to an enumeration
or Dictionary
than a string
. Financial data and percentages should always be modelled as decimal
, not double
to avoid rounding issues, and 'status' appears to be a boolean.monthlyCharge = balance * annualRate * (1/12))
is common to more than one branch. For maintenance reasons, do not duplicate this code.e.g. here is an alternative representation of your model:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
For quick reference of anyone who wants to go to the end of line or start of line in iTerm2, the above link http://hackaddict.blogspot.com/2007/07/skip-to-next-or-previous-word-in-iterm.html notes that in iTerm2:
I found a solution by extending ArrayAdapter
and Overriding the getView
method.
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* A SpinnerAdapter which does not show the value of the initial selection initially,
* but an initialText.
* To use the spinner with initial selection instead call notifyDataSetChanged().
*/
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {
private Context context;
private int resource;
private boolean initialTextWasShown = false;
private String initialText = "Please select";
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* @param objects The objects to represent in the ListView.
*/
public SpinnerAdapterWithInitialText(@NonNull Context context, int resource, @NonNull T[] objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
}
/**
* Returns whether the user has selected a spinner item, or if still the initial text is shown.
* @param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
* @return true if the user has selected a spinner item, false if not.
*/
public boolean selectionMade(Spinner spinner) {
return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
}
/**
* Returns a TextView with the initialText the first time getView is called.
* So the Spinner has an initialText which does not represent the selected item.
* To use the spinner with initial selection instead call notifyDataSetChanged(),
* after assigning the SpinnerAdapterWithInitialText.
*/
@Override
public View getView(int position, View recycle, ViewGroup container) {
if(initialTextWasShown) {
return super.getView(position, recycle, container);
} else {
initialTextWasShown = true;
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(resource, container, false);
((TextView) view).setText(initialText);
return view;
}
}
}
What Android does when initialising the Spinner, is calling getView for the selected item before calling getView for all items in T[] objects
.
The SpinnerAdapterWithInitialText
returns a TextView
with the initialText
, the first time it is called.
All the other times it calls super.getView
which is the getView
method of ArrayAdapter
which is called if you are using the Spinner normally.
To find out whether the user has selected a spinner item, or if the spinner still displays the initialText
, call selectionMade
and hand over the spinner the adapter is assigned to.
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
I suggest using a mutationObserver to do this. It gives you a lot more control over what is going on. It also gives you more details on how the browse interprets all the keystrokes
Here in TypeScript
import * as React from 'react';
export default class Editor extends React.Component {
private _root: HTMLDivElement; // Ref to the editable div
private _mutationObserver: MutationObserver; // Modifications observer
private _innerTextBuffer: string; // Stores the last printed value
public componentDidMount() {
this._root.contentEditable = "true";
this._mutationObserver = new MutationObserver(this.onContentChange);
this._mutationObserver.observe(this._root, {
childList: true, // To check for new lines
subtree: true, // To check for nested elements
characterData: true // To check for text modifications
});
}
public render() {
return (
<div ref={this.onRootRef}>
Modify the text here ...
</div>
);
}
private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
mutations.forEach(() => {
// Get the text from the editable div
// (Use innerHTML to get the HTML)
const {innerText} = this._root;
// Content changed will be triggered several times for one key stroke
if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
console.log(innerText); // Call this.setState or this.props.onChange here
this._innerTextBuffer = innerText;
}
});
}
private onRootRef = (elt: HTMLDivElement) => {
this._root = elt;
}
}
This is a pre-commit hook which replaces the symlink blobs in the index, with the content of those symlinks.
Put this in .git/hooks/pre-commit
, and make it executable:
#!/bin/sh
# (replace "find ." with "find ./<path>" below, to work with only specific paths)
# (these lines are really all one line, on multiple lines for clarity)
# ...find symlinks which do not dereference to directories...
find . -type l -exec test '!' -d {} ';' -print -exec sh -c \
# ...remove the symlink blob, and add the content diff, to the index/cache
'git rm --cached "$1"; diff -au /dev/null "$1" | git apply --cached -p1 -' \
# ...and call out to "sh".
"process_links_to_nondir" {} ';'
# the end
We use POSIX compliant functionality as much as possible; however, diff -a
is not POSIX compliant, possibly among other things.
There may be some mistakes/errors in this code, even though it was tested somewhat.
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
No, those are nested dictionaries, so that is the only real way (you could use get()
but it's the same thing in essence). However, there is an alternative. Instead of having nested dictionaries, you can use a tuple as a key instead:
tempDict = {("ONE", "TWO", "THREE"): 10}
tempDict["ONE", "TWO", "THREE"]
This does have a disadvantage, there is no (easy and fast) way of getting all of the elements of "TWO"
for example, but if that doesn't matter, this could be a good solution.
Just put ScriptManager
inside form
tag like this:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If it has Master Page
then Put this in the Master Page itself.
What happens is that the recursive call itself results in further recursive behaviour. If you were to write it out you get:
fact(4)
fact(3) * 4;
(fact(2) * 3) * 4;
((fact(1) * 2) * 3) * 4;
((1 * 2) * 3) * 4;
We can achieve by Bootstrap 4 Flexbox:
<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>
d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%
Example: JSFiddle
In cases where one is using android:layout_weight
property to assign available screen space to layout components, for instance
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
/* And we want to add a verical separator here */
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
</LinearLayout>
To add a separator between the existing two layouts which has taken the entire screen space already, we cannot just add another LinearLayout with android:weight:"1"
because that will make three equal width columns which we don't want. Instead, we will decrease the amount of space we will be giving to this new layout.
Final code would look like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
/* *************** ********************** */
/* Add another LinearLayout with android:layout_weight="0.01" and
android:background="#your_choice" */
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.01"
android:background="@android:color/darker_gray"
/>
/* Or View can be used */
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="@android:color/darker_gray"
/>
/* *************** ********************** */
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
...
...
</LinearLayout>
</LinearLayout>
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
Here is the official answer from Microsoft: http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx
Summary if you'd rather not click through:
Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:
MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
Install the DirectX SDK (June 2010)
Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB2565063 with a security fix.
Windows SDK: The Windows SDK 7.1 has exactly the same issue as noted in KB 2717426.
if you want smooth scrolling add behavior
configuration.
document.getElementById('id').scrollIntoView({
behavior: 'smooth'
});
Perhaps try this:
function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
var CCSstyle = undefined, rules;
for(var m in document.styleSheets){
if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
for(var n in rules){
if(rules[n].selectorText == selectorText){
CCSstyle = rules[n].style;
break;
}
}
break;
}
}
if(value == undefined)
return CCSstyle[style]
else
return CCSstyle[style] = value
}
Singletons are NOT bad. It's only bad when you make something globally unique that isn't globally unique.
However, there are "application scope services" (think about a messaging system that makes components interact) - this CALLS for a singleton, a "MessageQueue" - class that has a method "SendMessage(...)".
You can then do the following from all over the place:
MessageQueue.Current.SendMessage(new MailArrivedMessage(...));
And, of course, do:
MessageQueue.Current.RegisterReceiver(this);
in classes that implement IMessageReceiver.
I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.
I tried the following and it worked for me:
#! /bin/bash
var="hello.c"
length=${#var}
endindex=$(expr $length - 4)
echo ${var:0:$endindex}
Output: hel
I changed the plugin folder name. Restart Notepad ++ It works now, a
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
my way:
in gradle.properties:
profile=profile-dev
in build.gradle add VM options -Dspring.profiles.active:
bootRun {
jvmArgs = ["-Dspring.output.ansi.enabled=ALWAYS","-Dspring.profiles.active="+profile]
}
this will override application spring.profiles.active option
Another approach:
declaring an int first with the default fontsize
int txtSize = 16;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setTextSize(txtSize++);
}
});
I know this is a little off the OPs original request but I came across this while looking for a way to use Invoke-WebRequest against a site requiring basic authentication.
The difference is, I did not want to record the password in the script. Instead, I wanted to prompt the script runner for credentials for the site.
Here's how I handled it
$creds = Get-Credential
$basicCreds = [pscredential]::new($Creds.UserName,$Creds.Password)
Invoke-WebRequest -Uri $URL -Credential $basicCreds
The result is the script runner is prompted with a login dialog for the U/P then, Invoke-WebRequest is able to access the site with those credentials. This works because $Creds.Password is already an encrypted string.
I hope this helps someone looking for a similar solution to the above question but without saving the username or PW in the script
I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.
My GOPATH workspace is c:\work\go
and under that I have
/src/pg/main.go (package main)
/src/pg/dbtypes.go (pakage dbtypes)
in main.go
I import "/pg/dbtypes"
Both lines have the same problem
T newT1 = "some text";
T newT2 = (string)t;
The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with
T newT1 = "some text" as T;
T newT2 = t;
you don't need to cast the t since it's already a string, also need to add the constraint
where T : class
You want to use Test-Path
:
Test-Path <path to file> -PathType Leaf
The multi-column index can be used for queries referencing all the columns:
SELECT *
FROM TableName
WHERE Column1=1 AND Column2=2 AND Column3=3
This can be looked up directly using the multi-column index. On the other hand, at most one of the single-column index can be used (it would have to look up all records having Column1=1, and then check Column2 and Column3 in each of those).
Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.
There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.
I used the search term windows explorer tree view C#
in Google to find these links.
The limit is not 2g or 3gb its 4gb for 32bit.
The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.
Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.
4Gig not 3 not 2 got it?
To literally fix your example you would use this:
Sub Normalize()
Dim Ticker As Range
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Sheets("Sheet2").Select
Cells(1, 1).PasteSpecial xlPasteAll
End Sub
To Make slight improvments on it would be to get rid of the Select and Activates:
Sub Normalize()
With Sheets("Sheet1")
.Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
End With
End Sub
but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.
Sub Normalize()
Dim CopyFrom As Range
Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
End Sub
To define the CopyFrom
you can use anything you want to define the range, You could use Range("A2:A65")
, Range("A2",[A65])
, Range("A2", "A65")
all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:
Sub Normalize()
Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value
End Sub
I added the Copy from range, and the Resize
property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.
Listing all foreign keys in a db including description
SELECT
i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
i2.UPDATE_RULE, i2.DELETE_RULE
FROM
information_schema.KEY_COLUMN_USAGE AS i1
INNER JOIN
information_schema.REFERENTIAL_CONSTRAINTS AS i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL
AND i1.TABLE_SCHEMA ='db_name';
restricting to a specific column in a table table
AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'
$ alias gpuom='git push origin master'
$ alias
hit Enter.$ vim ~/.bashrc
and hit Enter (I'm guessing you are familiar with vim).#My custom aliases
alias gpuom='git push origin master'
alias gplom='git pull origin master'
$ alias
hit Enter.First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:
public function win_os(){
ob_start();
system('ipconfig-a');
$mycom=ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
$pmac = strpos($mycom, $findme); // Find the position of Physical text
$mac=substr($mycom,($pmac+36),17); // Get Physical Address
return $mac;
}
And your OS Linux Ubuntu or Linux then this code use:
public function unix_os(){
ob_start();
system('ifconfig -a');
$mycom = ob_get_contents(); // Capture the output into a variable
ob_clean(); // Clean (erase) the output buffer
$findme = "Physical";
//Find the position of Physical text
$pmac = strpos($mycom, $findme);
$mac = substr($mycom, ($pmac + 37), 18);
return $mac;
}
This code may be work OS X.
Simple Example
var request = require('request');
//Custom Header pass
var headersOpt = {
"content-type": "application/json",
};
request(
{
method:'post',
url:'https://www.googleapis.com/urlshortener/v1/url',
form: {name:'hello',age:25},
headers: headersOpt,
json: true,
}, function (error, response, body) {
//Print the Response
console.log(body);
});
RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]
(No space inside your website)
Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
In version 1.1.1:
.*
><
>\n<
If there may be empty trailing spaces, probably there isn't better solution. COALESCE
is just for problems like yours.
const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")
const JSONDisplayer = ({children}) => (
<div>
<pre>{getJsonIndented(children)}</pre>
</div>
)
Then you can easily use it:
const Demo = (props) => {
....
return <JSONDisplayer>{someObj}<JSONDisplayer>
}
Following are the steps to remove mapping of a project from TFS:
(1) Click on View Button.
(2) Open Team Explorer
(3) Click on Source Control
(4) Right click on your project/Directory
(5) Click on Remove Mapping
(6) Finally Delete the Project form local directory.
While testing in the ios8 beta simulator, you may toggle between the "software keyboard" and "hardware keyboard" with ?+K.
UPDATE: Since iOS Simulator 8.0, the shortcut is ?+?+K.
I would imagine that the caching DNS servers you're using aren't behaving properly (or the DNS server for the domain you're resolving isn't working properly). You can try to fix the former possibility.
Do you have at least 2 name servers registered on your network adapter? You could always swap your computer over to use a different caching DNS server to rule this out. Try Google's:
8.8.8.8
8.8.4.4
#include<iostream>
int main()
{//initialize variables
int limit;
int num;
int sum=0;
int counter=0;
cout<<"Enter limit of numbers you wish to see"<<" ";
cin>>limit;
cout<<endl;
while(counter<limit)
{
cout<<"Enter number "<<endl;
cin>>num;
sum=sum+num;
counter++;
}
cout<<"The sum of numbers is "<<" "<<endl
return 0;
}
Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.
System specs:
import timeit
d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000
print (len(d.keys()))
# 1000
print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000)) # 1
print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2
Result:
1) = 37.0100378
2) = 37.002148899999995
So it seems that len(d.keys())
is currently faster than just using len()
.
Label1.Text = dt.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
will output:
07 Mai 2009 | 08:16 | 13 | +02:00 | +02 | +2
I'm in Denmark, my Offset from GMT is +2 hours, witch is correct.
if you need to get the CLIENT Offset, I recommend that you check a little trick that I did. The Page is in a Server in UK where GMT is +00:00 and, as you can see you will get your local GMT Offset.
Regarding you comment, I did:
DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1.ToUniversalTime();
Label1.Text = dt1.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
Label2.Text = dt2.ToString("dd MMM yyyy | hh:mm | FF | ZZZ | ZZ | Z");
and I get this:
07 Mai 2009 | 08:24 | 14 | +02:00 | +02 | +2
07 Mai 2009 | 06:24 | 14 | ZZZ | ZZ | Z
I get no Exception, just ... it does nothing with capital Z :(
I'm sorry, but am I missing something?
Reading carefully the MSDN on Custom Date and Time Format Strings
there is no support for uppercase 'Z'.
You could use
options(warn=-1)
But note that turning off warning messages globally might not be a good idea.
To turn warnings back on, use
options(warn=0)
(or whatever your default is for warn
, see this answer)
To expand on Solomon Rutzky's answer, if you are looking for a piece of data that shows up in a range (i.e. more than once but less than 5x), you can use
having count(*) > 1 and count(*) < 5
And you can use whatever qualifiers you desire in there - they don't have to match, it's all just included in the 'having' statement. https://webcheatsheet.com/sql/interactive_sql_tutorial/sql_having.php
var val = $.parseJSON(data);
if(val.success == true)
{
setTimeout(function(){ location.reload(); }, 5000);
}
function array_unique(nav_array) {
nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });
var ret = [nav_array[0]];
// Start loop at 1 as element 0 can never be a duplicate
for (var i = 1; i < nav_array.length; i++) {
if (nav_array[i-1] !== nav_array[i]) {
ret.push(nav_array[i]);
}
}
return ret;
}
Apparently, you did it right. But here is a list of things you'll need with examples from a working application:
1) A context.xml file in META-INF, specifying your data source:
<Context>
<Resource
name="jdbc/DsWebAppDB"
auth="Container"
type="javax.sql.DataSource"
username="sa"
password=""
driverClassName="org.h2.Driver"
url="jdbc:h2:mem:target/test/db/h2/hibernate"
maxActive="8"
maxIdle="4"/>
</Context>
2) web.xml which tells the container that you are using this resource:
<resource-env-ref>
<resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml
, but it's similar in hibernate.cfg.xml
<persistence-unit name="dswebapp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
</properties>
</persistence-unit>
The solution for PyMongo (Python mongo):
db.example.update({}, {'$unset': {'tags.words':1}}, multi=True);
There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF
Regards Gerry
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
If you need in range use:
public int nextFreePort(int from, int to) {
int port = randPort(from, to);
while (true) {
if (isLocalPortFree(port)) {
return port;
} else {
port = ThreadLocalRandom.current().nextInt(from, to);
}
}
}
private boolean isLocalPortFree(int port) {
try {
new ServerSocket(port).close();
return true;
} catch (IOException e) {
return false;
}
}
Fiddle of working example: http://jsfiddle.net/tdpLdqpo/1/
HTML:
<h1 id="test1">
How wide is this text?
</h1>
<div id="result1"></div>
<hr/>
<p id="test2">
How wide is this text?
</p>
<div id="result2"></div>
<hr/>
<p id="test3">
How wide is this text?<br/><br/>
f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
</p>
<div id="result3"></div>
JavaScript code:
function getTextWidth(text, font) {
var canvas = getTextWidth.canvas ||
(getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
$("#result1")
.text("answer: " +
getTextWidth(
$("#test1").text(),
$("#test1").css("font")) + " px");
$("#result2")
.text("answer: " +
getTextWidth(
$("#test2").text(),
$("#test2").css("font")) + " px");
$("#result3")
.text("answer: " +
getTextWidth(
$("#test3").text(),
$("#test3").css("font")) + " px");
in spring MultipartFile file;
org.springframework.web.multipart.MultipartFile
file.getContentType();
Add to ~/.bash_profile
:
function killTcpListen () {
kill -QUIT $(sudo lsof -sTCP:LISTEN -i tcp:$1 -t)
}
Then source ~/.bash_profile
and run
killTcpListen 8080
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
I happened to have the same problem just now. However, the first few answers don't work for me.I propose a solution:change the .classpath file.For example,you can define the classpathentry node's path like this: path="src/prefix1/java" or path="src/prefix1/resources". Hope it can help.
Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page
.
So its easy as changing:
$(document).scroll(function() { // OR $(window).scroll(function() {
didScroll = true;
});
to
$('div#page').scroll(function() {
didScroll = true;
});
Check out our new podcast at Crafty Coders. It covers programming topics (mostly .net, but also other languages and topics).
You should create a function inside activity to open new fragment and pass the activity reference to the fragment and on some event inside fragment call this function.
You don't need css or html tricks for it. Font Awesome has built in class for it - fa-circle To stack multiple icons together you can use fa-stack class on the parent div
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-flag fa-stack-1x fa-inverse"></i>
</span>
//And we have now facebook icon inside circle:)
Laravel 4+ offers you these methods: whereDay()
, whereMonth()
, whereYear()
(#3946) and whereDate()
(#6879).
They do the SQL DATE()
work for you, and manage the differences of SQLite.
Your result can be achieved as so:
->whereDate('date', '<=', '2014-07-10')
For more examples, see first message of #3946 and this Laravel Daily article.
Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE()
SQL function has to be applied on each record, thus discarding the possible index.
Here are some ways to make the comparison (but please read notes below):
->where('date', '<=', '2014-07-10 23:59:59')
->where('date', '<', '2014-07-11')
// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');
->where('date', '<', $dayAfter)
Notes:
What about:
@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs
For what you are wanting to do, you should use the enumerated()
method on your Array:
for (index, element) in list.enumerated() {
print("\(index) - \(element)")
}
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
I found this very useful.
If you are getting the following message
start: Rejected send message, 1 matched rules; type="method_call", sender=":1.84" (uid=1000 pid=3215 comm="start mongodb ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
shriprasad@shriprasad-HP-430-Notebook-PC:/var/lib/mongodb$ mongo
You must be trying to start the mongodb service as user other than root. You must be root user. Thus log in as root and then run following command as follows:
sudo bash
followed by
service mongodb start
the window
contains everything, so you can call window.screen
and window.document
to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/
You can also see the contents of the object in firebug/dev tools like this:
console.dir(window);
console.dir(document);
console.dir(screen);
window
is the root of everything, screen
just has screen dimensions, and document
is top DOM object. so you can think of it as window
being like a super-document
...
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
By the way, instead of generating the x and y coordinates yourself, you can also use the curve()
function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).
see
help(curve)
and its examples.
And if you want to add som text to properly label the mean and standard deviations, you can use the text()
function (see also plotmath
, for annotations with mathematical symbols) .
see
help(text)
help(plotmath)
According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.
And too many addresses in this post.
Well, you are having a valid access token to access your information and not others( this is because you got logged in and you have given permission to access your information). But the picture owner has not done the same (logged in + permission ) and so you are getting a violation error.
To obtain permission see this link and decide what kind of informations you want from any user and decide the permissions. Later on embed this in your code. (In the login function call)
Thanks
I find it incredible what type of trouble the compiler goes through to sugar code the use of Outer Variables:
string output = "helo world!";
Action action = () => Console.WriteLine(output);
output = "hello!";
action();
This actually prints hello!
. Why? Because the compiler creates a nested class for the delegate, with public fields for all outer variables and inserts setting-code before every single call to the delegate :) Here is above code 'reflectored':
Action action;
<>c__DisplayClass1 CS$<>8__locals2;
CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.output = "helo world!";
action = new Action(CS$<>8__locals2.<Main>b__0);
CS$<>8__locals2.output = "hello!";
action();
Pretty cool I think.
You get your browser's language for your button. There's no way to change it programmatically.
A possible explanation is that the selectlist value that you are binding to is not a string.
So in that example, is the parameter 'PageOptionsDropDown' a string in your model? Because if it isn't then the selected value in the list wouldn't be shown.
Move favicon.ico to your assets and then to img folder, and after that only change your icon link tag in header. It helps me when favicon was not displayed at all.
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
index.js
to index.pug
'/'
route: res.render('index.pug')
- instead of res.render('index')
DEBUG=express:view
Now it works like a charm.You need to tell MySQL which database to use:
USE database_name;
before you create a table.
In case the database does not exist, you need to create it as:
CREATE DATABASE database_name;
followed by:
USE database_name;
Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).
The line
base64String = Base64.encode(byteArray);
converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.
Here's a slide in/out animation between fragments:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.animator.enter_anim, R.animator.exit_anim);
transaction.replace(R.id.listFragment, new YourFragment());
transaction.commit();
We are using an objectAnimator.
Here are the two xml files in the animator subfolder.
enter_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="x"
android:valueFrom="2000"
android:valueTo="0"
android:valueType="floatType" />
</set>
exit_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set>
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="x"
android:valueFrom="0"
android:valueTo="-2000"
android:valueType="floatType" />
</set>
I hope that would help someone.
Unfortunately, (for practical and security reasons I guess), if you want to add/copy local content, it must be located under the same root path than the Dockerfile
.
From the documentation:
The <src> path must be inside the context of the build; you cannot ADD ../something/something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon.
EDIT: There's now an option (-f
) to set the path of your Dockerfile ; it can be used to achieve what you want, see @Boedy 's response.
From C++ FAQ Lite -
Use references when you can, and pointers when you have to.
References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
The exception to the above is where a function's parameter or return value needs a "sentinel" reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references must always alias objects, not a dereferenced NULL pointer).
Note: Old line C programmers sometimes don't like references since they provide reference semantics that isn't explicit in the caller's code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.
Two other ways are strcpy(str, "");
and string[0] = 0
To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.
#include <string.h>
...
int i=0;
for(i=0;i<strlen(string);i++)
{
string[i] = 0;
}
In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.
At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.
It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)
I hope this was useful for anybody ;)
As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).
Use Spring's Numberformatter instead, which is thread safe.
Run this code in your powershell or cmd
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
I have found Transform Feedback to be a useful tool for debugging vertex shaders. You can use this to capture the values of VS outputs, and read them back on the CPU side, without having to go through the rasterizer.
Here is another link to a tutorial on Transform Feedback.