Since no one has shared a neat two liner, I will share my own:
logging.basicConfig(filename='logs.log', level=logging.DEBUG, format="%(asctime)s:%(levelname)s: %(message)s")
logging.getLogger().addHandler(logging.StreamHandler())
Run this script to refresh data in materialized view:
BEGIN
DBMS_SNAPSHOT.REFRESH('Name here');
END;
it works for me in ios 10 and later :
- (void)viewWillAppear:(BOOL)animated {
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
it doesnt work on viewDidLoad() method.
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
I'm going to add some updated info and references to @max-malysh's excellent answer above.
In short, if you do something on the master, it needs to be replicated on the slave. Postgres uses WAL records for this, which are sent after every logged action on the master to the slave. The slave then executes the action and the two are again in sync. In one of several scenarios, you can be in conflict on the slave with what's coming in from the master in a WAL action. In most of them, there's a transaction happening on the slave which conflicts with what the WAL action wants to change. In that case, you have two options:
We're concerned with #1, and two values:
max_standby_archive_delay
- this is the delay used after a long disconnection between the master and slave, when the data is being read from a WAL archive, which is not current data.max_standby_streaming_delay
- delay used for cancelling queries when WAL entries are received via streaming replication.Generally, if your server is meant for high availability replication, you want to keep these numbers short. The default setting of 30000
(milliseconds if no units given) is sufficient for this. If, however, you want to set up something like an archive, reporting- or read-replica that might have very long-running queries, then you'll want to set this to something higher to avoid cancelled queries. The recommended 900s
setting above seems like a good starting point. I disagree with the official docs on setting an infinite value -1
as being a good idea--that could mask some buggy code and cause lots of issues.
The one caveat about long-running queries and setting these values higher is that other queries running on the slave in parallel with the long-running one which is causing the WAL action to be delayed will see old data until the long query has completed. Developers will need to understand this and serialize queries which shouldn't run simultaneously.
For the full explanation of how max_standby_archive_delay
and max_standby_streaming_delay
work and why, go here.
You can add this command line at the begining of your script:
set PGPASSWORD=[your password]
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
This works with Bootstrap 4.1.3:
<script>
$("input[type=file]").change(function () {
var fieldVal = $(this).val();
// Change the node's value by removing the fake path (Chrome)
fieldVal = fieldVal.replace("C:\\fakepath\\", "");
if (fieldVal != undefined || fieldVal != "") {
$(this).next(".custom-file-label").attr('data-content', fieldVal);
$(this).next(".custom-file-label").text(fieldVal);
}
});
</script>
I think you meant something like this: JSON Visualization
Don't know if you might use it, but you might ask the author.
Try the strict equality comparison:
if(1 === true)
document.write("oh!!! that's true"); //**this is not displayed**
The ==
operator does conversion from one type to another, the ===
operator doesn't.
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
It seems working :
HTML :
<input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
JavaScript :
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = parseInt($('#pointspossible').val());
var pEarned = parseInt($('#pointsgiven').val());
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned/pPos) * 100).toFixed(3);
}
$('#pointsperc').val(perc);
}
});
char buffer[41];
memset(buffer, '-', 40); // initialize all with the '-' character<br /><br />
buffer[40] = 0; // put a NULL at the end<br />
printf("%s\n", buffer); // show 40 dashes<br />
To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
To improve a little bit the extension method on xr280xr answer I added an optional bool parameter to determine whether the sorting is descending or not. I also included the suggestion made by Carlos P in the comment to that answer. Please see below.
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector, bool desc = false)
{
if (source == null) return;
Comparer<TKey> comparer = Comparer<TKey>.Default;
for (int i = source.Count - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
TSource o1 = source[j - 1];
TSource o2 = source[j];
int comparison = comparer.Compare(keySelector(o1), keySelector(o2));
if (desc && comparison < 0)
source.Move(j, j - 1);
else if (!desc && comparison > 0)
source.Move(j - 1, j);
}
}
}
@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5.
@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.
You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.
your code $(".a, .b")
will work for below multiple elements (at a same time)
<element class="a">
<element class="b">
if you want to select element having a and b both class like <element class="a b">
than use js without coma
$('.a.b')
Is this what you're after?
I added :text-align:center
to the div and image
You need INDIRECT
function:
=INDIRECT("'"&A5&"'!G7")
If you are running MYSQL through XAMPP:
Open XAMPP mysql configuration file (on OSX):
/Applications/XAMPP/etc/my.cnf
Copy the socket path:
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Open rails project's database configuration file: myproject/config/database.yml
Add the socket config to the development database config:
-->
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: difiuri_falcioni
pool: 5
username: root
password:
host: localhost
socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
Enjoy :)
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round
function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...
The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places)
is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:
>>> round(52.15, 1)
52.1
With a naive understanding of what round
does, this looks wrong: surely it should be rounding up to 52.2
rather than down to 52.1
? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.
So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n
-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):
First the numeric literal 52.15
gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47
, or 52.14999999999999857891452847979962825775146484375
.
Internally as the first step of the round
operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15
, we end up rounding down and getting a string 52.1
. This explains why we're getting 52.1
as the final output instead of 52.2
.
Then in the second step of the round
operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1
, which is now 7332423143312589 * 2**-47
, or 52.10000000000000142108547152020037174224853515625
.
Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1
as the final output.
In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr
implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:
>>> x = 15.34509809234
>>> x
15.34509809234
Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:
>>> round(52.15, 1)
52.200000000000003
Not only do we round in the opposite direction, getting 52.2
instead of 52.1
, but the displayed value doesn't even print as 52.2
! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round
that's broken, it's user expectations. (Okay, okay, round
is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)
Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.
So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.
If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:
>>> format(66.66666666666, '.4f')
'66.6667'
>>> format(1.29578293, '.6f')
'1.295783'
Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.
>>> format(52.15, '.1f')
'52.1'
If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal
type. Doing a decimal round on the Decimal
type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal
module gives you better control of the rounding mode. In Python 3, round
does the job directly. In Python 2, you need the quantize
method.
>>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
Decimal('66.6667')
>>> Decimal('1.29578293').quantize(Decimal('1e-6'))
Decimal('1.295783')
In rare cases, the two-argument version of round
really is what you want: perhaps you're binning floats into bins of size 0.01
, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round
builtin based on those cases alone.
I too have struggled with this new pagespeed metric.
Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.
Combining all css into one file helped a lot. All my sites are back up to %95 - %98.
The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.
Just use setTitle(null)
above
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
The title will disappear then you can use the logo of your choice.....
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
This one is good, but will match an empty String
This one does not match empty string :
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$
how do you write out the parameters os.path.dirname
.... command?
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
Use vector::front
, it should be the most portable solution. I've used this when I'm interfacing with a fixed API that wants a char ptr. Example:
void funcThatTakesCharPtr(char* start, size_t size);
...
void myFunc(vector<char>& myVec)
{
// Get a pointer to the front element of my vector:
char* myDataPtr = &(myVec.front());
// Pass that pointer to my external API:
funcThatTakesCharPtr(myDataPtr, myVec.size());
}
First of all stop the server and image the disc. There's no point only having one shot at this. Then take a look here.
I have same problem when I use this code
webview.setWebViewClient(new WebViewClient() {
}
so may be you should remove it in your code
And remember to add 3 modes below for your webview
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
this fixes size based on screen size
For element with id
<input id="id_input_text16" type="text" placeholder="Ender Data"></input>
You can set the value as
$("#id_input_text16").val("testValue");
Documentation here.
I had to use Stylesheet directory to work for me.
<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">
They are extension methods. Welcome to a whole new fluent world. :)
First type
i
to enter the commit message then press ESC
then type
:wq
to save the commit message and to quit. Or type
:q!
to quit without saving the message.
You will be able to get the current iteration's index
for the map
method through its 2nd parameter.
Example:
const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return currElement; //equivalent to list[index]
});
Output:
The current iteration is: 0 <br>The current element is: h
The current iteration is: 1 <br>The current element is: e
The current iteration is: 2 <br>The current element is: l
The current iteration is: 3 <br>The current element is: l
The current iteration is: 4 <br>The current element is: o
See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Parameters
callback - Function that produces an element of the new Array, taking three arguments:
1) currentValue
The current element being processed in the array.2) index
The index of the current element being processed in the array.3) array
The array map was called upon.
This function returns the mode or modes of a function no matter how many, as well as the frequency of the mode or modes in the dataset. If there is no mode (ie. all items occur only once), the function returns an error string. This is similar to A_nagpal's function above but is, in my humble opinion, more complete, and I think it's easier to understand for any Python novices (such as yours truly) reading this question to understand.
def l_mode(list_in):
count_dict = {}
for e in (list_in):
count = list_in.count(e)
if e not in count_dict.keys():
count_dict[e] = count
max_count = 0
for key in count_dict:
if count_dict[key] >= max_count:
max_count = count_dict[key]
corr_keys = []
for corr_key, count_value in count_dict.items():
if count_dict[corr_key] == max_count:
corr_keys.append(corr_key)
if max_count == 1 and len(count_dict) != 1:
return 'There is no mode for this data set. All values occur only once.'
else:
corr_keys = sorted(corr_keys)
return corr_keys, max_count
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
All Func delegates return something; all the Action delegates return void.
Func<TResult>
takes no arguments and returns TResult:
public delegate TResult Func<TResult>()
Action<T>
takes one argument and does not return a value:
public delegate void Action<T>(T obj)
Action
is the simplest, 'bare' delegate:
public delegate void Action()
There's also Func<TArg1, TResult>
and Action<TArg1, TArg2>
(and others up to 16 arguments). All of these (except for Action<T>
) are new to .NET 3.5 (defined in System.Core).
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
this worked for me
sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
domain.com -d www.domain.com
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
The comma got eaten by the quotes!
This part:
("username," visitorName);
Should be this:
("username", visitorName);
Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
Easiest solution:
class OuterClass:
outer_var = 1
class InnerClass:
def __init__(self):
self.inner_var = OuterClass.outer_var
It requires you to be explicit, but doesn't take much effort.
To make it work in JSON, you need to escape a few more character than that.
myString.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\r", "\\r")
.replace("\n", "\\n")
and if you want to be able to use json2.js
to parse it then you also need to escape
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
which JSON allows inside quoted strings, but which JavaScript does not.
Fiddle 1: a replica of the modal used on the twitter bootstrap site. (This is the modal that doesn't display by default, but that launches when you click on the demo button.)
Fiddle 2: a replica of the modal described in the bootstrap documentation,
but that incorporates the necessary elements to avoid the use of any javascript.
Note especially the inclusion of the hide
class on #myModal
div, and the use of data-dismiss="modal"
on the Close button.
<a class="btn" data-toggle="modal" href="#myModal">Launch Modal</a>
<div class="modal hide" id="myModal"><!-- note the use of "hide" class -->
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a><!-- note the use of "data-dismiss" -->
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>?
It's also worth noting that the site you are using is running on bootstrap 2.0, while the official twitter bootstrap site is on 2.0.3.
Mu. No correct way exists, not even one that's consistent across browsers.
This is a problem that comes from the HTTP specification (section 15.6):
Existing HTTP clients and user agents typically retain authentication information indefinitely. HTTP/1.1. does not provide a method for a server to direct clients to discard these cached credentials.
On the other hand, section 10.4.2 says:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.
In other words, you may be able to show the login box again (as @Karsten says), but the browser doesn't have to honor your request - so don't depend on this (mis)feature too much.
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
Since it is difficult to do 3rd party cookies and also some browsers won't allow that.
You can try storing them in HTML5 local storage and then sending them with every request from your front end app.
If you still use OID, it would be better to remove the dependency on it, because in recent versions of Postgres it is no longer supported. This can stop (temporarily until you solve it) your migration from version 10 to 12 for example.
See also: https://dev.to/rafaelbernard/postgresql-pgupgrade-from-10-to-12-566i
I also had this issue - However it was for a completely different reason then any I have seen online. I realized that my app did not have the proper iOS Provisioning profile associated for app store release. I simply changed the build number, validated and resubmitted. Within 15 minutes, the new version was ready to be added as a current build. The previous two versions I tried to upload are both still processing.
I am not sure why Apple does not tell you that there is an incorrect provisioning profile for the build to be uploaded, but this was my cure!
To split the string ({filepath}/{filename}) and get the file name you could use something like this:
str.split(/(\\|\/)/g).pop()
"The pop method removes the last element from an array and returns that value to the caller."
Mozilla Developer Network
Example:
from: "/home/user/file.txt".split(/(\\|\/)/g).pop()
you get: "file.txt"
You can use XMLHttpRequest, fetch API, ...
If you want to use XMLHttpRequest you can do the following
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
Or if you want to use fetch API
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
})
.then(result => {
// do something with the result
console.log("Completed with result:", result);
});
For my .bashrc, I use the following code:
platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
platform='freebsd'
fi
Then I do somethings like:
if [[ $platform == 'linux' ]]; then
alias ls='ls --color=auto'
elif [[ $platform == 'freebsd' ]]; then
alias ls='ls -G'
fi
It's ugly, but it works. You may use case
instead of if
if you prefer.
I've written this little plugin for jQuery which will make all calls to .val(value)
update the angular element if present:
(function($, ng) {
'use strict';
var $val = $.fn.val; // save original jQuery function
// override jQuery function
$.fn.val = function (value) {
// if getter, just return original
if (!arguments.length) {
return $val.call(this);
}
// get result of original function
var result = $val.call(this, value);
// trigger angular input (this[0] is the DOM object)
ng.element(this[0]).triggerHandler('input');
// return the original result
return result;
}
})(window.jQuery, window.angular);
Just pop this script in after jQuery and angular.js and val(value)
updates should now play nice.
Minified version:
!function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);
Example:
// the function_x000D_
(function($, ng) {_x000D_
'use strict';_x000D_
_x000D_
var $val = $.fn.val;_x000D_
_x000D_
$.fn.val = function (value) {_x000D_
if (!arguments.length) {_x000D_
return $val.call(this);_x000D_
}_x000D_
_x000D_
var result = $val.call(this, value);_x000D_
_x000D_
ng.element(this[0]).triggerHandler('input');_x000D_
_x000D_
return result;_x000D_
_x000D_
}_x000D_
})(window.jQuery, window.angular);_x000D_
_x000D_
(function(ng){ _x000D_
ng.module('example', [])_x000D_
.controller('ExampleController', function($scope) {_x000D_
$scope.output = "output";_x000D_
_x000D_
$scope.change = function() {_x000D_
$scope.output = "" + $scope.input;_x000D_
}_x000D_
});_x000D_
})(window.angular);_x000D_
_x000D_
(function($){ _x000D_
$(function() {_x000D_
var button = $('#button');_x000D_
_x000D_
if (button.length)_x000D_
console.log('hello, button');_x000D_
_x000D_
button.click(function() {_x000D_
var input = $('#input');_x000D_
_x000D_
var value = parseInt(input.val());_x000D_
value = isNaN(value) ? 0 : value;_x000D_
_x000D_
input.val(value + 1);_x000D_
});_x000D_
});_x000D_
})(window.jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div ng-app="example" ng-controller="ExampleController">_x000D_
<input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
<span>{{output}}</span>_x000D_
<button id="button">+</button>_x000D_
</div>
_x000D_
This answer was copied verbatim from my answer to another similar question.
The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
Then render it at the top of your app, but below Router:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>
^ copied directly from the documentation
Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.
I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect
call. For example,
con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
connect_timeout=1000)
Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.
For detail about different arguments that you can pass to _mysql.connect
, see MySQLdb API documentation
If you have the OAuth PHP library installed, you don't have to worry about forming the request yourself.
$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);
$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());
print_r($twitter_data);
For more information, check out The docs or their example. You can use pecl install oauth
to get the library.
Write a util function like
public class ListUtil{
public static int sum(List<Integer> list){
if(list==null || list.size()<1)
return 0;
int sum = 0;
for(Integer i: list)
sum = sum+i;
return sum;
}
}
Then use like
int sum = ListUtil.sum(yourArrayList)
One solution is like, If you know the specific lat/lng.
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(new google.maps.LatLng(latitude, longitude));
map.setZoom(8);
});
If don't have specific lat/lng
google.maps.event.addListener(map, 'idle', function() {
map.setCenter(map.getCenter());
map.setZoom(8);
});
or
google.maps.event.addListener(map, 'idle', function() {
var bounds = new google.maps.LatLngBounds();
map.setCenter(bounds.getCenter());
map.setZoom(8);
});
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
The range function in python has the syntax:
range(start, end, step)
It has the same syntax as python lists where the start is inclusive but the end is exclusive.
So if you want to count from 5 to 1, you would use range(5,0,-1)
and if you wanted to count from last
to posn
you would use range(last, posn - 1, -1)
.
This can be done with CSS3:
<input type="text" />
input
{
-moz-border-radius: 15px;
border-radius: 15px;
border:solid 1px black;
padding:5px;
}
However, an alternative would be to put the input
inside a div
with a rounded background, and no border on the input
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
You can achieve this like following :
map<string, int>::iterator it;
for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
std::cout << it->first // string (key)
<< ':'
<< it->second // string's value
<< std::endl;
}
With C++11 ( and onwards ),
for (auto const& x : symbolTable)
{
std::cout << x.first // string (key)
<< ':'
<< x.second // string's value
<< std::endl;
}
With C++17 ( and onwards ),
for (auto const& [key, val] : symbolTable)
{
std::cout << key // string (key)
<< ':'
<< val // string's value
<< std::endl;
}
If you want to handle IPV6 in standard notation there are 8 groups of 4 hex digits:
2001:0dc5:72a3:0000:0000:802e:3370:73E4
32 hex digits + 7 separators = 39 characters.
CAUTION: If you also want to hold IPV4 addresses mapped as IPV6 addresses, use 45 characters as @Deepak suggests.
In this article I read that frameworks like Underscore.js use this function:
function isUndefined(obj){
return obj === void 0;
}
Add two datasets containing datatables, now it will merge as required
DataSet ds1 = new DataSet();
DataSet ds2 = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("Column1", typeof(System.String)));
DataRow newSelRow1 = dt1.NewRow();
newSelRow1["Column1"] = "Select";
dt1.Rows.Add(newSelRow1);
DataTable dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("Column1", typeof(System.String)));
DataRow newSelRow2 = dt1.NewRow();
newSelRow2["Column1"] = "DataRow1Data"; // Data
dt2.Rows.Add(newSelRow2);
ds1.Tables.Add(dt1);
ds2.Tables.Add(dt2);
ds1.Tables[0].Merge(ds2.Tables[0]);
Now ds1 will have the merged data
For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that
private String U_id;
will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue
annotation or by assigning a value manually.
In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id
, e.g.
public Role (String U_id) { ... }
This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.
Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role
using the default constructor, just declare it as private
.
This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.
/*
* Hide only visually, but have it available for screenreaders: h5bp.com/v
*/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element to be focusable
* when navigated to via the keyboard: h5bp.com/p
*/
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
Even when they say that all services and factories are singleton, I don't agree 100 percent with that. I would say that factories are not singletons and this is the point of my answer. I would really think about the name that defines every component(Service/Factory), I mean:
A factory because is not a singleton, you can create as many as you want when you inject, so it works like a factory of objects. You can create a factory of an entity of your domain and work more comfortably with this objects which could be like an object of your model. When you retrieve several objects you can map them in this objects and it can act kind of another layer between the DDBB and the AngularJs model.You can add methods to the objects so you oriented to objects a little bit more your AngularJs App.
Meanwhile a service is a singleton, so we can only create 1 of a kind, maybe not create but we have only 1 instance when we inject in a controller, so a service provides more like a common service(rest calls,functionality.. ) to the controllers.
Conceptually you can think like services provide a service, factories can create multiple instances(objects) of a class
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
How about ..
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());
// C
// o
// d
// i
// n
// g
}
I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.
auto_now=True
didn't work for me in Django 1.4.1, but the below code saved me. It's for timezone aware datetime.
from django.utils.timezone import get_current_timezone
from datetime import datetime
class EntryVote(models.Model):
voted_on = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.voted_on = datetime.now().replace(tzinfo=get_current_timezone())
super(EntryVote, self).save(*args, **kwargs)
Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.
So, if you had a script called my_shell_script:
#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
puts value
end
...make it executable (as others have mentioned):
chmod u+x my_shell_script
And call it like so:
> ./my_shell_script one two three four five
You'd get this:
I was passed:
one
two
three
four
five
The arguments work nicely with filename expansion:
./my_shell_script *
I was passed:
a_file_in_the_current_directory
another_file
my_shell_script
the_last_file
Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.
You can get if from your document_cache folder, subfolder (mine is 1946507). Once there, rename the "content" by adding .pdf to the end of the file, save, and open with any pdf reader.
You have it covered aside from using the wrong property. The scrollbar can be triggered with any property overflow
, overflow-x
, or overflow-y
and each can be set to any of visible
, hidden
, scroll
, auto
, or inherit
. You are currently looking at these two:
auto
- This value will look at the width and height of the box. If they are defined, it won't let the box expand past those boundaries. Instead (if the content exceeds those boundaries), it will create a scrollbar for either boundary (or both) that exceeds its length.
scroll
- This values forces a scrollbar, no matter what, even if the content does not exceed the boundary set. If the content doesn't need to be scrolled, the bar will appear as "disabled" or non-interactive.
If you always want the vertical scrollbar to appear:
You should use overflow-y: scroll
. This forces a scrollbar to appear for the vertical axis whether or not it is needed. If you can't actually scroll the context, it will appear as a"disabled" scrollbar.
If you only want a scrollbar to appear if you can scroll the box:
Just use overflow: auto
. Since your content by default just breaks to the next line when it cannot fit on the current line, a horizontal scrollbar won't be created (unless it's on an element that has word-wrapping disabled). For the vertical bar,it will allow the content to expand up to the height you have specified. If it exceeds that height, it will show a vertical scrollbar to view the rest of the content, but will not show a scrollbar if it does not exceed the height.
The order in which the callbacks are called after commit():
I needed to do some work that involved some Views, so onAttach() didn't work for me; it crashed. So I moved part of my code that was setting some params inside a method called right after commit() (1.), then the other part of the code that handled view inside onCreateView() (3.).
Look at shutil in the Python docs, specifically the copytree command.
If the destination directory already exists, try:
shutil.copytree(source, destination, dirs_exist_ok=True)
You're missing the data-toggle="tab"
data-tag on your menu urls so your scripts can't tell where your tab switches are:
HTML
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
I updated jsch lib latest one (0.1.55). working fine for me. no need to restart the server or no need to update java(current using java8)
You have no valid main method... The signature should be: public static void main(String[] args);
Hence, in your case the code should look like this:
public class Echo {
public static void main (String[] arg) {
System.out.println(arg[0]);
}
}
Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.
Share : Text
@IBAction func shareOnlyText(_ sender: UIButton) {
let text = "This is the text....."
let textShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
}
Share : Image
@IBAction func shareOnlyImage(_ sender: UIButton) {
let image = UIImage(named: "Product")
let imageShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
Share : Text - Image - URL
@IBAction func shareAll(_ sender: UIButton) {
let text = "This is the text...."
let image = UIImage(named: "Product")
let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
let shareAll= [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
I want to do this:
print("Hello"[1...3])
// out: Error
But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.
We can do this however:
print("Hello"[range: 1...3])
// out: ell
Just add this to your project:
extension String {
subscript(range: ClosedRange<Int>) -> String {
get {
let start = String.Index(utf16Offset: range.lowerBound, in: self)
let end = String.Index(utf16Offset: range.upperBound, in: self)
return String(self[start...end])
}
}
}
You can use:
JsonConvert.PopulateObject(json, obj);
here: json
is the json string,obj
is the target object. See: example
Note: PopulateObject()
will not erase obj's list data, after Populate()
, obj's
list member will contains its original data and data from json string
You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.
You want:
var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
do stuff;
}
else {
do other stuff;
}
Use:
bt
- backtrace: show stack functions and argsinfo frame
- show stack start/end/args/locals pointers x/100x $sp
- show stack memory(gdb) bt
#0 zzz () at zzz.c:96
#1 0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2 0xf7d3a4f6 in yyyinit () at yyy.c:590
#3 0x0804ac0c in gnninit () at gnn.c:374
#4 main (argc=1, argv=0xffffd5e4) at gnn.c:389
(gdb) info frame
Stack level 0, frame at 0xffeac770:
eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
source language c.
Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
Locals at 0xffeac768, Previous frame's sp is 0xffeac770
Saved registers:
ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c
(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba 0xf7d3c0d8 0xf7d3c21b 0x00000001
0xffeac64c: 0xf78d133f 0xffeac6f4 0xf7a14450 0xffeac678
0xffeac65c: 0x00000000 0xf7d3790e
See the documentation on MDN about expressions and operators and statements.
this
keyword:var x = function()
vs. function x()
— Function declaration syntax(function(){
…})()
— IIFE (Immediately Invoked Function Expression)(function(){…})();
work but function(){…}();
doesn't?(function(){…})();
vs (function(){…}());
!function(){…}();
- What does the exclamation mark do before the function?+function(){…}();
- JavaScript plus sign in front of function expression!
vs leading semicolon(function(window, undefined){…}(window));
someFunction()()
— Functions which return other functions=>
— Equal sign, greater than: arrow function expression syntax|>
— Pipe, greater than: Pipeline operatorfunction*
, yield
, yield*
— Star after function
or yield
: generator functions[]
, Array()
— Square brackets: array notationIf the square brackets appear on the left side of an assignment ([a] = ...
), or inside a function's parameters, it's a destructuring assignment.
{key: value}
— Curly brackets: object literal syntax (not to be confused with blocks)If the curly brackets appear on the left side of an assignment ({ a } = ...
) or inside a function's parameters, it's a destructuring assignment.
`
…${
…}
…`
— Backticks, dollar sign with curly brackets: template literals`…${…}…`
code from the node docs mean?/
…/
— Slashes: regular expression literals$
— Dollar sign in regex replace patterns: $$
, $&
, $`
, $'
, $n
()
— Parentheses: grouping operatorobj.prop
, obj[prop]
, obj["prop"]
— Square brackets or dot: property accessors?.
, ?.[]
, ?.()
— Question mark, dot: optional chaining operator::
— Double colon: bind operatornew
operator...iter
— Three dots: spread syntax; rest parameters(...args) => {}
— What is the meaning of “…args” (three dots) in a function definition?[...iter]
— javascript es6 array feature […data, 0] “spread operator”{...props}
— Javascript Property with three dots (…)++
, --
— Double plus or minus: pre- / post-increment / -decrement operatorsdelete
operatorvoid
operator+
, -
— Plus and minus: addition or concatenation, and subtraction operators; unary sign operators|
, &
, ^
, ~
— Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators~1
equal -2
?%
— Percent sign: remainder operator&&
, ||
, !
— Double ampersand, double pipe, exclamation point: logical operators??
— Double question mark: nullish-coalescing operator**
— Double star: power operator (exponentiation)x ** 2
is equivalent to Math.pow(x, 2)
==
, ===
— Equal signs: equality operators!=
, !==
— Exclamation point and equal signs: inequality operators<<
, >>
, >>>
— Two or three angle brackets: bit shift operators?
…:
… — Question mark and colon: conditional (ternary) operator=
— Equal sign: assignment operator%=
— Percent equals: remainder assignment+=
— Plus equals: addition assignment operator&&=
, ||=
, ??=
— Double ampersand, pipe, or question mark, followed by equal sign: logical assignments||=
(or equals) in JavaScript?,
— Comma operator{
…}
— Curly brackets: blocks (not to be confused with object literal syntax)var
, let
, const
— Declaring variableslabel:
— Colon: labels#
— Hash (number sign): Private methods or private fieldsuse return
in the if condition will returns you out from the function,
so that you can use return to break the the if condition.
Did you check the MSDN documentation (or IntelliSense)? How about the String.Substring
method?
You can get the length using the Length
property, subtract two from this, and return the substring from the beginning to 2 characters from the end.
For example:
string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
You cannot, and here is the simple answer.
Every media asset poured into the browser is identified by a mime type name. A browser then makes processing determinations upon that mime type name. If it is image/gif or image/jpeg the browser processes the asset as an image. If it is text/css or text/javascript it is processed as a code asset unless the asset is addressed independent of HTML. PDF is identified as application/pdf. When browsers see application/pdf they immediately switch processing to a plugin software capable of processing that media type. If you attempt to push media of type application/pdf into a div the browser will likely throw an error to the user. Typically files of type application/pdf are linked to directly so that the processing software an intercept the request and process the media independent of the browser.
<%= f.submit nil, :class => 'btn btn-primary' %>
Yields something like:
Here is a sample implementation:
import java.util.*;
public class MyBSTree<K,V> implements MyTree<K,V>{
private BSTNode<K,V> _root;
private int _size;
private Comparator<K> _comparator;
private int mod = 0;
public MyBSTree(Comparator<K> comparator){
_comparator = comparator;
}
public Node<K,V> root(){
return _root;
}
public int size(){
return _size;
}
public boolean containsKey(K key){
if(_root == null){
return false;
}
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return true;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
return false;
}
private int compare(K k1, K k2){
if(_comparator != null){
return _comparator.compare(k1,k2);
}
else {
Comparable<K> comparable = (Comparable<K>)k1;
return comparable.compareTo(k2);
}
}
public V get(K key){
Node<K,V> node = node(key);
return node != null ? node.value() : null;
}
private BSTNode<K,V> node(K key){
if(_root != null){
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return node;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
}
return null;
}
public void add(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
if(_root == null){
_root = new BSTNode<K, V>(key, value);
}
BSTNode<K,V> prev = null, curr = _root;
boolean lastChildLeft = false;
while(curr != null){
int comparison = compare(key, curr.key());
prev = curr;
if(comparison == 0){
curr._value = value;
return;
}else if(comparison < 0){
curr = curr._left;
lastChildLeft = true;
}
else{
curr = curr._right;
lastChildLeft = false;
}
}
mod++;
if(lastChildLeft){
prev._left = new BSTNode<K, V>(key, value);
}else {
prev._right = new BSTNode<K, V>(key, value);
}
}
private void removeNode(BSTNode<K,V> curr){
if(curr.left() == null && curr.right() == null){
if(curr == _root){
_root = null;
}else{
if(curr.isLeft()) curr._parent._left = null;
else curr._parent._right = null;
}
}
else if(curr._left == null && curr._right != null){
curr._key = curr._right._key;
curr._value = curr._right._value;
curr._left = curr._right._left;
curr._right = curr._right._right;
}
else if(curr._left != null && curr._right == null){
curr._key = curr._left._key;
curr._value = curr._left._value;
curr._right = curr._left._right;
curr._left = curr._left._left;
}
else { // both left & right exist
BSTNode<K,V> x = curr._left;
// find right-most node of left sub-tree
while (x._right != null){
x = x._right;
}
// move that to current
curr._key = x._key;
curr._value = x._value;
// delete duplicate data
removeNode(x);
}
}
public V remove(K key){
BSTNode<K,V> curr = _root;
V val = null;
while(curr != null){
int comparison = compare(key, curr.key());
if(comparison == 0){
val = curr._value;
removeNode(curr);
mod++;
break;
}else if(comparison < 0){
curr = curr._left;
}
else{
curr = curr._right;
}
}
return val;
}
public Iterator<MyTree.Node<K,V>> iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<Node<K,V>>{
int _startMod;
Stack<BSTNode<K,V>> _stack;
public MyIterator(){
_startMod = MyBSTree.this.mod;
_stack = new Stack<BSTNode<K, V>>();
BSTNode<K,V> node = MyBSTree.this._root;
while (node != null){
_stack.push(node);
node = node._left;
}
}
public void remove(){
throw new UnsupportedOperationException();
}
public boolean hasNext(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
return !_stack.empty();
}
public Node<K,V> next(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
if(!hasNext()){
throw new NoSuchElementException();
}
BSTNode<K,V> node = _stack.pop();
BSTNode<K,V> x = node._right;
while (x != null){
_stack.push(x);
x = x._left;
}
return node;
}
}
@Override
public String toString(){
if(_root == null) return "[]";
return _root.toString();
}
private static class BSTNode<K,V> implements Node<K,V>{
K _key;
V _value;
BSTNode<K,V> _left, _right, _parent;
public BSTNode(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
_key = key;
_value = value;
}
public K key(){
return _key;
}
public V value(){
return _value;
}
public Node<K,V> left(){
return _left;
}
public Node<K,V> right(){
return _right;
}
public Node<K,V> parent(){
return _parent;
}
boolean isLeft(){
if(_parent == null) return false;
return _parent._left == this;
}
boolean isRight(){
if(_parent == null) return false;
return _parent._right == this;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
try{
BSTNode<K,V> node = (BSTNode<K,V>)o;
return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
}catch (ClassCastException ex){
return false;
}
}
@Override
public int hashCode(){
int hashCode = _key.hashCode();
if(_value != null){
hashCode ^= _value.hashCode();
}
return hashCode;
}
@Override
public String toString(){
String leftStr = _left != null ? _left.toString() : "";
String rightStr = _right != null ? _right.toString() : "";
return "["+leftStr+" "+_key+" "+rightStr+"]";
}
}
}
Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32
. This leads to a broken array with wrong dimensions and the above mentioned error.
To solve the problem, make sure that all images have the correct dimensions.
Like many many people, I have had the same problem. Although the user is set to use mysql_native_password, and I can connect from the command line, the only way I could get mysqli() to connect is to add
default-authentication-plugin=mysql_native_password
to the [mysqld] section of, in my setup on ubuntu 19.10, /etc/mysql/mysql.conf.d/mysqld.cnf
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
One of the possible reasons is when you load jQuery TWICE ,like:
<script src='..../jquery.js'></script>
....
....
....
....
....
<script src='......./jquery.js'></script>
So, check your source code and remove duplicate jQuery load.
I was getting the same error coz I change my github user name, then I do this:
git remote -v
then:
git remote set-url newname newurl
git push -u origin master
this time I was able to push to the repository. I hope this helps.
I don't think that you'll like it but I made a pair port for python :) using it is some how similar to c++
pair = Pair
pair.make_pair(value1, value2)
or
pair = Pair(value1, value2)
here's the source code pair_stl_for_python
I fixed it like this example.
$scope.myCalendar = new Date(myUnixDate*1000);
<input date-time ng-model="myCalendar" format="DD/MM/YYYY" />
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
Microsoft Visual Studio 2008 Service Pack 1 (iso)
http://www.microsoft.com/en-us/download/details.aspx?id=13276
Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB
Supported Operating System
Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
On Windows Vista: 2.4 GHz CPU, 768 MB RAM
Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.
Well ya you can do that in this way.
<input type="text" name="address" id="address">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<input type="button" onclick="showAddress(address.value)" value="ShowMap"/>
Java Script
function showAddress(address){
alert("This is address :"+address)
}
That is one example for the same. and that will run.
another way is to use the range method
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]
print a + b
=> [1, 2, 3, 40, 50 , 60]
I think DATETIME2
is the better way to store the date
, because it has more efficiency than
the DATETIME
. In SQL Server 2008
you can use DATETIME2
, it stores a date and time, takes 6-8 bytes
to store and has a precision of 100 nanoseconds
. So anyone who needs greater time precision will want DATETIME2
.
Using ANSI SQL-92 CASE Statements, you could do something like this (derived table plus case):
SELECT jobId, jobName, SUM(Priority1)
AS Priority1, SUM(Priority2) AS
Priority2, SUM(Priority3) AS
Priority3, SUM(Priority4) AS
Priority4, SUM(Priority5) AS
Priority5 FROM (
SELECT jobId, jobName,
CASE WHEN Priority = 1 THEN 1 ELSE 0 END AS Priority1,
CASE WHEN Priority = 2 THEN 1 ELSE 0 END AS Priority2,
CASE WHEN Priority = 3 THEN 1 ELSE 0 END AS Priority3,
CASE WHEN Priority = 4 THEN 1 ELSE 0 END AS Priority4,
CASE WHEN Priority = 5 THEN 1 ELSE 0 END AS Priority5
FROM TableName
)
Had the same issue, but executing the queries alone will not help. To fix this I did the following,
UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];
}
-(void)btnClicked
{
// Here You can write functionality
}
I also faced this problem when I used
String BaseFolder = "3patti_Logs";
S3Object object = s3client.getObject(bucketName, BaseFolder);
I got error key not found
When I hit and try
String BaseFolder = "3patti_Logs";
S3Object object = s3client.getObject(bucketName, BaseFolder+"/");
it worked , this code is working with 1.9 jar otherwise update to 1.11 and use doesObjectExist as said above
Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.
The correct url should be in the format with file name included like "http://server name/document library name/new file name"
So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.
Easy, simply wrap a MemoryStream
around it:
Stream stream = new MemoryStream(buffer);
just a different approach
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
will represent ascii of a.. and thus the other characters in the whole array.
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
The simplest solution would be a correlated sub select:
select
A.*
from
table_A A
where
A.id in (
select B.id from table_B B where B.tag = 'chair'
)
Alternatively you could join the tables and filter the rows you want:
select
A.*
from
table_A A
inner join table_B B
on A.id = B.id
where
B.tag = 'chair'
You should profile both and see which is faster on your dataset.
You can use lambda to bind a method to an instance:
def run(self):
print self._instanceString
class A(object):
def __init__(self):
self._instanceString = "This is instance string"
a = A()
a.run = lambda: run(a)
a.run()
Output:
This is instance string
java -DLOG_DIR=${LOG_DIR} -jar myjar.jar "param1" "param2"
==> in cmd line if you have "value="${LOG_DIR}/log/clientProject/project-error.log" in xml
I solved this error
A connection attempt failed with "ECONNREFUSED - Connection refused by server"
by changing my port to 22 that was successful
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
and you leave it null
(0
) when persisting. (null
if you use the Integer
/ Long
wrappers)
In some cases the AUTO
strategy is resolved to SEQUENCE
rathen than to IDENTITY
or TABLE
, so you might want to manually set it to IDENTITY
or TABLE
(depending on the underlying database).
It seems SEQUENCE
+ specifying the sequence name worked for you.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
1-press CTRL F
2-paste the copied text in search bar
3-press CTRL A followed by CTRL C to copy the text again from search
4-paste in Notepad++
5-replace 'space'
with ','
This allows for parallel execution on all android versions with API 4+ (Android 1.6+):
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
This is a summary of Arhimed's excellent answer.
Please make sure you use API level 11 or higher as your project build target. In Eclipse, that is Project > Properties > Android > Project Build Target
. This will not break backward compatibility to lower API levels. Don't worry, you will get Lint errors if your accidentally use features introduced later than minSdkVersion
. If you really want to use features introduced later than minSdkVersion
, you can suppress those errors using annotations, but in that case, you need take care about compatibility yourself. This is exactly what happened in the code snippet above.
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
I find the existing explanations too gobbledygook. Here's my explanation in plain English:
STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.
MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.
That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.
A simple ddply
option:
ddply(test,.(id),function(x) head(x,1))
If speed is an issue, a similar approach could be taken with data.table
:
testd <- data.table(test)
setkey(testd,id)
testd[,.SD[1],by = key(testd)]
or this might be considerably faster:
testd[testd[, .I[1], by = key(testd]$V1]
If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.
Otherwise, look for list comprehensions used with the zip builtin function:
[a_i - b_i for a_i, b_i in zip(a, b)]
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
All string
objects are immutable in C#. Objects of the class string
, once created, can never represent any value other than the one they were constructed with. All operations that seem to "change" a string instead produce a new one. This is inefficient with memory, but extremely useful with regard to being able to trust that a string won't change out form under you- because as long as you don't change your reference, the string being referred to will never change.
A mutable object, by contrast, has data fields that can be altered. One or more of its methods will change the contents of the object, or it has a Property that, when written into, will change the value of the object.
If you have a mutable object- the most similar one to String is StringBuffer
- then you have to make a copy of it if you want to be absolutely sure it won't change out from under you. This is why mutable objects are dangerous to use as keys into any form of Dictionary
or set- the objects themselves could change, and the data structure would have no way of knowing, leading to corrupt data that would, eventually, crash your program.
However, you can change its contents- so it's much, much more memory efficient than making a complete copy because you wanted to change a single character, or something similar.
Generally, the right thing to do is use mutable objects while you're creating something, and immutable objects once you're done. This applies to objects that have immutable forms, of course; most of the collections don't. It's often useful to provide read-only forms of collections, though, which is the equivalent of immutable, when sending the internal state of your collection to other contexts- otherwise, something could take that return value, do something to it, and corrupt your data.
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
Just in general, if this happens in Windows, and you are using tortoisegit, it is the status cache of tortoisegit. Kill that process and it will be freed.
Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.
<style type="text/css">
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px; height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; }
h3.nextelement { clear: both; }
</style>
<ul id="imageSet">
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
</ul>
<h3 class="nextelement">Next Element in Doc</h3>
Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)
How about
session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()
edit: Without the ORM, it would be
session.execute(
select(
[MyUserTable.c.id, MyUserTable.c.name],
MyUserTable.c.id.in_((123, 456))
)
).fetchall()
select()
takes two parameters, the first one is a list of fields to retrieve, the second one is the where
condition. You can access all fields on a table object via the c
(or columns
) property.
None of the above solutions worked for me on localhost. I even allowed access from less secure apps, allowed access through display unlock captcha and set the verify peer and verify peer name to false for SSL.
Eventually, I used the open source SMTP testing solution of MailHog. The steps are as follows:
MAIL_DRIVER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
MAIL_USERNAME=testuser
MAIL_PASSWORD=testpwd
MAIL_ENCRYPTION=null
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
I believe you can do this using a cast:
float f_val = 3.6f;
int i_val = (int) f_val;
Please use SqlBulkCopyColumnMapping.
Example:
private void SaveFileToDatabase(string filePath)
{
string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MHMRA_TexMedEvsConnectionString"].ConnectionString.ToString();
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select * from [Crosswalk$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "PaySrcCrosswalk";
// this is a simpler alternative to explicit column mappings, if the column names are the same on both sides and data types match
foreach(DataColumn column in dt.Columns) {
s.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
}
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
Following is my TypeScript code which can be converted easily into JavaScript and you can use
/**
* Convert BASE64 to BLOB
* @param base64Image Pass Base64 image data to convert into the BLOB
*/
private convertBase64ToBlob(base64Image: string) {
// Split into two parts
const parts = base64Image.split(';base64,');
// Hold the content type
const imageType = parts[0].split(':')[1];
// Decode Base64 string
const decodedData = window.atob(parts[1]);
// Create UNIT8ARRAY of size same as row data length
const uInt8Array = new Uint8Array(decodedData.length);
// Insert all character code into uInt8Array
for (let i = 0; i < decodedData.length; ++i) {
uInt8Array[i] = decodedData.charCodeAt(i);
}
// Return BLOB image after conversion
return new Blob([uInt8Array], { type: imageType });
}
C++11 standard on jumping over some initializations
JohannesD gave an explanation, now for the standards.
The C++11 N3337 standard draft 6.7 "Declaration statement" says:
3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).
87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.
[ Example:
void f() { // ... goto lx; // ill-formed: jump into scope of a // ... ly: X a = 1; // ... lx: goto ly; // OK, jump implies destructor // call for a followed by construction // again immediately following label ly }
— end example ]
As of GCC 5.2, the error message now says:
crosses initialization of
C
C allows it: c99 goto past initialization
The C99 N1256 standard draft Annex I "Common warnings" says:
2 A block with initialization of an object that has automatic storage duration is jumped into
This may also tangentially help, to understand if a logging request (from the code) at a certain level will result in it actually being logged given the effective logging level that a deployment is configured with. Decide what effective level you want to configure you deployment with from the other Answers here, and then refer to this to see if a particular logging request from your code will actually be logged then...
For examples:
from logback documentation:
In a more graphic way, here is how the selection rule works. In the following table, the vertical header shows the level of the logging request, designated by p, while the horizontal header shows effective level of the logger, designated by q. The intersection of the rows (level request) and columns (effective level) is the boolean resulting from the basic selection rule.
So a code line that requests logging will only actually get logged if the effective logging level of its deployment is less than or equal to that code line's requested level of severity.
There are couple of good free service that let you do the same. Ideal for showing something quickly for testing:
Edits:
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT
clause). You can only select one column from such a query in this context.
Consider joining to the users
table instead; this will give you more flexibility when selecting what columns you want from users
.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
If it fits the protocol you use, consider using a DataInputStream, where the behavior is very well defined.
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
Try to use "n" the Node extremely simple package manager.
> npm install -g n
Once you have "n" installed. You can pull the latest node by doing the following:
> n latest
I've used it successfully on Ubuntu 16.0x and MacOS 10.12 (Sierra)
Reference: https://github.com/tj/n
Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:
resources :articles do
resources :comments
end
You get paths like:
/articles/42
/articles/42/comments/99
routed to controllers at
app/controllers/articles_controller.rb
app/controllers/comments_controller.rb
just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.
But partials and forms become tricky. Note the square brackets:
<%= form_for [@article, @comment] do |f| %>
Most important, if you want a URI, you may need something like this:
article_comment_path(@article, @comment)
Alternatively:
[@article, @comment]
as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
For example, inside a collections partial with comment_item
supplied for iteration,
<%= link_to "delete", article_comment_path(@article, comment_item),
:method => :delete, :confirm => "Really?" %>
What jamuraa says may work in the context of Article, but it did not work for me in various other ways.
There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources
Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:
# POST /comments
post :create, :comment => {:article_id=>42, ...}
In order to test the route that they may prefer, they need to do it this way:
# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}
I learned this because my unit-tests started failing when I switched from this:
resources :comments
resources :articles do
resources :comments
end
to this:
resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:
resources :comments
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
Sorry for the long answer. Not many people are aware of the subtleties, I think.
Try this
SELECT t1.*
FROM
some_table t1,
(SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT (*) > 1) t2
WHERE
t1.relevant_field = t2.relevant_field;
Short version of Franci's answer:
for(Iterator<String> iter = json.keys();iter.hasNext();) {
String key = iter.next();
...
}
Here's my workaround:
I created a library with Angular 6. I added a common component commonlib-header
which is used like this in an external application.
Note the serviceReference
which is the class (injected in the component constructor(public serviceReference: MyService)
that uses the commonlib-header
) that holds the stringFunctionName
method:
<commonlib-header
[logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
[buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
</common-header>
The library component is programmed like this. The dynamic event is added in the onClick(fn: any)
method:
export class HeaderComponent implements OnInit {
_buttons: Array<NavItem> = []
@Input()
set buttons(buttons: Array<any>) {
buttons.forEach(navItem => {
let _navItem = new NavItem(navItem.href, navItem.innerHtml)
_navItem.class = navItem.class
_navItem.onClick = navItem.onClick // this is the array from the component @Input properties above
this._buttons[navItem.index] = _navItem
})
}
constructor() {}
ngOnInit() {}
onClick(fn: any){
let ref = fn[0]
let fnName = fn[1]
let args = fn[2]
ref[fnName].apply(ref, args)
}
The reusable header.component.html
:
<div class="topbar-right">
<button *ngFor="let btn of _buttons"
class="{{ btn.class }}"
(click)="onClick(btn.onClick)"
[innerHTML]="btn.innerHtml | keepHtml"></button>
</div>
You can't name a variable with capital letters or Ruby will asume its a constant and will want it to keep it's value constant, in which case changing it's value would be an error an "dynamic constant assignment error". With lower case should be fine
class MyClass
def mymethod
myconstant = "blah"
end
end
macOS 10.15.7
Prefrences...
Window
tabScrollback
to Limit number of rows to:
what your wanted.I'd had this issue with Eclipse 2019-12 where the includes were previously being resolved, but then weren't. This was with a Meson build C/C++ project. I'm not sure exactly what happened, but closing the project and reopening it resolved the issue for me.
Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.
You can use it like this:
Intent intent = new...
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("myKey", AnyValue);
startActivity(intent);
You can get the passed values by doing:
Bundle extras = intent.getExtras();
String tmp = extras.getString("myKey");
You can find more info at:
Use Calendar
Calendar.getInstance().get(Calendar.MILLISECOND);
or
Calendar c=Calendar.getInstance();
c.setTime(new Date()); /* whatever*/
//c.setTimeZone(...); if necessary
c.get(Calendar.MILLISECOND);
In practise though I think it will nearly always equal System.currentTimeMillis()%1000; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.
You can also make it a reusable method by expending JavaScript:
Array.prototype.findIndexBy = function(key, value) {
return this.findIndex(item => item[key] === value)
}
const peoples = [{name: 'john'}]
const cats = [{id: 1, name: 'kitty'}]
peoples.findIndexBy('name', 'john')
cats.findIndexBy('id', 1)
If your are using express above 2.x
, you have to declare app.router
like below code. Please try to replace your code
app.use('/', routes);
with
app.use(app.router);
routes.initialize(app);
Please click here to get more details about app.router
app.router
is depreciated in express 3.0+
. If you are using express 3.0+, refer to Anirudh's answer below.
I think what you're looking for is an IP Geolocation database or service provider. There are many out there and some are free (get what you pay for).
Although I haven't used this service before, it claims to be in real-time. https://kickfire.com/kf-api
Here's another IP geo location API from Abstract API - https://www.abstractapi.com/ip-geolocation-api
But just do a google search on IP geo and you'll get more results than you need.
You can't without an iteration.
Option 1
Carnet findCarnet(String codeIsIn) {
for(Carnet carnet : listCarnet) {
if(carnet.getCodeIsIn().equals(codeIsIn)) {
return carnet;
}
}
return null;
}
Option 2
Override the equals()
method of Carnet
.
Option 3
Storing your List
as a Map
instead, using codeIsIn
as the key:
HashMap<String, Carnet> carnets = new HashMap<>();
// setting map
Carnet carnet = carnets.get(codeIsIn);
The easiest way to remove any link from the My Account panel in Magento is to first copy:
app/design/frontend/base/default/template/customer/account/navigation.phtml
to
app/design/frontend/enterprise/YOURSITE/template/customer/account/navigation.phtml
Open the file and fine this line, it should be around line 34:
<?php $_index = 1; ?>
Right below it add this:
<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */
?>
Just remove any of the links here that you DO want to appear.
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
This is documented in the 'R Installation and Administration' manual that came with your installation.
On my Linux box:
R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"
[3] "/usr/lib/R/library"
R>
meaning that the default path is the first of these. You can override that via an argument to both install.packages()
(from inside R) or R CMD INSTALL
(outside R).
You can also override by setting the R_LIBS_USER variable.
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
You can test whether an array has a certain element at all or not with isset() or sometimes even better array_key_exists() (the documentation explains the differences). If you can't be sure if the array has an element with the index 'say' you should test that first or you might get 'warning: undefined index....' messages.
As for the test whether the element's value is equal to a string you can use == or (again sometimes better) the identity operator === which doesn't allow type juggling.
if( isset($something['say']) && 'bla'===$something['say'] ) {
// ...
}
see more this url:
http://www.baeldung.com/spring-nosuchbeandefinitionexception
Here is combined solution for purging Core Data.
- (void)deleteAllObjectsInCoreData
{
NSArray *allEntities = self.managedObjectModel.entities;
for (NSEntityDescription *entityDescription in allEntities)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];
fetchRequest.includesPropertyValues = NO;
fetchRequest.includesSubentities = NO;
NSError *error;
NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Error requesting items from Core Data: %@", [error localizedDescription]);
}
for (NSManagedObject *managedObject in items) {
[self.managedObjectContext deleteObject:managedObject];
}
if (![self.managedObjectContext save:&error]) {
NSLog(@"Error deleting %@ - error:%@", entityDescription, [error localizedDescription]);
}
}
}
Suggest use Apache IOUtils.readLines for this. See link below.
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here's a short-and-sweet version using the "DO" statement:
DO $$
BEGIN
BEGIN
ALTER TABLE <table_name> ADD COLUMN <column_name> <column_type>;
EXCEPTION
WHEN duplicate_column THEN RAISE NOTICE 'column <column_name> already exists in <table_name>.';
END;
END;
$$
You can't pass these as parameters, you'll need to do variable substitution in the string on the client side, but this is a self contained query that only emits a message if the column already exists, adds if it doesn't and will continue to fail on other errors (like an invalid data type).
I don't recommend doing ANY of these methods if these are random strings coming from external sources. No matter what method you use (client-side or server-side dynamic strings executed as queries), it would be a recipe for disaster as it opens you to SQL injection attacks.
You have to use cin.getline()
:
char input[100];
cin.getline(input,sizeof(input));
Another way to think about Return-Path
vs Reply-To
is to compare it to snail mail.
When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path
.
Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To
.
In essence, a Postage Return Address is comparable to SMTP's Return-Path
header and SMTP's Reply-To
header is similar to the replying instructions contained in a letter.
find out what the date was 5 days ago from today in php
$date = strtotime(date("Y-m-d", strtotime("-5 day")));
find out what the date was n days ago from today in php
$date = strtotime(date("Y-m-d", strtotime("-n day")));
Various NPM packages are available to make this task easy.
For Development
For Production (with extended functionality such as clustering, remote deploy etc.)
npm install -g pm2
npm install -g strongloop
Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.
For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:
easy_install -U packageName
Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.
If you would like to prepend array (a1 with an array a2) you could use the following:
var a1 = [1, 2];
var a2 = [3, 4];
Array.prototype.unshift.apply(a1, a2);
console.log(a1);
// => [3, 4, 1, 2]
I have resolved this one by creating the POJO class (Student.class) of the JSON and Main Class is used for read the values from the JSON in the problem.
**Main Class**
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "[ \r\n" + " {\r\n" + " \"firstName\" : \"abc\",\r\n"
+ " \"lastName\" : \"xyz\"\r\n" + " }, \r\n" + " {\r\n"
+ " \"firstName\" : \"pqr\",\r\n" + " \"lastName\" : \"str\"\r\n" + " } \r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
List<Student> details = mapper.readValue(jsonStr, new
TypeReference<List<Student>>() { });
for (Student itr : details) {
System.out.println("Value for getFirstName is: " +
itr.getFirstName());
System.out.println("Value for getLastName is: " +
itr.getLastName());
}
}
**RESULT:**
Value for getFirstName is: abc
Value for getLastName is: xyz
Value for getFirstName is: pqr
Value for getLastName is: str
**Student.class:**
public class Student {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
} }
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
By default time zone of laravel project is **UTC*
'timezone' => 'UTC',
now change according to your time zone for me it's Asia/Calcutta
so for me setting will be 'timezone' => 'Asia/Calcutta',
*for time zone list visit this url https://www.w3schools.com/php/php_ref_timezones.asp
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
Hide keyboard when user clicks search. Addition to Robby Pond answer
private void performSearch() {
editText.clearFocus();
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(editText.getWindowToken(), 0);
//...perform search
}
var message = document.getElementById('contact-error');_x000D_
$('#contact').focusout(function(){_x000D_
if(!$(this).val().match('[0-9]{10}')) {_x000D_
$('#contact-error').addClass('contact-message');_x000D_
message.innerHTML = "required 10 digits, match requested format!";_x000D_
}else {_x000D_
$('#contact-error').removeClass('contact-message');_x000D_
message.innerHTML = "";_x000D_
}_x000D_
})
_x000D_
.contact-message {_x000D_
display: block;_x000D_
margin-bottom: 20px;_x000D_
color: #cc0033;_x000D_
}
_x000D_
<input type="text" id="contact" required>_x000D_
<span id="contact-error"></span>
_x000D_
true
or if its empty.The method empty?
comes from the Array class
http://ruby-doc.org/core-2.0.0/Array.html#method-i-empty-3F
It's used to check if the array contains something or not. This includes things that evaluate to false
, such as nil
and false
.
>> a = []
=> []
>> a.empty?
=> true
>> a = [nil, false]
=> [nil, false]
>> a.empty?
=> false
>> a = [nil]
=> [nil]
>> a.empty?
=> false
The method any?
comes from the Enumerable module.
http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-any-3F
It's used to evaluate if "any" value in the array evaluates to true
.
Similar methods to this are none?
, all?
and one?
, where they all just check to see how many times true could be evaluated. which has nothing to do with the count of values found in a array.
case 1
>> a = []
=> []
>> a.any?
=> false
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> true
case 2
>> a = [nil, true]
=> [nil, true]
>> a.any?
=> true
>> a.one?
=> true
>> a.all?
=> false
>> a.none?
=> false
case 3
>> a = [true, true]
=> [true, true]
>> a.any?
=> true
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> false
Hope this helps : Declared a variable , in case of any changes need to be made thats only once .
declare @line varchar(100)
set @line ='[email protected]'
select SUBSTRING(@line ,(charindex('-',@line)+1), CHARINDEX('@',@line)-charindex('-',@line)-1)
OPTIONS
method returns info about API (methods/content type)
HEAD
method returns info about resource (version/length/type)
Server response
OPTIONS
HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0
HEAD
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
OPTIONS
Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?HEAD
Checking whether a resource has changed. This is useful when maintaining a cached version of a resourceHEAD
Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrievalHEAD, OPTIONS
Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application
Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.
A few things I'd like to add here:
Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.
There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won't launch.
There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
You are returning Observable<Product>
and expecting it to be Product[]
inside subscribe
callback.
The Type returned from http.get()
and getProducts()
should be Observable<Product[]>
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
I prefer "timelimit", which has a package at least in debian.
http://devel.ringlet.net/sysutils/timelimit/
It is a bit nicer than the coreutils "timeout" because it prints something when killing the process, and it also sends SIGKILL after some time by default.
If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017
Agent queue.
I know this thread is old... but in "modern times".. there is a far superior "include strategy" via clang's @import
modules - that is oft-overlooked..
Modules improve access to the API of software libraries by replacing the textual preprocessor inclusion model with a more robust, more efficient semantic model. From the user’s perspective, the code looks only slightly different, because one uses an import declaration rather than a #include preprocessor directive:
@import Darwin; // Like including all of /usr/include. @see /usr/include/module.map
or
@import Foundation; // Like #import <Foundation/Foundation.h>
@import ObjectiveC; // Like #import <objc/runtime.h>
However, this module import behaves quite differently from the corresponding #include: when the compiler sees the module import above, it loads a binary representation of the module and makes its API available to the application directly. Preprocessor definitions that precede the import declaration have no impact on the API provided... because the module itself was compiled as a separate, standalone module. Additionally, any linker flags required to use the module will automatically be provided when the module is imported. This semantic import model addresses many of the problems of the preprocessor inclusion model.
To enable modules, pass the command-line flag -fmodules
aka CLANG_ENABLE_MODULES
in Xcode
- at compile time. As mentioned above.. this strategy obviates ANY and ALL LDFLAGS
. As in, you can REMOVE any "OTHER_LDFLAGS" settings, as well as any "Linking" phases..
I find compile / launch times to "feel" much snappier (or possibly, there's just less of a lag while "linking"?).. and also, provides a great opportunity to purge the now extraneous Project-Prefix.pch file, and corresponding build settings, GCC_INCREASE_PRECOMPILED_HEADER_SHARING
, GCC_PRECOMPILE_PREFIX_HEADER
, and GCC_PREFIX_HEADER
, etc.
Also, while not well-documented… You can create module.map
s for your own frameworks and include them in the same convenient fashion. You can take a look at my ObjC-Clang-Modules github repo for some examples of how to implement such miracles.
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
The first thing you need is the real File path If you have it great, if you are using URI then use this method to get the real Path:
public static String getRealPathFromURI(Uri contentURI,Context context) {
String path= contentURI.getPath();
try {
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = context.getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
catch(Exception e)
{
return path;
}
return path;
}
extract your Bitmap for example:
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
}
catch (IOException e)
{
Log.e("IOException",e.toString());
}
you can use decodeFile() instead if you wish.
Now that you have the Bitmap and the real Path get the Orientation of the Image:
private static int getExifOrientation(String src) throws IOException {
int orientation = 1;
ExifInterface exif = new ExifInterface(src);
String orientationString=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
try {
orientation = Integer.parseInt(orientationString);
}
catch(NumberFormatException e){}
return orientation;
}
and finally rotate it to the right position like so:
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
try {
int orientation = getExifOrientation(src);
if (orientation == 1) {
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case 2:
matrix.setScale(-1, 1);
break;
case 3:
matrix.setRotate(180);
break;
case 4:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case 5:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case 6:
matrix.setRotate(90);
break;
case 7:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case 8:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return oriented;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
That's it , you now have the bitmap rotated to the right position.
cheers.
try this
for example
DecimalFormat df = new DecimalFormat("#.##");
df.format(55.544545);
output:
55.54
Now which drive letter did that removable device get?
Two ways to locate e.g. a USB-disk in git Bash
:
$ cat /proc/partitions major minor #blocks name win-mounts 8 0 500107608 sda 8 1 1048576 sda1 8 2 131072 sda2 8 3 496305152 sda3 C:\ 8 4 1048576 sda4 8 5 1572864 sda5 8 16 0 sdb 8 32 0 sdc 8 48 0 sdd 8 64 0 sde 8 80 3952639 sdf 8 81 3950592 sdf1 E:\ $ mount C:/Program Files/Git on / type ntfs (binary,noacl,auto) C:/Program Files/Git/usr/bin on /bin type ntfs (binary,noacl,auto) C:/Users/se2982/AppData/Local/Temp on /tmp type ntfs (binary,noacl,posix=0,usertemp) C: on /c type ntfs (binary,noacl,posix=0,user,noumount,auto) E: on /e type vfat (binary,noacl,posix=0,user,noumount,auto) G: on /g type ntfs (binary,noacl,posix=0,user,noumount,auto) H: on /h type ntfs (binary,noacl,posix=0,user,noumount,auto)
... so; likely drive letter in this example => /e
(or E:\ if you must), when knowing that C, G, and H are other things (in Windows).
This is the solution according to the VS code debugging page. This worked for my setup on Windows 10.
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${file}"
}
The solution is here:
https://code.visualstudio.com/docs/editor/debugging
Here is the launch configuration generated for Node.js debugging
Hypothetically, if search landed you on this question then you probably want this:
doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));
Why? Because like me you value time and you are not going to implement .equals
just for the sake of the single test scenario.
And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null
at all costs, use Optional
or move to Kotlin. This implies that verify
does not need to be used that often and ArgumentCaptors are just too tedious to write.
Think of Observables as a pipe with flowing water in it, sometimes water flows and sometimes it doesn't. In some cases, you may actually need a pipe that has always water in it, you can do this by creating a special pipe which always contains a water no matter how small it is, lets call this special pipe BehaviorSubject, if you happens to be a water supply provider in your community, you can sleep peacefully at night knowing that your newly installed pipe just works.
In technical terms: you may encounter usescases where an Observable should always have value in it, perhaps you want to capture the value of a input text over time, you can then create an instance of BehaviorSubject to ensure this kind of behavior, lets say:
const firstNameChanges = new BehaviorSubject("<empty>");
// pass value changes.
firstNameChanges.next("Jon");
firstNameChanges.next("Arya");
You can then use "value" to sample changes over time.
firstNameChanges.value;
This comes handy when you combine Observables later, by taking a look at the type of your stream as BehaviorSubject you can then ensure that the stream at least fires or signal just once atleast.
For those using Yarn as their package manager instead of npm:
yarn global add babel-cli