One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
maybe requests-futures is another choice.
from requests_futures.sessions import FuturesSession
session = FuturesSession()
# first request is started in background
future_one = session.get('http://httpbin.org/get')
# second requests is started immediately
future_two = session.get('http://httpbin.org/get?foo=bar')
# wait for the first request to complete, if it hasn't already
response_one = future_one.result()
print('response one status: {0}'.format(response_one.status_code))
print(response_one.content)
# wait for the second request to complete, if it hasn't already
response_two = future_two.result()
print('response two status: {0}'.format(response_two.status_code))
print(response_two.content)
It is also recommended in the office document. If you don't want involve gevent, it's a good one.
Had the same problem until I tried deleting the .git folder. It worked. I guess this type of problem can have different causes.
Just remember that string comparison like "x" > "X" is case-sensitive
"aa" < "ab" //true
"aa" < "Ab" //false
You can use .toLowerCase()
to compare without case sensitivity.
After struggling with this problem I took three steps:
<body></body>
tags rather than in the <head></head>
.
These worked for me but there may be different behaviors based on the browser you are using.Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
The MACAddress property of the Win32_NetworkAdapterConfiguration WMI class can provide you with an adapter's MAC address. (System.Management Namespace)
MACAddress
Data type: string
Access type: Read-only
Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter.
Example: "00:80:C7:8F:6C:96"
If you're not familiar with the WMI API (Windows Management Instrumentation), there's a good overview here for .NET apps.
WMI is available across all version of windows with the .Net runtime.
Here's a code example:
System.Management.ManagementClass mc = default(System.Management.ManagementClass);
ManagementObject mo = default(ManagementObject);
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (var mo in moc) {
if (mo.Item("IPEnabled") == true) {
Adapter.Items.Add("MAC " + mo.Item("MacAddress").ToString());
}
}
This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.
Check Mike's answer to his own question here: stackoverflow question 24705877
This solved the issue for me both command line AND within eclipse.
Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.
In a Windows Forms project:
For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;
Here is a middle of the road approach that doesn't rely on any external libraries. I use list comprehension to exclude overlaps between abbreviations and terminators as well as to exclude overlaps between variations on terminations, for example: '.' vs. '."'
abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro': 'brother', 'mrs.': 'mistress', 'ms.': 'miss', 'jr.': 'junior', 'sr.': 'senior',
'i.e.': 'for example', 'e.g.': 'for example', 'vs.': 'versus'}
terminators = ['.', '!', '?']
wrappers = ['"', "'", ')', ']', '}']
def find_sentences(paragraph):
end = True
sentences = []
while end > -1:
end = find_sentence_end(paragraph)
if end > -1:
sentences.append(paragraph[end:].strip())
paragraph = paragraph[:end]
sentences.append(paragraph)
sentences.reverse()
return sentences
def find_sentence_end(paragraph):
[possible_endings, contraction_locations] = [[], []]
contractions = abbreviations.keys()
sentence_terminators = terminators + [terminator + wrapper for wrapper in wrappers for terminator in terminators]
for sentence_terminator in sentence_terminators:
t_indices = list(find_all(paragraph, sentence_terminator))
possible_endings.extend(([] if not len(t_indices) else [[i, len(sentence_terminator)] for i in t_indices]))
for contraction in contractions:
c_indices = list(find_all(paragraph, contraction))
contraction_locations.extend(([] if not len(c_indices) else [i + len(contraction) for i in c_indices]))
possible_endings = [pe for pe in possible_endings if pe[0] + pe[1] not in contraction_locations]
if len(paragraph) in [pe[0] + pe[1] for pe in possible_endings]:
max_end_start = max([pe[0] for pe in possible_endings])
possible_endings = [pe for pe in possible_endings if pe[0] != max_end_start]
possible_endings = [pe[0] + pe[1] for pe in possible_endings if sum(pe) > len(paragraph) or (sum(pe) < len(paragraph) and paragraph[sum(pe)] == ' ')]
end = (-1 if not len(possible_endings) else max(possible_endings))
return end
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1:
return
yield start
start += len(sub)
I used Karl's find_all function from this entry: Find all occurrences of a substring in Python
On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:
var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;
That allows me to get the real relative position of element on document, even if it has been scrolled.
I was having a similar problem. (No problems training with GradientDescent optimizer, but error raised when using to Adam Optimizer, or any other optimizer with its own variables)
Changing to an interactive session solved this problem for me.
sess = tf.Session()
into
sess = tf.InteractiveSession()
If you use AND
and OR
, you'll eventually get tripped up by something like this:
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
Want to guess what $truthiness
equals?
If you said false
... bzzzt, sorry, wrong!
$truthiness
above has the value true
. Why? =
has a higher precedence than and
. The addition of parentheses to show the implicit order makes this clearer:
($truthiness = $this_one) and $that
If you used &&
instead of and
in the first code example, it would work as expected and be false
.
As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =
:
$truthiness = ($this_one and $that)
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
Here is another way, by rotating element
with the scrollbar
for 180deg,
wrapping it's content
into another element, and rotating
that wrapper
for -180deg
.
Check the snippet below
div {_x000D_
display: inline-block;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 2px solid black;_x000D_
margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
direction: rtl;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
direction: ltr;_x000D_
margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
direction: rtl;_x000D_
transform: rotate(180deg);_x000D_
overflow-y: hidden;_x000D_
overflow-x: scroll;_x000D_
background: tomato;_x000D_
padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
direction: ltr;_x000D_
display: inline-block;_x000D_
transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
<p>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content_x000D_
<br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
I am new in Swift 3, but looking the String
(index) syntax for analogy I think that index is like a "pointer" constrained to string and Int can help as an independent object. Using the base + offset syntax , then we can get the i-th character from string with the code bellow:
let s = "abcdefghi"
let i = 2
print (s[s.index(s.startIndex, offsetBy:i)])
// print c
For a range of characters ( indexes) from string using String (range) syntax we can get from i-th to f-th characters with the code bellow:
let f = 6
print (s[s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 )])
//print cdefg
For a substring (range) from a string using String.substring (range) we can get the substring using the code bellow:
print (s.substring (with:s.index(s.startIndex, offsetBy:i )..<s.index(s.startIndex, offsetBy:f+1 ) ) )
//print cdefg
Notes:
The i-th and f-th begin with 0.
To f-th, I use offsetBY: f + 1, because the range of subscription use ..< (half-open operator), not include the f-th position.
Of course must include validate errors like invalid index.
This is the real solution:
<td>
<span class="inline-flag">
<i class="flag-bfh-ES"></i>
<span>+34 666 66 66 66</span>
</span>
</td>
css:
.inline-flag {
position: relative;
display: inline;
line-height: 14px; /* play with this */
}
.inline-flag > i {
position: absolute;
display: block;
top: -1px; /* play with this */
}
.inline-flag > span {
margin-left: 18px; /* play with this */
}
Example, images which always before text:
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
Don't declare function inside a loop (like foreach
, for
, while
...) ! Declare before them.
You should include that file (wherein that function exists) only once. So,
instead of : include ("functions.php");
use: include_once("functions.php");
If none of above helps, before function declaration, add a check to avoid re-declaration:
if (!function_exists('your_function_name')) {
function your_function_name() {
........
}
}
Use this simple code for generate med-strong password 12 length
$password_string = '!@#$%*&abcdefghijklmnpqrstuwxyzABCDEFGHJKLMNPQRSTUWXYZ23456789';
$password = substr(str_shuffle($password_string), 0, 12);
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
Other way to do it using jQuery CSS method:
$("#id").css({display: "none"});
$("#id").css({display: "block"});
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
I was struggling with this too. My changes weren't being reflected in phpInfo. It wasn't until I stopped my servers and then restarted them again that my changes actually took effect.
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
Yes, it works when with the command npm install --no-optional
Using environment:
I was getting this problem and it turned out I had included my controller both in ui.router and in the html template as in
.config(['$stateProvider',
function($stateProvider) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/views/index.html',
controller: 'DashboardController'
});
}
]);
and
<section data-ng-controller="DashboardController">
ObjectExtractor oe = new ObjectExtractor(document);
SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm(); // Tabula algo.
Page page = oe.extract(1); // extract only the first page
for (int y = 0; y < sea.extract(page).size(); y++) {
System.out.println("table: " + y);
Table table = sea.extract(page).get(y);
for (int i = 0; i < table.getColCount(); i++) {
for (int x = 0; x < table.getRowCount(); x++) {
System.out.println("col:" + i + "/lin:x" + x + " >>" + table.getCell(x, i).getText());
}
}
}
Make sure you also use your intermediate crt (.crt file with a bundle.. some providers also call it bundle or ca certificate). then in your ssl.conf,
SSLCertificateFile </path/for/actual/certificate>
SSLCACertificateFile </path/for/actual/intermediate_certificate>
then restart your webserver :ex for apache use :
sudo service httpd restart
I'm using dictionaries as a sort of "database", so I need to find a key that I can reuse. For my case, if a key's value is None
, then I can take it and reuse it without having to "allocate" another id. Just figured I'd share it.
db = {0:[], 1:[], ..., 5:None, 11:None, 19:[], ...}
keys_to_reallocate = [None]
allocate.extend(i for i in db.iterkeys() if db[i] is None)
free_id = keys_to_reallocate[-1]
I like this one because I don't have to try and catch any errors such as StopIteration
or IndexError
. If there's a key available, then free_id
will contain one. If there isn't, then it will simply be None
. Probably not pythonic, but I really didn't want to use a try
here...
You can define the _CRT_SECURE_NO_WARNINGS symbol to suppress them and undefine it to reinstate them back.
Building upon or rather correcting a bit on what Babak said....
np.percentile DOES VERY MUCH calculate the values of Q1, median, and Q3. Consider the sorted list below:
s1=[18,45,66,70,76,83,88,90,90,95,95,98]
running np.percentile(s1, [25, 50, 75])
returns the actual values from the list:
[69. 85.5 91.25]
However, the quartiles are Q1=68.0, Median=85.5, Q3=92.5, which is the correct thing to say
What we are missing here is the interpolation parameter of the np.percentile
and related functions. By default the value of this argument is linear. This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:
linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.
lower: i.
higher: j.
nearest: i or j, whichever is nearest.
midpoint: (i + j) / 2.
Thus running np.percentile(s1, [25, 50, 75], interpolation='midpoint')
returns the actual results for the list:
[68. 85.5 92.5]
All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.
Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row
For i = 2 To lastA
compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
If IsError(compare) Then
Range("A" & i).Interior.ColorIndex = 3
End If
Next i
End Sub
Only this worked for me (but for "same-domain"):
function MakeIframeFullHeight(iframeElement){
iframeElement.style.width = "100%";
var ifrD = iframeElement.contentDocument || iframeElement.contentWindow.document;
var mHeight = parseInt( window.getComputedStyle( ifrD.documentElement).height ); // Math.max( ifrD.body.scrollHeight, .. offsetHeight, ....clientHeight,
var margins = ifrD.body.style.margin + ifrD.body.style.padding + ifrD.documentElement.style.margin + ifrD.documentElement.style.padding;
if(margins=="") { margins=0; ifrD.body.style.margin="0px"; }
(function(){
var interval = setInterval(function(){
if(ifrD.readyState == 'complete' ){
iframeElement.style.height = (parseInt(window.getComputedStyle( ifrD.documentElement).height) + margins+1) +"px";
setTimeout( function(){ clearInterval(interval); }, 1000 );
}
},1000)
})();
}
you can use either:
MakeIframeFullHeight(document.getElementById("iframe_id"));
or
<iframe .... onload="MakeIframeFullHeight(this);" ....
If are using jQuery, grep may be useful:
var arr = [ a, b, c, , e, f, , g, h ];
arr = jQuery.grep(arr, function(n){ return (n); });
arr
is now [ a, b, c, d, e, f, g];
Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
Following worked for me and it seems very simple as well:
Let's assume that we want to import a script ./data/get_my_file.py and want to access get_set1() function in it.
import sys
sys.path.insert(0, './data/')
import get_my_file as db
print (db.get_set1())
tl;dr
cp -R "/src/project 1/App" "/src/project 2"
Explanation:
Using quotes will cater for spaces in the directory names
cp -R "/src/project 1/App" "/src/project 2"
If the App directory is specified in the destination directory:
cp -R "/src/project 1/App" "/src/project 2/App"
and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"
Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.
Inside a bash script:
cp -R "${1}/App" "${2}"
The CSV format uses commas to separate values, values which contain carriage returns, linefeeds, commas, or double quotes are surrounded by double-quotes. Values that contain double quotes are quoted and each literal quote is escaped by an immediately preceding quote: For example, the 3 values:
test
list, of, items
"go" he said
would be encoded as:
test
"list, of, items"
"""go"" he said"
Any field can be quoted but only fields that contain commas, CR/NL, or quotes must be quoted.
There is no real standard for the CSV format, but almost all applications follow the conventions documented here. The RFC that was mentioned elsewhere is not a standard for CSV, it is an RFC for using CSV within MIME and contains some unconventional and unnecessary limitations that make it useless outside of MIME.
A gotcha that many CSV modules I have seen don't accommodate is the fact that multiple lines can be encoded in a single field which means you can't assume that each line is a separate record, you either need to not allow newlines in your data or be prepared to handle this.
If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.
<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>
Adding in gradle file and sync project:
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'
Adding in Java class:
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties
OkHttpClient client = b.build();
As alternative, php has a built-in timer controller: new EvTimer()
.
It can be used to make a task scheduler, with proper handling of special cases.
This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)
EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.
The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year, it will still time out after(roughly) one hour.
The callback is guaranteed to be invoked only after its timeout has passed (...). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values.
The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.
The first two parameters allows to controls the time delay before execution, and the number of iterations.
The third parameter is a callback function, called at each iteration.
after
Configures the timer to trigger after after seconds.
repeat
If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
https://www.php.net/manual/en/class.evtimer.php
https://www.php.net/manual/en/evtimer.construct.php
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
We can of course easily create this with basic looping and some tempo with sleep()
, usleep()
, or hrtime()
, but new EvTimer()
allows cleans and organized multiples calls, while handling special cases like overlapping.
You can't. With inline styles you are targeting the element directly. You can't use other selectors there.
What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.
Similiary to accepted answer what you could do is use react
and react-router
itself to provide you history
object which you can scope in a file and then export.
history.js
import React from 'react';
import { withRouter } from 'react-router';
// variable which will point to react-router history
let globalHistory = null;
// component which we will mount on top of the app
class Spy extends React.Component {
constructor(props) {
super(props)
globalHistory = props.history;
}
componentDidUpdate() {
globalHistory = this.props.history;
}
render(){
return null;
}
}
export const GlobalHistory = withRouter(Spy);
// export react-router history
export default function getHistory() {
return globalHistory;
}
You later then import Component and mount to initialize history variable:
import { BrowserRouter } from 'react-router-dom';
import { GlobalHistory } from './history';
function render() {
ReactDOM.render(
<BrowserRouter>
<div>
<GlobalHistory />
//.....
</div>
</BrowserRouter>
document.getElementById('app'),
);
}
And then you can just import in your app when it has been mounted:
import getHistory from './history';
export const goToPage = () => (dispatch) => {
dispatch({ type: GO_TO_SUCCESS_PAGE });
getHistory().push('/success'); // at this point component probably has been mounted and we can safely get `history`
};
I even made and npm package that does just that.
Please take a look at ack, which is designed for exactly these situations. Your example of
grep -ircl --exclude=*.{png,jpg} "foo=" *
is done with ack as
ack -icl "foo="
because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do
ack -icl --cpp "foo="
Ion_auth! Looks very promising and small footprint! I like..
This might work...
from p in db.products
select new
{
Owner = (p.price > 0 ?
from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
}
On Ubuntu (doc)
sudo systemctl status mongod
If running
? mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
Docs: https://docs.mongodb.org/manual
Main PID: 1604 (mongod)
Memory: 210.8M
CGroup: /system.slice/mongod.service
+-1604 /usr/bin/mongod --config /etc/mongod.conf
If not running
? mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: https://docs.mongodb.org/manual
To start mongodb
sudo systemctl start mongod
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
Really! after spending 4 hours and insane debugging I found this very strange code at com.fasterxml.jackson.databind.deser.DeserializerCache
if (deser == null) {
try {
deser = _createAndCacheValueDeserializer(ctxt, factory, type);
} catch (Exception e) {
return false;
}
}
Ya, the problem was double setter.
you can try this along, it may help to give a shorter code on large function.
$('#menu li a').on('click', function(){
$('li a.current').toggleClass('current');
});
A great solution, and my thanks to your contributors. For years I've been struggling with a totally crappy color scheme -- using SSH under Windows Vista to a Redhat system, terminal type xterm. The editor would come up with a black background and weird colors for various keywords. Worse -- that weird color scheme sticks in the xterm terminal after leaving Vim.
Really confusing.
Also, Backspace failed during an insert mode, which was nasty to remember -- though Delete did the same thing.
The cure --
In the SSH monitor, select Edit/Settings.
a. Choose Profile Settings/Colors
b. check 'enable ANSI colors'
c. The standard Text colors are probably OK
Add these lines to $HOME/.vimrc:
colorscheme default
if &term == "xterm"
set t_kb=^H
fixdel
endif
NOTE: the ^H MUST be typed as ctrl-V ctrl-H. Seems peculiar, but this seems to work.
To make understanding better , lets find out where exactly bind and connect comes into picture,
Further to positioning of two calls , as clarified by Sourav,
bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.] connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.
We cannot use them interchangeably (even when we have client/server on same machine) because of specific roles and corresponding implementation.
I will further recommend to correlate these calls TCP/IP handshake .
So , who will send SYN here , it will be connect() . While bind() is used for defining the communication end point.
Hope this helps!!
Try to use the func below to add colorbar:
def add_colorbar(mappable):
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
last_axes = plt.gca()
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = fig.colorbar(mappable, cax=cax)
plt.sca(last_axes)
return cbar
Then you codes need to be modified as:
fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)
You can combine insertAdjacentHTML method and document.currentScript property.
The insertAdjacentHTML()
method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position:
'beforebegin'
: Before the element itself.'afterbegin'
: Just inside the element, before its first child.'beforeend'
: Just inside the element, after its last child.'afterend'
: After the element itself.The document.currentScript
property returns the <script>
element whose script is currently being processed. Best position will be beforebegin — new HTML will be inserted before <script>
itself. To match document.write
's native behavior, one would position the text afterend, but then the nodes from consecutive calls to the function aren't placed in the same order as you called them (like document.write
does), but in reverse. The order in which your HTML appears is probably more important than where they're place relative to the <script>
tag, hence the use of beforebegin.
document.currentScript.insertAdjacentHTML(
'beforebegin',
'This is a document.write alternative'
)
_x000D_
Read-Host
is a simple option for getting string input from a user.
$name = Read-Host 'What is your username?'
To hide passwords you can use:
$pass = Read-Host 'What is your password?' -AsSecureString
To convert the password to plain text:
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
As for the type returned by $host.UI.Prompt()
, if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member
(for example, $results | gm
). The result is a Dictionary where the key is the name of a FieldDescription
object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field']
.
To access information without invoking a method, leave the parentheses off:
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions
will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>)
.
It's python source parser failure on sum.up=False
named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation()
returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.
What you need to do is to modify the interface, so that it is asynchronous:
interface IIO
{
Task DoOperationAsync(); // note: no async here
}
class IOImplementation : IIO
{
public async Task DoOperationAsync()
{
// perform the operation here
}
}
This way, the user will see that the operation is async
and they will be able to await
it. This also pretty much forces the users of your code to switch to async
, but that's unavoidable.
Also, I assume using StartNew()
in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task()
is even worse, that won't even work, because you don't Start()
the Task
.)
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
This is what it works for me in Swift:
override func viewWillDisappear(_ animated: Bool) {
if self.navigationController?.viewControllers.index(of: self) == nil {
// back button pressed or back gesture performed
}
super.viewWillDisappear(animated)
}
In case it helps anyone, I had this exact same problem and discovered that it was caused by the "Do Not Track Plus" Chrome Extension (version 2.0.8). When I disabled that extension, the image loaded without error.
No, it's not possible.
It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".
Faced same issue because of multiple .gitconfig
files in windows, followed below steps to fix the same:
Step 1: Open Git BASH
Step 2: Look for .gitconfig
, executing following command:
git config --list --global --show-origin
Step 3: Copy the below content in .gitconfig
:
[http]
proxy = http://YOUR_PROXY_USERNAME:[email protected]:YOUR.PROXY.SERVER.PORT
sslverify = false
[https]
proxy = http://YOUR_PROXY_USERNAME:[email protected]:YOUR.PROXY.SERVER.PORT
sslverify = false
[url "http://github.com/"]
insteadOf = git://github.com/
[user]
name = Arpit Aggarwal
email = [email protected]
This works for both GET and POST:
@Context
private HttpServletRequest httpRequest;
private void printRequest(HttpServletRequest httpRequest) {
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}
Yes, take a look at this thread which talks about the differences between platforms.
How to detect right-click event for Mac OS
BUTTON3
is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.
Using fancybox version: 2.1.5 and tried all of the different options suggest here and none of them worked still showing the scrollbar.
$('.foo').click(function(e){
$.fancybox({
href: $(this).data('href'),
type: 'iframe',
scrolling: 'no',
iframe : {
scrolling : 'no'
}
});
e.preventDefault();
});
So did some debugging in the code until I found this, so its overwriting all options I set and no way to overwrite this using the many options.
if (type === 'iframe' && isTouch) {
coming.scrolling = 'scroll';
}
In the end the solutions was to use CSS !important hack.
.fancybox-inner {
overflow: hidden !important;
}
The line of code responsible is:
current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
Fancybox used to be a reliable working solution now I am finding nothing but inconsistencies. Actually debating about downgrading now even after purchasing a developers license. More info here if you didn't realize you needed one for commercial project: https://stackoverflow.com/a/8837258/560287
You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step
geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx
Here's a pure VBA solution because Excel can hold joined cells:
Public Function GetIndexForColumn(Column As String) As Long
Dim astrColumn() As String
Dim Result As Long
Dim i As Integer
Dim n As Integer
Column = UCase(Column)
ReDim astrColumn(Len(Column) - 1)
For i = 0 To (Len(Column) - 1)
astrColumn(i) = Mid(Column, (i + 1), 1)
Next
n = 1
For i = UBound(astrColumn) To 0 Step -1
Result = (Result + ((Asc(astrColumn(i)) - 64) * n))
n = (n * 26)
Next
GetIndexForColumn = Result
End Function
Basically, this function does the same as any Hex to Dec function, except that it only takes alphabetical chars (A = 1, B = 2, ...). The rightmost char counts single, each char to the left counts 26 times the char right to it (which makes AA = 27 [1 + 26], AAA = 703 [1 + 26 + 676]). The use of UCase() makes this function case-insensitive.
This is a Python 101 type question,
It's a simple question but one where the answer is not so simple.
In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.
To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.
Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.
If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.
print(bytesThing)
Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.
Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation
I'm not sure exactly how to use it.
Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).
You need to create a new indent level after each colon:
for x in range(0, 50):
print x
print 2*x
print x
In this code, the first two print
statements are "inside" the body of the for
statement because they are indented more than the line containing the for
. The third print
is outside because it is indented less than the previous (nonblank) line.
If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.
Finally, certain statements, like lambda
feature a colon, but cannot have a multiline block as the body.
This also work proper in chrome and internet Explorer
$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();
Put according your choice possition value of DropDown 0,1,2,3,4.....
This may be too simple, but I always use:
SELECT COUNT(*)>0 FROM `table` WHERE condition;
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
I also have the issue because of i have compile 'com.android.support:appcompat-v7:24.0.0-alpha1' but i added recyclerview liberary compile 'com.android.support:recyclerview-v7:24.0.2'..i changed the version as same as compat like (24.0.2 intead of 24.0.0).
i got the answer..may be it will help for someone.
According to man(2)stat you can use the S_ISDIR macro on the st_mode field:
bool isdir = S_ISDIR(st.st_mode);
Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.
try with @disabled and jquery, in that way you can get the value on the Controller.
Html.DropDownList("Types", Model.Types, new {@class = "your_class disabled", @disabled= "disabled" })
Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes
<script>
function clickSubmit() {
$("select.disabled").attr("disabled", false);
setTimeout(function () {
$("select.disabled").attr("disabled", true);
}, 500);
}
</script>
submit button like this.
<button type="submit" value="Submit" onclick="clickSubmit();">Save</button>
in case of inputs, just use @readonly="readonly"
@Html.TextBoxFor("Types",Model.Types, new { @class = "form-control", @readonly= "readonly" })
I've used an empty :after
element and decorated one border on it. You can even use CSS transforms to rotate it for a slanted line. Result: pure CSS, no extra HTML elements! Downside: doesn't wrap across multiple lines, although IMO you shouldn't use strikethrough on large blocks of text anyway.
s,_x000D_
strike {_x000D_
text-decoration: none;_x000D_
/*we're replacing the default line-through*/_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
/* keeps it from wrapping across multiple lines */_x000D_
}_x000D_
_x000D_
s:after,_x000D_
strike:after {_x000D_
content: "";_x000D_
/* required property */_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
border-top: 2px solid red;_x000D_
height: 45%;_x000D_
/* adjust as necessary, depending on line thickness */_x000D_
/* or use calc() if you don't need to support IE8: */_x000D_
height: calc(50% - 1px);_x000D_
/* 1px = half the line thickness */_x000D_
width: 100%;_x000D_
transform: rotateZ(-4deg);_x000D_
}
_x000D_
<p>Here comes some <strike>strike-through</strike> text!</p>
_x000D_
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Oracles Java Tutorial for File Choosers: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Note getSelectedFile()
returns the selected folder, despite the name.
getCurrentDirectory()
returns the directory of the selected folder.
import javax.swing.*;
public class Example
{
public static void main(String[] args)
{
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
}
}
For mac:
Click Android Studio on top -> Click on Preferences -> Languages & Framework
-> Select Flutter
-> Browse Flutter SDK Path you have download link ["https://flutter.dev/docs/get-started/install/macos"]
-> Click OK ENJOY!!!!!
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).
for you you should do the following:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
We can use Stack and push "i" into the stack every time we encounter the condition "arr[i]==value"
Check this:
static void getindex(int arr[], int value)
{
Stack<Integer>st= new Stack<Integer>();
int n= arr.length;
for(int i=n-1; i>=0 ;i--)
{
if(arr[i]==value)
{
st.push(i);
}
}
while(!st.isEmpty())
{
System.out.println(st.peek()+" ");
st.pop();
}
}
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
For non-sealed classes simply inherit from them:
public class Vector : List<int> { }
But for sealed classes it's possible to simulate typedef behavior with such base class:
public abstract class Typedef<T, TDerived> where TDerived : Typedef<T, TDerived>, new()
{
private T _value;
public static implicit operator T(Typedef<T, TDerived> t)
{
return t == null ? default : t._value;
}
public static implicit operator Typedef<T, TDerived>(T t)
{
return t == null ? default : new TDerived { _value = t };
}
}
// Usage examples
class CountryCode : Typedef<string, CountryCode> { }
class CurrencyCode : Typedef<string, CurrencyCode> { }
class Quantity : Typedef<int, Quantity> { }
void Main()
{
var canadaCode = (CountryCode)"CA";
var canadaCurrency = (CurrencyCode)"CAD";
CountryCode cc = canadaCurrency; // Compilation error
Concole.WriteLine(canadaCode == "CA"); // true
Concole.WriteLine(canadaCurrency); // CAD
var qty = (Quantity)123;
Concole.WriteLine(qty); // 123
}
long timeNow = System.currentTimeMillis();
System.out.println(new Date(timeNow));
Fri Apr 04 14:27:05 PDT 2014
When your native query is based on joins, in that case you can get the result as list of objects and process it.
one simple example.
@Autowired
EntityManager em;
String nativeQuery = "select name,age from users where id=?";
Query query = em.createNativeQuery(nativeQuery);
query.setParameter(1,id);
List<Object[]> list = query.getResultList();
for(Object[] q1 : list){
String name = q1[0].toString();
//..
//do something more on
}
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
GCM is being replaced with FCM
Have a look at developers.android.com - Google replaced C2DM with GCM Demo Implementation / How To
1) You need to check on the server what HTTP response you are getting from the Google servers. Make sure it is a 200 OK response, so you know the message was sent. If you get another response (302, etc) then the message is not being sent successfully.
2) You also need to check that the Registration ID you are using is correct. If you provide the wrong Registration ID (as a destination for the message - specifying the app, on a specific device) then the Google servers cannot successfully send it.
3) You also need to check that your app is successfully registering with the Google servers, to receive push notifications. If the registration fails, you will not receive messages.
Here is a good question you may should have a look at it: How to add a push notification in my own android app
Also here is a good blog with a really simple how to: http://blog.serverdensity.com/android-push-notifications-tutorial/
public class Main {
public static List<String> list = new ArrayList();
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(222);
l.add(100);
l.add(45);
l.add(415);
l.add(311);
l.sort(null);
System.out.println(l.get(0));
}
}
without l.sort(null) returned 222
with l.sort(null) returned 45
R is missing a concurrent assignment as proposed by Edsger W. Dijkstra in A Discipline of Programming, 1976, ch.4, p.29. This would allow for an elegant solution:
a, b <- b, a # swap
a, b, c <- c, a, b # rotate right
With OpenSSL you can convert pfx to Apache compatible format with next commands:
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
First command extracts public key to domain.cer
.
Second command extracts private key to domain.key
.
Update your Apache configuration file with:
<VirtualHost 192.168.0.1:443>
...
SSLEngine on
SSLCertificateFile /path/to/domain.cer
SSLCertificateKeyFile /path/to/domain.key
...
</VirtualHost>
in your main layout put this in the head at the bottom of everything
@stack('styles')
and in your view put this
@push('styles')
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
@endpush
basically a placeholder so the links will appear on your main layout, and you can see custom css files on different pages
I use something like:
mysql --defaults-extra-file=/path/to/config.cnf
or
mysqldump --defaults-extra-file=/path/to/config.cnf
Where config.cnf contains:
[client]
user = "whatever"
password = "whatever"
host = "whatever"
This allows you to have multiple config files - for different servers/roles/databases. Using ~/.my.cnf will only allow you to have one set of configuration (although it may be a useful set of defaults).
If you're on a Debian based distro, and running as root, you could skip the above and just use /etc/mysql/debian.cnf to get in ... :
mysql --defaults-extra-file=/etc/mysql/debian.cnf
I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.
private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
{
// row represent particular row you want to bold its content.
for (i = 0; i < columnCollection.Count; i++)
{
DataColumn col = columnCollection[i];
xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
// Some Font Styles
xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
//xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
}
}
You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection
to your columns name and change col.Caption
to specific column name.
Alternate
You may do this to cell of excel sheet you want bold.
xlWorkSheet.Cells[row, column].Style.Font.Bold = true;
In Sublime Text (confirmed in both v2.x and v3.x) there is a menu command:
View -> Syntax -> Open all with current extension as ...
If you want to do binary, give a --binary
option when you run git diff
.
You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.
Download WinSCP .NET assembly.
The latest package as of now is WinSCP-5.17.10-Automation.zip
;
Extract the .zip
archive along your script;
Use a code like this (based on the official PowerShell upload example):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
You can have WinSCP generate the PowerShell script for the upload for you:
You will get a code like above with all session and transfer settings filled in.
(I'm the author of WinSCP)
What ultimately worked for me was the following steps:
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
An example to make things concrete. If you have a selection thus:
<select onchange="" onblur="">
<option>....
</select>
the onblur()
is called when you navigate away. The onchange()
is called when you select a different option from the selection - i.e. you change what it's currently selected as.
If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);
That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps - Luke
You should use Directory.CreateDirectory.
Some of the above answers will give you a black bar on top if you set your screen bound 20px, other will keep reduce your webview screen if you use webview.frame.size.height -20px; Try this one then, it works on any ios and no need to change css, put in inside
- (void)webViewDidFinishLoad:(UIWebView*)theWebView {
//is it IOS7 and up
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
//get the device screen size
CGRect screenBounds = [[UIScreen mainScreen] bounds];
//reduce the height by 20px
int x= screenBounds.size.height -20;
//set the webview top pos 20px so it is under the status bar and reduce the size by 20px
[theWebView setFrame:CGRectMake(0, 20, theWebView.frame.size.width, x )];
}
Target parameters:
float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);
Your original file:
var image = new Bitmap(file);
Target sizing (scale factor):
float scale = Math.Min(width / image.Width, height / image.Height);
The resize including brushing canvas first:
var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);
// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;
var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
And don't forget to do a bmp.Save(filename)
to save the resulting file.
Without modifying your csv file you can:
excel will properly format and separate your csv cells as text formatted ignoring auto date formats.
Kind of a silly work around, but it beats modifying the csv data before importing. Andy Baird and Richard sort of eluded to this method, but missed a couple important steps.
anchor.href = null;
I would write GetValue
as below
public static T GetValue<T>(this JToken jToken, string key, T defaultValue = default(T))
{
dynamic ret = jToken[key];
if (ret == null) return defaultValue;
if (ret is JObject) return JsonConvert.DeserializeObject<T>(ret.ToString());
return (T)ret;
}
This way you can get the value of not only the basic types but also complex objects. Here is a sample
public class ClassA
{
public int I;
public double D;
public ClassB ClassB;
}
public class ClassB
{
public int I;
public string S;
}
var jt = JToken.Parse("{ I:1, D:3.5, ClassB:{I:2, S:'test'} }");
int i1 = jt.GetValue<int>("I");
double d1 = jt.GetValue<double>("D");
ClassB b = jt.GetValue<ClassB>("ClassB");
Well guys, the solution to the problem is the following:
1) Folder 00A: 2) Counter: the last number 3) Help: the last number
Folder Perflib:
Last Counter: 00A folder´s Counter
Last Help: 00A folder´s Help
Ready, verify the same number in both. success
AsyncTask is really clunky. Coroutines are a cleaner alternative (just sprinkle a couple of keywords and your sync code becomes async).
// Step 1: add `suspend` to your fun
suspend fun roomFun(...): Int
suspend fun notRoomFun(...) = withContext(Dispatchers.IO) { ... }
// Step 2: launch from coroutine scope
private fun myFun() {
lifecycleScope.launch { // coroutine on Main
val queryResult = roomFun(...) // coroutine on IO
doStuff() // ...back on Main
}
}
Dependencies (adds coroutine scopes for arch components):
// lifecycleScope:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha04'
// viewModelScope:
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha04'
-- Updates:
08-May-2019: Room 2.1 now supports suspend
13-Sep-2019: Updated to use Architecture components scope
I got it and explained in below:
//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;
<table id="tableID" class="table table-condensed">
<thead>
<tr>
<th><label>From Group</lable></th>
<th><label>To Group</lable></th>
<th><label>Level</lable></th>
</tr>
</thead>
<tbody>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
<tr id="rowCount">
<td>
<select >
<option value="">select</option>
<option value="G1">G1</option>
<option value="G2">G2</option>
<option value="G3">G3</option>
<option value="G4">G4</option>
</select>
</td>
<td>
<input type="text" id="" value="" readonly="readonly" />
</td>
<td>
<input type="text" value="" readonly="readonly" />
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>
//call on click of Save button;
$('#saveDtls').click(function(event) {
var TableData = []; //initialize array;
var data=""; //empty var;
//Here traverse and read input/select values present in each td of each tr, ;
$("table#tableID > tbody > tr").each(function(row, tr) {
TableData[row]={
"fromGroup": $('td:eq(0) select',this).val(),
"toGroup": $('td:eq(1) input',this).val(),
"level": $('td:eq(2) input',this).val()
};
//Convert tableData array to JsonData
data=JSON.stringify(TableData)
//alert('data'+data);
});
});
Typically you want to cancel the previous ajax request and ignore it's coming response, only when a new ajax request of that instance is started, for this purpose, do the following:
Example: getting some comments from API:
// declare an ajax request's cancelToken (globally)
let ajaxRequest = null;
function getComments() {
// cancel previous ajax if exists
if (ajaxRequest ) {
ajaxRequest.cancel();
}
// creates a new token for upcomming ajax (overwrite the previous one)
ajaxRequest = axios.CancelToken.source();
return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
console.log(response.data)
}).catch(function(err) {
if (axios.isCancel(err)) {
console.log('Previous request canceled, new request is send', err.message);
} else {
// handle error
}
});
}
It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.
Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.
function showHideColumns() {
$('#jqGrid').jqGrid('columnChooser', {
width: 250,
dialog_opts: {
modal: true,
minWidth: 250,
height: 300,
show: 'blind',
hide: 'explode',
dividerLocation: 0.5
} });
You need to go through SimpleDateFormat.format
in order to format the date as a string.
Here's an example that goes from String
-> Date
-> String
.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
This is what worked for me on Windows. The cause being multiple python installations
python -m pip uninstall pip setuptools
Use wc
:
wc -l <filename>
This will output the number of lines in <filename>
:
$ wc -l /dir/file.txt
3272485 /dir/file.txt
Or, to omit the <filename>
from the result use wc -l < <filename>
:
$ wc -l < /dir/file.txt
3272485
You can also pipe data to wc
as well:
$ cat /dir/file.txt | wc -l
3272485
$ curl yahoo.com --silent | wc -l
63
First of all, check out my post on retained Fragments. It might help.
Now to answer your questions:
Does the fragment also retain its
viewstate, or will this be recreated on configuration change - what exactly is "retained"?
Yes, the Fragment
's state will be retained across the configuration change. Specifically, "retained" means that the fragment will not be destroyed on configuration changes. That is, the Fragment
will be retained even if the configuration change causes the underlying Activity
to be destroyed.
Will the fragment be destroyed when the user leaves the activity?
Just like Activity
s, Fragment
s may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy the Fragment
s once you leave the Activity
. If you leave the Activity
(i.e. by pressing the home button), the Fragment
s may or may not be destroyed. If you leave the Activity
by pressing the back button (thus, calling finish()
and effectively destroying the Activity
), all of the Activity
s attached Fragment
s will also be destroyed.
Why doesn't it work with fragments on the back stack?
There are probably multiple reasons why it's not supported, but the most obvious reason to me is that the Activity
holds a reference to the FragmentManager
, and the FragmentManager
manages the backstack. That is, no matter if you choose to retain your Fragment
s or not, the Activity
(and thus the FragmentManager
's backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.
Which are the use cases where it makes sense to use this method?
Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of Thread
or AsyncTask
, managing its operation. See my blog post on this topic for more information.
In general, I would treat it similarly to using onConfigurationChanged
with an Activity
... don't use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.
I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.
For deep cloning you'll need a different solution.
const clone = {...original}
to shallow clone
const newobj = {...original, prop: newOne}
to immutably add another prop to the original and store as a new object.
package main
import "fmt"
func main() {
var x float64 = 5.7
var y int = int(x)
fmt.Println(y) // outputs "5"
}
If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.
Preparations to get the table object. There are also different ways.
import sqlalchemy
database_engine = sqlalchemy.create_engine("connection string")
# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)
table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object
Issuing the count query on the table_object
query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'
count_result = database_engine.scalar(query)
Or you can write your own extension method:
static partial class Extensions
{
public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
{
if (!items.Any())
{
throw new InvalidOperationException("Empty input sequence");
}
var comparer = Comparer<U>.Default;
T maxItem = items.First();
U maxValue = selector(maxItem);
foreach (T item in items.Skip(1))
{
// Get the value of the item and compare it to the current max.
U value = selector(item);
if (comparer.Compare(value, maxValue) > 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
}
As a side note, I was playing around with Volume GUIDs in Windows XP. This is a very obscure partition layout with three disks and fourteen volumes.
\\?\Volume{23005604-eb1b-11de-85ba-806d6172696f}\ (F:)
\\?\Volume{23005605-eb1b-11de-85ba-806d6172696f}\ (G:)
\\?\Volume{23005606-eb1b-11de-85ba-806d6172696f}\ (H:)
\\?\Volume{23005607-eb1b-11de-85ba-806d6172696f}\ (J:)
\\?\Volume{23005608-eb1b-11de-85ba-806d6172696f}\ (D:)
\\?\Volume{23005609-eb1b-11de-85ba-806d6172696f}\ (P:)
\\?\Volume{2300560b-eb1b-11de-85ba-806d6172696f}\ (K:)
\\?\Volume{2300560c-eb1b-11de-85ba-806d6172696f}\ (L:)
\\?\Volume{2300560d-eb1b-11de-85ba-806d6172696f}\ (M:)
\\?\Volume{2300560e-eb1b-11de-85ba-806d6172696f}\ (N:)
\\?\Volume{2300560f-eb1b-11de-85ba-806d6172696f}\ (O:)
\\?\Volume{23005610-eb1b-11de-85ba-806d6172696f}\ (E:)
\\?\Volume{23005611-eb1b-11de-85ba-806d6172696f}\ (R:)
| | | | |
| | | | +-- 6f = o
| | | +---- 69 = i
| | +------ 72 = r
| +-------- 61 = a
+---------- 6d = m
It's not that the GUIDs are very similar but the fact that all GUIDs have the string "mario" in them. Is that a coincidence or is there an explanation behind this?
Now, when googling for part 4 in the GUID I found approx 125.000 hits with volume GUIDs.
Conclusion: When it comes to Volume GUIDs they aren't as unique as other GUIDs.
Do you have a table that has all dates? If not, you might want to consider implementing a calendar table and left joining your data onto the calendar table.
As to the short script, the following runs on my Linux host
#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"
while read MYFILE ; do
adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")
"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.
You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.
With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.
If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.
If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy
. For example:
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.
Also, the -t
option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5
. If you are using a current version of ffmpeg you can also replace -t
with -to
in the above command to end at the specified time.
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
If you run "dir c:\
", the last line will give you the free disk space.
Edit:
Better solution: "fsutil volume diskfree c:
"
There are two ways to fix the problem which is caused by the last print
statement.
You can assign the result of the str(c)
call to c
as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print
simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
You just need to name the anonymous property the same on both sides
on new { t1.ProjectID, SecondProperty = true } equals
new { t2.ProjectID, SecondProperty = t2.Completed } into j1
Based on the comments of @svick, here is another implementation that might make more sense:
from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
.DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }
You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated()
to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.
Arulx Z's answer was exactly what I was looking for.
I'm writing an app with Navigation Drawer with recyclerview and webviews, for keeping the web browsing inside the app regardless of hyperlinks clicked (thus not launching the external web browser). For that it will suffice to put the following 2 lines of code:
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());?
exactly under your WebView statement.
Here's a example of my implemented WebView code:
public class WebView1 extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.wv1); //webview statement
wv.setWebViewClient(new WebViewClient()); //the lines of code added
wv.setWebChromeClient(new WebChromeClient()); //same as above
wv.loadUrl("http://www.google.com");
}}
this way, every link clicked in the website will load inside your WebView. (Using Android Studio 1.2.2 with all SDK's updated)
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
You can change the class you are testing to use a Func<DateTime>
which will be passed through it's constructor parameters, so when you create instance of the class in real code, you can pass () => DateTime.UtcNow
to the Func<DateTime>
parameter, and on the test, you can pass the time you wish to test.
For example:
[TestMethod]
public void MyTestMethod()
{
var instance = new MyClass(() => DateTime.MinValue);
Assert.AreEqual(instance.MyMethod(), DateTime.MinValue);
}
public void RealWorldInitialization()
{
new MyClass(() => DateTime.UtcNow);
}
class MyClass
{
private readonly Func<DateTime> _utcTimeNow;
public MyClass(Func<DateTime> UtcTimeNow)
{
_utcTimeNow = UtcTimeNow;
}
public DateTime MyMethod()
{
return _utcTimeNow();
}
}
for word in d:
if d in paid[j]:
do_something()
will try all the words in the list d
and check if they can be found in the string paid[j]
.
This is not very efficient since paid[j]
has to be scanned again for each word in d
. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.
sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]
s1 = set(sentence.split())
s2 = set(d)
print (s1.intersection(s2))
Output:
{'come', 'easy'}
var checked = []
$("input[name='options[]']:checked").each(function ()
{
checked.push(parseInt($(this).val()));
});
For example, if you want to select every 10th row in MSSQL, you can use;
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ColumnName1 ASC) AS rownumber, ColumnName1, ColumnName2
FROM TableName
) AS foo
WHERE rownumber % 10 = 0
Just take the MOD and change number 10 here any number you want.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
According to the documentation.
If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.
You can check what all devices are used by tensorflow by -
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Also as suggested in this answer
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.
If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.
pip install tensorflow-gpu
HTML and body height 100% doesn't work in older IE versions.
You have to move the backgroundproperties from the body element to the html element.
That will fix it crossbrowser.
Here is a solution written in golang. The method is similar to some other answers posted here, but not quite the same. It is easy to implement, and has been tested. Here are the steps:
The values for A, B, and C for the quadratic are derived here, where (n-et) and (m-dt) are the equations for the line's x and y coordinates, respectively. r is the radius of the circle.
(n-et)(n-et) + (m-dt)(m-dt) = rr
nn - 2etn + etet + mm - 2mdt + dtdt = rr
(ee+dd)tt - 2(en + dm)t + nn + mm - rr = 0
Therefore A = ee+dd, B = - 2(en + dm), and C = nn + mm - rr.
Here is the golang code for the function:
package geom
import (
"math"
)
// SegmentCircleIntersection return points of intersection between a circle and
// a line segment. The Boolean intersects returns true if one or
// more solutions exist. If only one solution exists,
// x1 == x2 and y1 == y2.
// s1x and s1y are coordinates for one end point of the segment, and
// s2x and s2y are coordinates for the other end of the segment.
// cx and cy are the coordinates of the center of the circle and
// r is the radius of the circle.
func SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r float64) (x1, y1, x2, y2 float64, intersects bool) {
// (n-et) and (m-dt) are expressions for the x and y coordinates
// of a parameterized line in coordinates whose origin is the
// center of the circle.
// When t = 0, (n-et) == s1x - cx and (m-dt) == s1y - cy
// When t = 1, (n-et) == s2x - cx and (m-dt) == s2y - cy.
n := s2x - cx
m := s2y - cy
e := s2x - s1x
d := s2y - s1y
// lineFunc checks if the t parameter is in the segment and if so
// calculates the line point in the unshifted coordinates (adds back
// cx and cy.
lineFunc := func(t float64) (x, y float64, inBounds bool) {
inBounds = t >= 0 && t <= 1 // Check bounds on closed segment
// To check bounds for an open segment use t > 0 && t < 1
if inBounds { // Calc coords for point in segment
x = n - e*t + cx
y = m - d*t + cy
}
return
}
// Since we want the points on the line distance r from the origin,
// (n-et)(n-et) + (m-dt)(m-dt) = rr.
// Expanding and collecting terms yeilds the following quadratic equation:
A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r
D := B*B - 4*A*C // discriminant of quadratic
if D < 0 {
return // No solution
}
D = math.Sqrt(D)
var p1In, p2In bool
x1, y1, p1In = lineFunc((-B + D) / (2 * A)) // First root
if D == 0.0 {
intersects = p1In
x2, y2 = x1, y1
return // Only possible solution, quadratic has one root.
}
x2, y2, p2In = lineFunc((-B - D) / (2 * A)) // Second root
intersects = p1In || p2In
if p1In == false { // Only x2, y2 may be valid solutions
x1, y1 = x2, y2
} else if p2In == false { // Only x1, y1 are valid solutions
x2, y2 = x1, y1
}
return
}
I tested it with this function, which confirms that solution points are within the line segment and on the circle. It makes a test segment and sweeps it around the given circle:
package geom_test
import (
"testing"
. "**put your package path here**"
)
func CheckEpsilon(t *testing.T, v, epsilon float64, message string) {
if v > epsilon || v < -epsilon {
t.Error(message, v, epsilon)
t.FailNow()
}
}
func TestSegmentCircleIntersection(t *testing.T) {
epsilon := 1e-10 // Something smallish
x1, y1 := 5.0, 2.0 // segment end point 1
x2, y2 := 50.0, 30.0 // segment end point 2
cx, cy := 100.0, 90.0 // center of circle
r := 80.0
segx, segy := x2-x1, y2-y1
testCntr, solutionCntr := 0, 0
for i := -100; i < 100; i++ {
for j := -100; j < 100; j++ {
testCntr++
s1x, s2x := x1+float64(i), x2+float64(i)
s1y, s2y := y1+float64(j), y2+float64(j)
sc1x, sc1y := s1x-cx, s1y-cy
seg1Inside := sc1x*sc1x+sc1y*sc1y < r*r
sc2x, sc2y := s2x-cx, s2y-cy
seg2Inside := sc2x*sc2x+sc2y*sc2y < r*r
p1x, p1y, p2x, p2y, intersects := SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r)
if intersects {
solutionCntr++
//Check if points are on circle
c1x, c1y := p1x-cx, p1y-cy
deltaLen1 := (c1x*c1x + c1y*c1y) - r*r
CheckEpsilon(t, deltaLen1, epsilon, "p1 not on circle")
c2x, c2y := p2x-cx, p2y-cy
deltaLen2 := (c2x*c2x + c2y*c2y) - r*r
CheckEpsilon(t, deltaLen2, epsilon, "p2 not on circle")
// Check if points are on the line through the line segment
// "cross product" of vector from a segment point to the point
// and the vector for the segment should be near zero
vp1x, vp1y := p1x-s1x, p1y-s1y
crossProd1 := vp1x*segy - vp1y*segx
CheckEpsilon(t, crossProd1, epsilon, "p1 not on line ")
vp2x, vp2y := p2x-s1x, p2y-s1y
crossProd2 := vp2x*segy - vp2y*segx
CheckEpsilon(t, crossProd2, epsilon, "p2 not on line ")
// Check if point is between points s1 and s2 on line
// This means the sign of the dot prod of the segment vector
// and point to segment end point vectors are opposite for
// either end.
wp1x, wp1y := p1x-s2x, p1y-s2y
dp1v := vp1x*segx + vp1y*segy
dp1w := wp1x*segx + wp1y*segy
if (dp1v < 0 && dp1w < 0) || (dp1v > 0 && dp1w > 0) {
t.Error("point not contained in segment ", dp1v, dp1w)
t.FailNow()
}
wp2x, wp2y := p2x-s2x, p2y-s2y
dp2v := vp2x*segx + vp2y*segy
dp2w := wp2x*segx + wp2y*segy
if (dp2v < 0 && dp2w < 0) || (dp2v > 0 && dp2w > 0) {
t.Error("point not contained in segment ", dp2v, dp2w)
t.FailNow()
}
if s1x == s2x && s2y == s1y { //Only one solution
// Test that one end of the segment is withing the radius of the circle
// and one is not
if seg1Inside && seg2Inside {
t.Error("Only one solution but both line segment ends inside")
t.FailNow()
}
if !seg1Inside && !seg2Inside {
t.Error("Only one solution but both line segment ends outside")
t.FailNow()
}
}
} else { // No intersection, check if both points outside or inside
if (seg1Inside && !seg2Inside) || (!seg1Inside && seg2Inside) {
t.Error("No solution but only one point in radius of circle")
t.FailNow()
}
}
}
}
t.Log("Tested ", testCntr, " examples and found ", solutionCntr, " solutions.")
}
Here is the output of the test:
=== RUN TestSegmentCircleIntersection
--- PASS: TestSegmentCircleIntersection (0.00s)
geom_test.go:105: Tested 40000 examples and found 7343 solutions.
Finally, the method is easily extendable to the case of a ray starting at one point, going through the other and extending to infinity, by only testing if t > 0 or t < 1 but not both.
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
Here you go:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String oeStartDateStr = "04/01/";
String oeEndDateStr = "11/14/";
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
oeStartDateStr = oeStartDateStr.concat(year.toString());
oeEndDateStr = oeEndDateStr.concat(year.toString());
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
System.out.println("Date is between 1st april to 14th nov...");
}
else{
System.out.println("Date is not between 1st april to 14th nov...");
}
}
easiest way, I think download Eric, unzip go to sources, open python directory, drag the install script into the python icon, not folder, follow prompts
For both Python 2 and 3:
import six
six.next(six.itervalues(d))
Never do a git -f
to do push
as it can result in later disastrous consequences.
You just need to do a git pull
of your local branch.
Ex:
git pull origin 'your_local_branch'
and then do a git push
A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:
<style>
p {
animation-name: example;
animation-duration: 2s;
}
@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>
I hope this is what you needed!
Just thought I added my own solution here since I haven't seen it anywhere. It's a small and portable C++ templated function and portable that only uses bit operations.
template<typename T> inline static T swapByteOrder(const T& val) {
int totalBytes = sizeof(val);
T swapped = (T) 0;
for (int i = 0; i < totalBytes; ++i) {
swapped |= (val >> (8*(totalBytes-i-1)) & 0xFF) << (8*i);
}
return swapped;
}
In addition to @Boaz's and @vegemite4me's answers....
By implementing ImplicitNamingStrategy
you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder
during Hibernate's initialization:
metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());
It works for @UniqueConstraint
, but not for @Column(unique = true)
, which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).
There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586
Thanks.
Youtube now has a player api, You should try that.
For Java code, Create a POJO class for your object instead of a JSONObject. and use JSONEncapsulator for your POJO class. that way order of elements depends on the order of getter setters in your POJO class. for eg. POJO class will be like
Class myObj{
String userID;
String amount;
String success;
// getter setters in any order that you want
and where you need to send your json object in response
JSONContentEncapsulator<myObj> JSONObject = new JSONEncapsulator<myObj>("myObject");
JSONObject.setObject(myObj);
return Response.status(Status.OK).entity(JSONObject).build();
The response of this line will be
{myObject : {//attributes order same as getter setter order.}}
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
For the allowed characters you can use
^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$
to validate a complete string that should consist of only allowed characters. Note that -
is at the end (because otherwise it'd be a range) and a few characters are escaped.
For the invalid characters you can use
[<>'"/;`%]
to check for them.
To combine both into a single regex you can use
^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])
but you'd need a regex engine that allows lookahead.
In Eclipse Neon.3, as well as in the new Eclipse Photon (4.8.0), I can resize the font easily with Ctrl + Shift + + and -, without any plugin or special key binding.
At least in Editor Windows (this does not work in other Views like Console, Project Explorer etc).
Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
When static variable is declared in a header file is its scope limited to .h file or across all units.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.
As such, a static variable declared in a header file is like a static variable in each individual source file.
Since declaring a variable static
this way means internal linkage, every translation unit #include
ing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.
I would like to know what is the difference between static variables in a header file vs declared in a class.
In a class declaration, static
means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static
(or "class") variable, it's the same value for all objects. You could think of it as a "class global".
Also generally static variable is initialized in .cpp file when declared in a class right ?
Yes, one (and only one) translation unit must initialize the class variable.
So that does mean static variable scope is limited to 2 compilation units ?
As I said:
static
means completely different things depending on context.Global static
limits scope to the translation unit. Class static
means global to all instances.
I hope this helps.
PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static
in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )
If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.
Try increasing the padding of the main div style:
#mainWrapperDivWithBGImage
{
background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;
height: 248px;
margin: 0;
overflow: hidden;
padding: 10px 10px;
width: 996px;
}
P.S: I assume the rounded corners have a radius of 10px.
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
Let me summarize a few different (non-programmatic) methods.
Save the following as an XML file in your drawable folder (for example, my_border.xml):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- View background color -->
<solid
android:color="@color/background_color" >
</solid>
<!-- View border color and width -->
<stroke
android:width="1dp"
android:color="@color/border_color" >
</stroke>
<!-- The radius makes the corners rounded -->
<corners
android:radius="2dp" >
</corners>
</shape>
Then just set it as the background to your TextView:
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_border" />
More help:
A 9-patch is a stretchable background image. If you make an image with a border then it will give your TextView a border. All you need to do is make the image and then set it to the background in your TextView.
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_ninepatch_image" />
Here are some links that will show how to make a 9-patch image:
Using a layer-list
You can use a layer list to stack two rectangles on top of each other. By making the second rectangle just a little smaller than the first rectangle, you can make a border effect. The first (lower) rectangle is the border color and the second rectangle is the background color.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Lower rectangle (border color) -->
<item>
<shape android:shape="rectangle">
<solid android:color="@color/border_color" />
</shape>
</item>
<!-- Upper rectangle (background color) -->
<item android:top="2dp">
<shape android:shape="rectangle">
<solid android:color="@color/background_color" />
</shape>
</item>
</layer-list>
Setting android:top="2dp"
offsets the top (makes it smaller) by 2dp. This allows the first (lower) rectangle to show through, giving a border effect. You can apply this to the TextView background the same way that the shape
drawable was done above.
Here are some more links about layer lists:
Using a 9-patch
You can just make a 9-patch image with a single border. Everything else is the same as discussed above.
Using a View
This is kind of a trick but it works well if you need to add a seperator between two views or a border to a single TextView.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- This adds a border between the TextViews -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@android:color/black" />
<TextView
android:id="@+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here are some more links:
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
A good way to do it without getting the view involved may be:
$.ajax({
type: "POST",
url: '/Controller/Search',
data: { queryString: searchVal },
success: function (data) {
alert("here" + data.d.toString());
}
});
This will try to POST to the URL:
"http://domain/Controller/Search (which is the correct URL for the action you want to use)"
Add the type for the script
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
So the important part is the type text/javascript.
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
sort()
was deprecated for DataFrames in favor of either:
sort_values()
to sort by column(s)sort_index()
to sort by the index sort()
was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values()
and sort_index()
. It was removed from Pandas with release 0.20 (2017-05-05).
I have found answers to my confusions.
There is a very important difference between the root
and the alias
directives. This difference exists in the way the path specified in the root
or the alias
is processed.
In case of the root
directive, full path is appended to the root including the location part, whereas in case of the alias
directive, only the portion of the path NOT including the location part is appended to the alias.
To illustrate:
Let's say we have the config
location /static/ {
root /var/www/app/static/;
autoindex off;
}
In this case the final path that Nginx will derive will be
/var/www/app/static/static
This is going to return 404
since there is no static/
within static/
This is because the location part is appended to the path specified in the root
. Hence, with root
, the correct way is
location /static/ {
root /var/www/app/;
autoindex off;
}
On the other hand, with alias
, the location part gets dropped. So for the config
location /static/ {
alias /var/www/app/static/;
autoindex off; ?
} |
pay attention to this trailing slash
the final path will correctly be formed as
/var/www/app/static
alias
directiveThere is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.
A few more places have discussed this, not conclusively though.
https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working
For py3
, base64 encode
and decode
string:
import base64
def b64e(s):
return base64.b64encode(s.encode()).decode()
def b64d(s):
return base64.b64decode(s).decode()
The scripts mentioned in previous answers, like:
$("body, html").animate({
scrollTop: $(document).height()
}, 400)
or
$(window).scrollTop($(document).height());
will not work in Chrome and will be jumpy in Safari in case html
tag in CSS has overflow: auto;
property set. It took me nearly an hour to figure out.
–npm install --save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.
npm install --save
String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(1, VALUE);
preparedStatement.setXXX(2, VALUE);
....
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
int key = rs.next() ? rs.getInt(1) : 0;
if(key!=0){
System.out.println("Generated key="+key);
}
You can do that with StringUtils
(from Apache Commons Lang). It avoids index-magic, so it's easier to understand. Unfortunately substringAfterLast
returns empty string when there is no separator in the input string so we need the if
statement for that case.
public static String getLastWord(String input) {
String wordSeparator = " ";
boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator);
if (inputIsOnlyOneWord) {
return input;
}
return StringUtils.substringAfterLast(input, wordSeparator);
}
To Send bold,italic,fixed width code you can use this :
# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname,
text="*boldtext* _italictext_ `fixed width font` [link] (http://google.com).",
parse_mode=telegram.ParseMode.MARKDOWN)
make sure you have enabled the bot as your admin .Then only it can send message
I had the same situation but any of above tips didn't help :) In our environment we had tomcat running as a service on Windows. We installed Java 1.7 and set up JAVA_HOME on this version. Off course the sources were built on Java 1.7. Nevertheless the tomcat said that it use previous version of JVM. After a deep analized turn out that the Tomcat service installed on Windows still keeping the old value for JAVA_HOME pointing to Java 1.6. After installing new Tomcat service everything were resolved. So the conclusion is: When you change java version and tomcat running as a service, you have to reinstall tomcat service.
If anyone is using angular and material design with sidenav. This will send you to to the top of the page:
let ele = document.getElementsByClassName('md-sidenav-content');
let eleArray = <Element[]>Array.prototype.slice.call(ele);
eleArray.map( val => {
val.scrollTop = document.documentElement.scrollTop = 0;
});
You can do this in jquery by setting the attribute disabled to 'disabled'.
$(this).prop('disabled', true);
I have made a simple example http://jsfiddle.net/4gnXL/2/
use global scope on your $con and put it inside your getPosts() function like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
If you are using select as inline to other component, then you can also use like given below.
<select onChange={(val) => this.handlePeriodChange(val.target.value)} className="btn btn-sm btn-outline-secondary dropdown-toggle">
<option value="TODAY">Today</option>
<option value="THIS_WEEK" >This Week</option>
<option value="THIS_MONTH">This Month</option>
<option value="THIS_YEAR">This Year</option>
<option selected value="LAST_AVAILABLE_DAY">Last Availabe NAV Day</option>
</select>
And on the component where select is used, define the function to handle onChange like below:
handlePeriodChange(selVal) {
this.props.handlePeriodChange(selVal);
}
Try this:
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;
First of all: The UIBezierPath
used as shadowPath
is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.
Regarding your issue specifically: The important line is view.layer.masksToBounds = NO
. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.
For those wondering what the difference between masksToBounds
(on the layer) and the view's own clipToBounds
property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.
Swift 2.2:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSizeMake(0.0, 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.CGPath
}
Swift 3:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.cgPath
}
I had a similar error with a different artifact.
<...> was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
None of the above described solutions worked for me. I finally resolved this in IntelliJ IDEA by File > Invalidate Caches / Restart ... > Invalidate and Restart.
You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".
Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X
to open up a context menu, then press J
.
Another solution is to implement your own custom popup/form/user control that will be universally interpreted across all browsers.
Granted this will not leverage the "mailto" out of the box capabilities. It all depends on what availability adherence you are working against. Unfortunately for myself - the mailto needed to be available to everyone by default without "inconveniencing the client".
Your decision ultimately.
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
Simply casting the string as an int
won't work reliably. You need to convert it to an int32
. For this you can use the .NET convert
class and its ToInt32
method. The method requires a string
($strNum
) as the main input, and the base number
(10
) for the number system to convert to. This is because you can not only convert to the decimal system (the 10
base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
What about using App-V? http://www.microsoft.com/systemcenter/appv/default.mspx
In particular Dynamic Application Virtualization http://www.microsoft.com/systemcenter/appv/dynamic.mspx
It virtualizes at the application level. It is useful when running incompatible software on the same OS instance.
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
You could also write
-Wl,-rpath=.
To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).
If you're using Radiant CMS, simply add
require 'thread'
to the top of config/boot.rb
.
(Kudos to Aaron's and nathanvda's responses.)
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset
won't touch them.
If you want to blow away all untracked files, the simplest way is git clean -f
(use git clean -n
instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.
Firstly, in your react project go to your package.json and adjust this line line of code to match your destination domain address + folder:
"homepage": "https://yourwebsite.com/your_folder_name/",
Secondly, go to terminal in your react project and type:
npm run build
Now, take all files from that newly created build folder and upload them into your_folder_name, with filezilla in subfolder like this:
public_html/your_folder_name
Check in the browser!
Using fairly simple code:
int i;
int value;
int n;
char ch;
/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
n = sscanf(argv[i], "%d%c", &value, &ch);
if (n != 1) {
/* sscanf didn't find a number to convert, so it wasn't a number */
}
else {
/* It was */
}
}
I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.
By using what @Aldi Unanto suggested here is a more complete answer:
jQuery('.show_hide').click(function(e) {
e.preventDefault();
if (jQuery('.slidingDiv').is(":visible") ) {
jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
} else {
jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
}
});
First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.
Edit: I have also added
.stop(true,true)
in order to clearQueue and jumpToEnd. Read about jQuery stop here
ArrayDeque
are faster in the stack than a Stack or LinkedList. "push()" inserts elements at the front of the Deque
protected <T> Stream<T> reverse(Stream<T> stream) {
ArrayDeque<T> stack = new ArrayDeque<>();
stream.forEach(stack::push);
return stack.stream();
}
Android 3.6.2.
Build >> Build/Bundle apk >> Build apk