I prefer the VBA-solution for professional solutions.
With the replace-procedure part in the question search and replace WHOLE WORDS ONLY, I use the following VBA-procedure:
''
' Evaluate Formula-Text in Excel
'
Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As Variant) As Variant
Dim i As Long
'
' replace strings by values
'
For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i), variablesAndValues(i + 1))
Next
'
' internationalisation
'
myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
myFormula = Replace(myFormula, Application.International(xlListSeparator), ",")
'
' return value
'
wm_Eval = Application.Evaluate(myFormula)
End Function
''
' Replace Whole Word
'
' Purpose : replace [strFind] with [strReplace] in [strSource]
' Comment : [strFind] can be plain text or a regexp pattern;
' all occurences of [strFind] are replaced
Public Function RegExpReplaceWord(ByVal strSource As String, _
ByVal strFind As String, _
ByVal strReplace As String) As String
' early binding requires reference to Microsoft VBScript
' Regular Expressions:
' with late binding, no reference needed:
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
're.IgnoreCase = True ' <-- case insensitve
re.Pattern = "\b" & strFind & "\b"
RegExpReplaceWord = re.Replace(strSource, strReplace)
Set re = Nothing
End Function
Usage of the procedure in an excel sheet looks like:
The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:
struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare());
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
Your SVN passwords in Ubuntu (12.04) are in:
~/.subversion/auth/svn.simple/
However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.
To install it on Ubuntu – add repository :
sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update
Install it:
sudo apt-get install gkeyring
And run as following:
gkeyring --id 15 --output=name,secret
Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.
I just type brew -v in terminal if you have it it will respond with the version number installed.
There is another approach with the MQ extension and the debug commands. This is a general way to modify history without losing data. Let me assume the same situation as Antonio.
// set current tip to rev 497
hg debugsetparents 497
hg debugrebuildstate
// hg add/remove if needed
hg commit
hg strip [-n] 498
Follow this :
1. File > Preferences > setting
2. In search type -> git path
3. Now scroll down a little > you will see "Git:path" section.
4. Click "Edit in settings.json".
5. Now just paste this path there "C:\\Program Files\\Git\\mingw64\\libexec\\git-core\\git.exe"
Restart VSCode and open new terminal in VSCode and try "git version"
In case still problem exists :
1. Inside terminal click on terminal options (1:Poweshell)
2. Select default shell
3. Select bash
open new terminal and change terminal option to 2:Bash Again try "git version" - this should work :)
Added to @muffls answer so that this works with all twitter bootstrap collapse and makes the change to the arrow before the animatation starts.
$('.collapse').on('show', function(){
$(this).parent().find(".icon-chevron-left").removeClass("icon-chevron-left").addClass("icon-chevron-down");
}).on('hide', function(){
$(this).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-left");
});
Depending on your HTML structure you may need to modify the parent()
.
This can be done in one pass with an O(N log N) algorithm and no extra storage.
Proceed from element a[1]
to a[N]
. At each stage i
, all of the elements to the left of a[i]
comprise a sorted heap of elements a[0]
through a[j]
. Meanwhile, a second index j
, initially 0, keeps track of the size of the heap.
Examine a[i]
and insert it into the heap, which now occupies elements a[0]
to a[j+1]
. As the element is inserted, if a duplicate element a[k]
is encountered having the same value, do not insert a[i]
into the heap (i.e., discard it); otherwise insert it into the heap, which now grows by one element and now comprises a[0]
to a[j+1]
, and increment j
.
Continue in this manner, incrementing i
until all of the array elements have been examined and inserted into the heap, which ends up occupying a[0]
to a[j]
. j
is the index of the last element of the heap, and the heap contains only unique element values.
int algorithm(int[] a, int n)
{
int i, j;
for (j = 0, i = 1; i < n; i++)
{
// Insert a[i] into the heap a[0...j]
if (heapInsert(a, j, a[i]))
j++;
}
return j;
}
bool heapInsert(a[], int n, int val)
{
// Insert val into heap a[0...n]
...code omitted for brevity...
if (duplicate element a[k] == val)
return false;
a[k] = val;
return true;
}
Looking at the example, this is not exactly what was asked for since the resulting array preserves the original element order. But if this requirement is relaxed, the algorithm above should do the trick.
To prevent unexpected margins and other browser-specific behavior in the future, I'd recommend to include reset.css in your stylesheets.
Be aware that you'll have to set the h[1..6] font size and weight to make headings look like headings again after that, and many other things.
Unfortunately,
mimeType = file.toURL().openConnection().getContentType();
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
However, you have this:
mimeType= URLConnection.guessContentTypeFromName(file.getName());
and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream
However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).
It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4
These arguments are passed to the program as an array of strings.
string[] args
// Array of Strings containing arguments.
You have to use absolute
position along with your desired height.
in your CSS, do the following:
#id-of-iFrame {
position: absolute;
height: 100%;
}
try this
Execute this SQL:
SHOW TABLE STATUS LIKE '<tablename>'
and fetch the value of the field Auto_increment
When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
Shortcut from JavaDoc:
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >=
and <=
:
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
String interning is an optimization technique by the compiler. If you have two identical string literals in one compilation unit then the code generated ensures that there is only one string object created for all the instance of that literal(characters enclosed in double quotes) within the assembly.
I am from C# background, so i can explain by giving a example from that:
object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;
output of the following comparisons:
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // false !?
Note1:Objects are compared by reference.
Note2:typeof(int).Name is evaluated by reflection method so it does not gets evaluated at compile time. Here these comparisons are made at compile time.
Analysis of the Results: 1) true because they both contain same literal and so the code generated will have only one object referencing "Int32". See Note 1.
2) true because the content of both the value is checked which is same.
3) FALSE because str2 and obj does not have the same literal. See Note 2.
I did it in my project:
Global Events in application.js:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
"loading" is the element to show and hide!
References: http://api.jquery.com/Ajax_Events/
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.
df[cat]=df[cat].astype('category')
And then check df.dtypes and perform label encoding.
If you go here you can find a comprehensive matrix that includes both the NLog and Log4Net libs as well as Enterprise Lib and other products.
Somebody could argue that the matrix is done in a way to underline the features of the only commercial lib present in the matrix. I think it's true but it was useful anyway to drive my choice versus NLog.
Regards
All the below answers would return you the list.Your need to convert it to matrix
def MATMUL(X, Y):
rows_A = len(X)
cols_A = len(X[0])
rows_B = len(Y)
cols_B = len(Y[0])
if cols_A != rows_B:
print "Matrices are not compatible to Multiply. Check condition C1==R2"
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
print C
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k] * B[k][j]
C = numpy.matrix(C).reshape(len(A),len(B[0]))
return C
You should be able to rely on os.name.
import os
if os.name == 'nt':
# ...
edit: Now I'd say the clearest way to do this is via the platform module, as per the other answer.
In Python, you can use urllib2
(http://docs.python.org/2/library/urllib2.html) to do all of that work for you.
Simply enough:
import urllib2
f = urllib2.urlopen(url)
print f.read()
Will print the received HTTP response.
To pass GET/POST parameters the urllib.urlencode()
function can be used. For more information, you can refer to the Official Urllib2 Tutorial
Great! Now here is styling available for reCaptcha.. I just use inline styling like:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXX" style="transform: scale(1.08); margin-left: 14px;"></div>
whatever you wanna to do small customize in inline styling...
Hope it will help you!!
Since Android API 16 there is a simple way to check if app is in foreground. It may not be foolproof, but no methods on Android are foolproof. This method is good enough to use when your service receives update from server and has to decide whether to show notification, or not (because if UI is foreground, user will notice the update without notification).
RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
isInBackground = myProcess.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
When you double-quote a path, you're stopping the tilde expansion. So there are a few ways to do this:
cd ~/"My Code"
cd ~/'My Code'
The tilde is not quoted here, so tilde expansion will still be run.
cd "$HOME/My Code"
You can expand environment variables inside double-quoted strings; this is basically what the tilde expansion is doing
cd ~/My\ Code
You can also escape special characters (such as space) with a backslash.
I had the same issue on a brand new Windows 10 machine. My setup:
But I couldn't build .NET 4.0 projects:
Die Aufgabe konnte "AL.exe" mit dem SdkToolsPath-Wert "" oder dem Registrierungsschlüssel "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x86
Solution: After trying (and failing) to install the Windows 7 SDK (because thats also includes the .NET 4.0 SDK) I needed to install the Windows 8 SDK and make sure the ".NET Framework 4.5 SDK" is installed.
It's crazy... but worked.
Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)
I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):
def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):
if low=='min':
low=min(s)
elif low=='abs':
low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
if hi=='max':
hi=max(s)
elif hi=='abs':
hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))
if center=='mid':
center=(max(s)+min(s))/2
elif center=='avg':
center=mean(s)
elif center=='median':
center=median(s)
s2=[x-center for x in s]
hi=hi-center
low=low-center
center=0.
r=[]
for x in s2:
if x<low:
r.append(0.)
elif x>hi:
r.append(1.)
else:
if x>=center:
r.append((x-center)/(hi-center)*0.5+0.5)
else:
r.append((x-low)/(center-low)*0.5+0.)
if insideout==True:
ir=[(1.-abs(z-0.5)*2.) for z in r]
r=ir
rr =[x-(x-0.5)*shrinkfactor for x in r]
return rr
This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:
#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]
It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:
#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]
So now "2" which is closest to the center, defined as "1" is the highest value.
Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.
If you are using "n" library @ https://github.com/tj/n . Do the following
echo $NODE_PATH
If node path is empty, then
sudo n latest - sudo is optional depending on your system
After switching Node.js versions using n, npm may not work properly.
curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH
You should see your Node Path now. Else, it might be something else
Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc
In fact, this is probably pretty easy to knock up in Python.
I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.
Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.
<input type='text' minlength=3 /><br />
if browser supports html5,
it will automatical be validate attributes(minlength) in tag
but Safari(iOS) doesn't working
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
You can also get DateTime object from timestamp, including your current daylight saving time:
public DateTime getDateTimeFromTimestamp(Long value) {
TimeZone timeZone = TimeZone.getDefault();
long offset = timeZone.getOffset(value);
if (offset < 0) {
value -= offset;
} else {
value += offset;
}
return new DateTime(value);
}
function validatePhone(inputtxt) {_x000D_
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
return phoneno.test(inputtxt)_x000D_
}
_x000D_
BottomNavigationView
uses colorPrimary from the theme applied for the selected tab and it uses android:textColorSecondary
for the inactive tab icon tint.
So you can create a style with the prefered primary color and set it as a theme to your BottomNavigationView
in an xml layout file.
styles.xml:
<style name="BottomNavigationTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/active_tab_color</item>
<item name="android:textColorSecondary">@color/inactive_tab_color</item>
</style>
your_layout.xml:
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:theme="@style/BottomNavigationTheme"
app:menu="@menu/navigation" />
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
PHP.net explanation about MAX_FILE_SIZE hidden field.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.
http://php.net/manual/en/features.file-upload.post-method.php
If this is nullable int field then yes.
update TableName
set FiledName = null
where Id = SomeId
I take a totally different approach to everyone else's answers here altogether. Let me prefix my solution and argue by stating that sometimes standards and conventions are meant to be broken, especially in the context of the standard HTML lexical tag definitions.
There's nothing to stop you from creating custom elements that are self-descriptive to it's very purpose.
Both modern browsers and even IE 6+ (w/ shim) can support things like:
<icon class="plus">
or
<icon-add>
Just make sure to normalize the tag:
icon { display:block; margin:0; padding:0; border:0; ... }
and use a shim if you need to support IE9 or earlier (see post below).
Check out this StackOverflow Post:
Is there a way to create your own html tag in HTML5
To further my argument, both Google's Angular Directives and the new Polymer projects utilize the concept of custom HTML tags.
Try launching the Emulator from the command line as follows:
emulator -verbose -avd <AVD name>
This will give you detailed output and may show the error that's preventing the emulator from connecting to the Internet.
From the Window menu, Reset Perspective
Insert all n elements from an array to BST takes O(n logn). n elemnts in an array can be inserted to a heap in O(n) time. Which gives heap a definite advantage
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : getParts("foobarspam", 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i=0; i<len; i+=partitionSize)
{
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
}
return parts;
}
}
yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )
with pip installed packages, you can do a
pip freeze
and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do
mkvirtualenv my_new_project
and then (inside that virtualenv), do
pip install all_your_stuff
This way, you can workon my_new_project
and then pip freeze
to see which packages are installed for that virtualenv/project.
for example:
? ~ mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details
(yo_dude)? ~ pip install django
Downloading/unpacking django
Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
Running setup.py egg_info for package django
Installing collected packages: django
Running setup.py install for django
changing mode of build/scripts-2.7/django-admin.py from 644 to 755
changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...
(yo_dude)? ~ pip freeze
Django==1.4.1
wsgiref==0.1.2
(yo_dude)? ~
or if you have a python package with a requirements.pip file,
mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze
will do the trick
I had changed the document root for my wamp-server-installed apache web server. so using the relative url i.e. (images/img.png) didn't work. I had to use the absolute url in order for it to work i.e.
background-image:url("http://localhost/project_x/images/img.png");
Both lines have the same problem
T newT1 = "some text";
T newT2 = (string)t;
The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with
T newT1 = "some text" as T;
T newT2 = t;
you don't need to cast the t since it's already a string, also need to add the constraint
where T : class
When using webview as a subview somewhere in scrollview, you can set height constraint to some constant value and later make outlet from it and use it like:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
webView.scrollView.scrollEnabled = NO;
_webViewHeight.constant = webView.scrollView.contentSize.height;
}
This one disables all bogus verbs and only allows GET and POST
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="false">
<clear/>
<add verb="GET" allowed="true"/>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
</security>
</system.webServer>
Take the number 123.456789
Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..
By default connection timeout is 240 but if you are faceing the problem of connection time out then you can increase upto "300" "Connection Timeout=300"
Basically <key>ITSAppUsesNonExemptEncryption</key><false/>
stands for a Boolean value equal to NO.
Update by @JosepH: This value means that the app uses no encryption, or only exempt encryption. If your app uses encryption and is not exempt, you must set this value to YES/true.
It seems debatable sometimes when an app is considered to use encryption.
If you have LWP installed, it provides a binary simply named "GET".
$ GET http://example.com <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE>Example Web Page</TITLE> </HEAD> <body> <p>You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser.</p> <p>These domain names are reserved for use in documentation and are not available for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </BODY> </HTML>
wget -O-
, curl
, and lynx -source
behave similarly.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
If you have div next each other like this
<div id="1" style="float:left; margin-right:5px">
</div>
<div id="2" style="float:left">
</div>
This should work!
You just want to call an external URL and use the results? PHP does this out of the box, if we're talking about a simple GET request to something serving JSON:
$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);
If you want to do a post request, it's a little harder but there's loads of examples how to do this with curl.
So I guess the question is; what exactly do you want?
If you're using the Web Publish feature in IIS, then the solution I found was to edit the publish configuration and remove the Destination URL
from the configuration (leave it blank).
If this is defined, then every time you publish the project it will open the URL specified in the Destination URL
(which is a redirect URL).
Reference: https://support.winhost.com/kb/a1604/visual-studio-publish-web-deploy.aspx
Simply select the class, right click and choose rename (probably F2 will also do). You can also select the class name in the source file, right click, choose Source, Refactor and rename. In both cases, both the class and the filename will be changed.
My shorter and faster version:
function isElementOutViewport(el){
var rect = el.getBoundingClientRect();
return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;
}
And a jsFiddle as required: https://jsfiddle.net/on1g619L/1/
The problem is that if you redirect StandardOutput
and/or StandardError
the internal buffer can become full. Whatever order you use, there can be a problem:
StandardOutput
the process can block trying to write to it, so the process never ends.StandardOutput
using ReadToEnd then your process can block if the process never closes StandardOutput
(for example if it never terminates, or if it is blocked writing to StandardError
).The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both StandardOutput
and StandardError
you can do this:
EDIT: See answers below for how avoid an ObjectDisposedException if the timeout occurs.
using (Process process = new Process())
{
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) => {
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(timeout) &&
outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
// Process completed. Check process.ExitCode here.
}
else
{
// Timed out.
}
}
}
A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.
This chain will continue up to any node doesn't have a reference point to the next node.
Please find the source code from my tech blog - http://www.algonuts.info/linked-list-program-in-java.html
package info.algonuts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
class LLNode {
int nodeValue;
LLNode childNode;
public LLNode(int nodeValue) {
this.nodeValue = nodeValue;
this.childNode = null;
}
}
class LLCompute {
private static LLNode temp;
private static LLNode previousNode;
private static LLNode newNode;
private static LLNode headNode;
public static void add(int nodeValue) {
newNode = new LLNode(nodeValue);
temp = headNode;
previousNode = temp;
if(temp != null)
{ compute(); }
else
{ headNode = newNode; } //Set headNode
}
private static void compute() {
if(newNode.nodeValue < temp.nodeValue) { //Sorting - Ascending Order
newNode.childNode = temp;
if(temp == headNode)
{ headNode = newNode; }
else if(previousNode != null)
{ previousNode.childNode = newNode; }
}
else
{
if(temp.childNode == null)
{ temp.childNode = newNode; }
else
{
previousNode = temp;
temp = temp.childNode;
compute();
}
}
}
public static void display() {
temp = headNode;
while(temp != null) {
System.out.print(temp.nodeValue+" ");
temp = temp.childNode;
}
}
}
public class LinkedList {
//Entry Point
public static void main(String[] args) {
//First Set Input Values
List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));
Iterator<Integer> ptr = firstIntList.iterator();
while(ptr.hasNext())
{ LLCompute.add(ptr.next()); }
System.out.println("Sort with first Set Values");
LLCompute.display();
System.out.println("\n");
//Second Set Input Values
List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));
ptr = secondIntList.iterator();
while(ptr.hasNext())
{ LLCompute.add(ptr.next()); }
System.out.println("Sort with first & Second Set Values");
LLCompute.display();
System.out.println();
}
}
If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:
netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672
for the remote access.
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
You are probably looking for the timeout
command in coreutils. Since it's a part of coreutils, it is technically a C solution, but it's still coreutils. info timeout
for more details.
Here's an example:
timeout 5 /path/to/slow/command with options
The best you can do is import the dynamic library inside a bridging header:
#import <sqlite3.h>
to the topYou will then be able to access all of the c methods like sqlite3_open
from your swift code.
However, you may just want to use FMDB and import that through the bridging header as that is a more object oriented wrapper of sqlite. Dealing with C pointers and structs will be cumbersome in Swift.
It will check whether the given the table
is Base Table.
SELECT
T.TABLE_NAME AS 'TABLE NAME',
C.COLUMN_NAME AS 'COLUMN NAME'
FROM INFORMATION_SCHEMA.TABLES T
INNER JOIN INFORMATION_SCHEMA.COLUMNS C ON T.TABLE_NAME=C.TABLE_NAME
WHERE T.TABLE_TYPE='BASE TABLE'
AND T.TABLE_NAME LIKE 'Your Table Name'
I have a script in my .bashrc that works under OSX and Linux (bash only !)
function trim_trailing_space() {
if [[ $# -eq 0 ]]; then
echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
echo "Usage :"
echo "$FUNCNAME file"
return
fi
local file=$1
unamestr=$(uname)
if [[ $unamestr == 'Darwin' ]]; then
#specific case for Mac OSX
sed -E -i '' 's/[[:space:]]*$//' $file
else
sed -i 's/[[:space:]]*$//' $file
fi
}
to which I add:
SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"
function find_source_files() {
if [[ $# -eq 0 ]]; then
echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
echo "Usage :"
echo "$FUNCNAME folder"
return
fi
local folder=$1
unamestr=$(uname)
if [[ $unamestr == 'Darwin' ]]; then
#specific case for Mac OSX
find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
else
#Rhahhh, lovely
local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
#echo "extensions_escaped:$extensions_escaped"
find $folder -iregex '.*\.\('$extensions_escaped'\)$'
fi
}
function trim_trailing_space_all_source_files() {
for f in $(find_source_files .); do trim_trailing_space $f;done
}
I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.
ALTER TABLE Customer ADD
CONSTRAINT customer_names__whitespace
CHECK (
Names NOT LIKE ' %'
AND Names NOT LIKE '% '
AND Names NOT LIKE '% %'
);
Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.
It may also be a good time to split those Names into family_name
, first_name
, etc :)
I did a quick performance check on these with perfplot (a project of mine) and found that it's hard to recommend anything else but numpy (note the log scale):
Code to reproduce the plot:
import perfplot
import numpy
def sorted_enumerate(seq):
return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
def sorted_enumerate_key(seq):
return [x for x, y in sorted(enumerate(seq), key=lambda x: x[1])]
def sorted_range(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def numpy_argsort(x):
return numpy.argsort(x)
perfplot.save(
"argsort.png",
setup=lambda n: numpy.random.rand(n),
kernels=[sorted_enumerate, sorted_enumerate_key, sorted_range, numpy_argsort],
n_range=[2 ** k for k in range(15)],
xlabel="len(x)",
)
You are right that this has long since been implemented in .NET Core.
At the time of writing (September 2019), the project.json
file of NuGet 3.x+ has been superseded by PackageReference
(as explained at https://docs.microsoft.com/en-us/nuget/archive/project-json).
To get access to the *Async
methods of the HttpClient
class, your .csproj
file must be correctly configured.
Open your .csproj
file in a plain text editor, and make sure the first line is
<Project Sdk="Microsoft.NET.Sdk.Web">
(as pointed out at https://docs.microsoft.com/en-us/dotnet/core/tools/project-json-to-csproj#the-csproj-format).
To get access to the *Async
methods of the HttpClient
class, you also need to have the correct package reference in your .csproj
file, like so:
<ItemGroup>
<!-- ... -->
<PackageReference Include="Microsoft.AspNetCore.App" />
<!-- ... -->
</ItemGroup>
(See https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference. Also: We recommend applications targeting ASP.NET Core 2.1 and later use the Microsoft.AspNetCore.App metapackage, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/metapackage)
Methods such as PostAsJsonAsync
, ReadAsAsync
, PutAsJsonAsync
and DeleteAsync
should now work out of the box. (No using directive needed.)
Update: The PackageReference tag is no longer needed in .NET Core 3.0.
Bah, this is better! http://sourceforge.net/projects/pwdtknet/ and it is better because ..... it performs Key Stretching AND uses HMACSHA512 :)
You should probably check for errors in /var/log/nginx/error.log
.
In my case I did no add the port for ipv6. You should also do this (in case you are running nginx on a port other than 80):
listen [::]:8000 default_server ipv6only=on;
This will also work and you don't need the extra class:
#navigation li li {}
If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:
#navigation li li li {}
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Late reply but for.databse-date-type the following line works.
SELECT to_date(t.given_date,'DD/MM/RRRR') response_date FROM Table T
given_date's column type is Date
https://github.com/jacoco/jacoco/issues/34
These are the different notations for classes we have:
Agent Parameters, Ant tasks and Maven prepare-agent goal
These specifications allow wildcards * and ?, where * wildcards any number of characters, even multiple nested folders.
Maven report goal
These specs allow Ant Filespec like wildcards *, ** and ?, where * wildcards parts of a single path element only.
Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!
For Leaflet, I'm using
map.setView(markersLayer.getBounds().getCenter());
I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.
If you don't have to do any group functions (sum, average etc in case you want to add numeric data to the table), use SELECT DISTINCT. I suspect it's faster, but i have nothing to show for it.
In any case, if you're worried about speed, create an index on the column.
See the Java Persistence book: Identity and Sequencing
The relevant part for your question is the No Primary Key section:
Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA
Id
does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.
If your object does not have an id, but its' table does, this is fine. Make the object an
Embeddable
object, embeddable objects do not have ids. You will need aEntity
that contains thisEmbeddable
to persist and query it.
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Europe/Istanbul'
for UTC+02:00
I modified rushidesai1's answer to include a working example.
import java.io.*;
import java.util.*;
public class JsonMarshaller<T> {
private static ClassLoader loader = JsonMarshaller.class.getClassLoader();
public static void main(String[] args) {
try {
JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
String jsonString = read(loader.getResourceAsStream("data.json"));
List<Station> stations = marshaller.unmarshal(jsonString);
stations.forEach(System.out::println);
System.out.println(marshaller.marshal(stations));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("resource")
public static String read(InputStream ios) {
return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
}
}
Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]
import java.io.*;
import java.util.List;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class JsonMarshallerUnmarshaller<T> {
private ObjectMapper mapper;
private Class<T> targetClass;
public JsonMarshallerUnmarshaller(Class<T> targetClass) {
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(introspector);
mapper.getSerializationConfig().with(introspector);
this.targetClass = targetClass;
}
public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
return parseList(jsonString, mapper, targetClass);
}
public String marshal(List<T> list) throws JsonProcessingException {
return mapper.writeValueAsString(list);
}
public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(str, listType(mapper, clazz));
}
public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(is, listType(mapper, clazz));
}
public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
}
}
public class Station {
private long id;
private String title;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
}
}
[{
"id": 123,
"title": "my title",
"name": "my name"
}, {
"id": 456,
"title": "my title 2",
"name": "my name 2"
}]
To change vector image color you can directly use android:tint="@color/colorAccent"
<ImageView
android:id="@+id/ivVectorImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_account_circle_black_24dp"
android:tint="@color/colorAccent" />
To change color programatically
ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));
Regarding your question,
It is the same both 'on' or 'where' on an inner join as long as your server can get it:
select * from a inner join b on a.c = b.c
and
select * from a inner join b where a.c = b.c
The 'where' option not all interpreters know so maybe should be avoided. And of course the 'on' clause is clearer.
In your example, you prepended your source string with AccountKey=
but not your target string.
$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
By not including that in the target string, the resulting string will remove AccountKey=
instead of replacing it. You correctly do this with the AccountName=
example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.
herein lies the answer... IIS Settings
IIS-->Default SMTP Virtual Server-->Properties-->Access-->Relay restrictions just add or exclude the IPs you care about, should resolve the issue.
function("MyString");
is similar to
char *s = "MyString";
function(s);
"MyString"
is in both cases a string literal and in both cases the string is unmodifiable.
function("MyString");
passes the address of a string literal to function
as an argument.
Using grid?
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: black;
}
body {
display: grid;
grid-template-rows: auto;
justify-items: center;
align-items: center;
}
canvas {
height: 80vh;
width: 80vw;
display: block;
}
_x000D_
<html>
<body>
<canvas></canvas>
</body>
</html>
_x000D_
From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
occurred because dispatch_group_t
was released while it was still locking (waiting for dispatch_group_leave
).
According to what you found, this was what happened :
dispatch_group_t group
was created. group
's retain count = 1.-[self webservice:onCompletion:]
captured the group
. group
's retain count = 2.dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... });
captured the group
again. group
's retain count = 3.group
was released. group
's retain count = 2.dispatch_group_leave
was never called.dispatch_group_wait
was timeout. The dispatch_async
block was completed. group
was released. group
's retain count = 1.-[self webservice:onCompletion:]
was called again, the old onCompletion
block was replaced with the new one. So, the old group
was released. group
's retain count = 0. group
was deallocated. That resulted to EXC_BAD_INSTRUCTION
.To fix this, I suggest you should find out why -[self webservice:onCompletion:]
didn't call onCompletion
block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.
In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group
for you :
DISPATCH_TIME_FOREVER
or a reasonable amount of time that all -[self webservice:onCompletion]
should call their onCompletion
blocks by the time. So that the block in dispatch_async(...)
will hold it for you.group
into a collection, such as NSMutableArray
.I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t
or dispatch_semaphore_t
.
I've had some troubles with anchor tags and preventDefault
in the past and I always forget what I'm doing wrong, so here's what I figured out.
The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault()
:
function (e, { href }) {
e.preventDefault();
// Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>
It seems the destructuring causes an error (Cannot read property 'href' of undefined
) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault
doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.
I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:
function (e) {
e.preventDefault();
const { href } = e.target;
// Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>
I hope this helps other people like me puzzled by not shown errors!
I had problem with encoding cyrillic letters to URF-8.
I modified one of the above scripts to match cyrillic char map. Implmented is the cyrrilic section of
https://en.wikipedia.org/wiki/UTF-8 and http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
Other sections development is sample and need verification with real data and calculate the char map offsets
Here is the script:
Public Function UTF8Encode( _
StringToEncode As String, _
Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String
Dim TempAns As String
Dim TempChr As Long
Dim CurChr As Long
Dim Offset As Long
Dim TempHex As String
Dim CharToEncode As Long
Dim TempAnsShort As String
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))
' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows
Select Case CharToEncode
' 7 U+0000 U+007F 1 0xxxxxxx
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case 0 To &H7F
TempAns = TempAns + "%" + Hex(CharToEncode And &H7F)
Case &H80 To &H7FF
' 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx
' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps
' offset 192 = &HC0 = 1100 0000 b added to start of UTF-8 cyrillic char map at &H410
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H1F) Or &HC0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
'' debug and development version
'' CharToEncode = CharToEncode - 192 + &H410
'' TempChr = (CharToEncode And &H3F) Or &H80
'' TempHex = Hex(TempChr)
'' TempAnsShort = "%" & Right("0" & TempHex, 2)
'' TempChr = ((CharToEncode And &H7C0) / &H40) Or &HC0
'' TempChr = ((CharToEncode \ &H40) And &H1F) Or &HC0
'' TempHex = Hex(TempChr)
'' TempAnsShort = "%" & Right("0" & TempHex, 2) & TempAnsShort
'' TempAns = TempAns + TempAnsShort
Case &H800 To &HFFFF
' 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
' not tested . Doesnot match Case condition... very strange
MsgBox ("Char to encode matched U+0800 U+FFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
'' CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &HF) Or &HE0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H10000 To &H1FFFFF
' 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched &H10000 &H1FFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H7) Or &HF0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H200000 To &H3FFFFFF
' 26 U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched U+200000 U+3FFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3) Or &HF8), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H4000000 To &H7FFFFFFF
' 31 U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched U+4000000 U+7FFFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000000) And &H1) Or &HFC), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case Else
' somethig else
' to be developped
MsgBox ("Char to encode not matched: " & CharToEncode & " = &H" & Hex(CharToEncode))
End Select
CurChr = CurChr + 1
Loop
UTF8Encode = TempAns
End Function
Good luck!
on mac terminal (at least in ZSH): open stackoverflow.com
(opens site in new tab in your chrome default browser)
I can't find a way to create a table with icons in SO, so I am uploading 2 images.
select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));
If you want to just restart your container:
docker-compose restart servicename
Think of this command as "just restart the container by its name", which is equivalent to docker restart
command.
If you changed ENV variables they won't updated in container. You need to stop it and start again. Or, using single command docker-compose up
will detect changes and recreate container.
As many others mentioned, if you changed docker-compose.yml
file itself, simple restart won't apply those changes.
If you copy your code inside container at the build stage (in Dockerfile
using ADD
or COPY
commands), every time the code changes you have to rebuild the container (docker-compose build
).
docker-compose restart
should work perfectly fine, if your code gets path mapped into the container by volume directive in docker-compose.yml
like so:
services:
servicename:
volumes:
- .:/code
But I'd recommend to use live code reloading, which is probably provided by your framework of choice in DEBUG mode (alternatively, you can search for auto-reload packages in your language of choice). Adding this should eliminate the need to restart container every time after your code changes, instead reloading the process inside.
This Worked for me
There are 2 options
in github - HTTPS/SSH
I had selected SSH
by mistake due to which the error was occuring -_-
Switch it to HTTPS and then copy the url again and try :)
You can use array_column for that.
$search_value = '5465';
$search_key = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));
print_r($userdb[$user]);
5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.
I'd probably use all.equal
and which
to get the information you want. It's not recommended to use all.equal
in an if...else
block for some reason, so we wrap it in isTRUE()
. See ?all.equal
for more:
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ",")
stop("error the A and B does not match at the following columns: ", mismatches )
} else {
message("Yahtzee!")
}
}
And in use:
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
Here is my preferred quickest and easiest solution. Works well if all slides have the same background color that you want to remove.
Step 1. In Powerpoint, "Save As" (shortcut F12) PNG, "All Slides".
Now you have a folder full of these PNG images of all your slides. The problem is that they still have a background. So now:
Step 2. Batch remove background color of all the PNG images, for example by following the steps in this SE answer.
You can use exceptional handling as str.digit
will only work for integers and can fail for something like this too:
>>> str.isdigit(' 1')
False
Using a generator function:
def solve(lis):
for x in lis:
try:
yield float(x)
except ValueError:
pass
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6] #returns converted values
or may be you wanted this:
def solve(lis):
for x in lis:
try:
float(x)
return True
except:
return False
...
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']
or using ast.literal_eval
, this will work for all types of numbers:
>>> from ast import literal_eval
>>> def solve(lis):
for x in lis:
try:
literal_eval(x)
return True
except ValueError:
return False
...
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6', '1+0j']
<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
class FeatureTest {
companion object {
private lateinit var heavyFeature: HeavyFeature
@BeforeClass
@JvmStatic
fun beforeHeavy() {
heavyFeature = HeavyFeature()
}
}
private lateinit var feature: Feature
@Before
fun before() {
feature = Feature()
}
@Test
fun testCool() {
Assert.assertTrue(heavyFeature.cool())
Assert.assertTrue(feature.cool())
}
@Test
fun testWow() {
Assert.assertTrue(heavyFeature.wow())
Assert.assertTrue(feature.wow())
}
}
Same as
import org.junit.Assert
import org.junit.Test
class FeatureTest {
companion object {
private val heavyFeature = HeavyFeature()
}
private val feature = Feature()
@Test
fun testCool() {
Assert.assertTrue(heavyFeature.cool())
Assert.assertTrue(feature.cool())
}
@Test
fun testWow() {
Assert.assertTrue(heavyFeature.wow())
Assert.assertTrue(feature.wow())
}
}
Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:
public void doSomething(Collection someStuff) {
...
}
than this:
public void doSomething(Vector someStuff) {
...
}
If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.
The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.
If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.
This example will help you to handle various types while creating insert statements
select
'insert into doc(Id, CDate, Str, Code, Price, Tag )' +
'values(' +
'''' + convert(nvarchar(50), Id) + ''',' -- uniqueidentifier
+ '''' + LEFT(CONVERT(VARCHAR, CDate, 120), 10) + ''',' -- date
+ '''' + Str+ ''',' -- string
+ '''' + convert(nvarchar(50), Code) + ''',' -- int
+ convert(nvarchar(50), Price) + ',' -- decimal
+ '''' + ISNULL(Tag, '''''') + '''' + ')' -- nullable string
from doc
where CDate> '2019-01-01 00:00:00.000'
Here's a good resource for wrapping columned lists. http://www.communitymx.com/content/article.cfm?cid=27f87
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
Description of the possible values:
left
: No floating elements allowed on the left sideright
: No floating elements allowed on the right sideboth
: No floating elements allowed on either the left or the right sidenone
: Default. Allows floating elements on both sidesinherit
: Specifies that the value of the clear property should be inherited from the parent element
Source: w3schools.com
This is because you have the following code:
class JSONDeserializer
{
Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};
This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).
class JSONDeserializer
{
Value ParseValue(TDR type, const json_string& valueString);
};
The error come from the fact that JSONDeserializer::ParseValue
is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.
I have updated Ronnie's version after spending way too much time trying to enter a password only to find out that I had my CAPS LOCK on!
With this version what ever the message is in _CapsLockMessage
will "float" at the end of the typing area and will be displayed in red.
This version takes a bit more code and does require a polling loop. On my computer CPU usage about 3% to 4%, but one could always add a small Sleep() value to decrease CPU usage if needed.
private const string _CapsLockMessage = " CAPS LOCK";
/// <summary>
/// Like System.Console.ReadLine(), only with a mask.
/// </summary>
/// <param name="mask">a <c>char</c> representing your choice of console mask</param>
/// <returns>the string the user typed in</returns>
public static string ReadLineMasked(char mask = '*')
{
// Taken from http://stackoverflow.com/a/19770778/486660
var consoleLine = new StringBuilder();
ConsoleKeyInfo keyInfo;
bool isDone;
bool isAlreadyLocked;
bool isCapsLockOn;
int cursorLeft;
int cursorTop;
ConsoleColor originalForegroundColor;
isDone = false;
isAlreadyLocked = Console.CapsLock;
while (isDone == false)
{
isCapsLockOn = Console.CapsLock;
if (isCapsLockOn != isAlreadyLocked)
{
if (isCapsLockOn)
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
originalForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("{0}", _CapsLockMessage);
Console.SetCursorPosition(cursorLeft, cursorTop);
Console.ForegroundColor = originalForegroundColor;
}
else
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
Console.Write("{0}", string.Empty.PadRight(_CapsLockMessage.Length));
Console.SetCursorPosition(cursorLeft, cursorTop);
}
isAlreadyLocked = isCapsLockOn;
}
if (Console.KeyAvailable)
{
keyInfo = Console.ReadKey(intercept: true);
if (keyInfo.Key == ConsoleKey.Enter)
{
isDone = true;
continue;
}
if (!char.IsControl(keyInfo.KeyChar))
{
consoleLine.Append(keyInfo.KeyChar);
Console.Write(mask);
}
else if (keyInfo.Key == ConsoleKey.Backspace && consoleLine.Length > 0)
{
consoleLine.Remove(consoleLine.Length - 1, 1);
if (Console.CursorLeft == 0)
{
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
}
else
{
Console.Write("\b \b");
}
}
if (isCapsLockOn)
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
originalForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("{0}", _CapsLockMessage);
Console.CursorLeft = cursorLeft;
Console.CursorTop = cursorTop;
Console.ForegroundColor = originalForegroundColor;
}
}
}
Console.WriteLine();
return consoleLine.ToString();
}
This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.
If you add / before /n, it should work, you need to escape new line character.
"Hello there //n start coding"
The result should be as following
Hello there
start coding
If you're using bash >=4.0 (or zsh)
rm **/*.pyc
Note that */*.pyc
selects all .pyc
files in the immediate first-level subdirectories while **/*.pyc
recursively scans the whole directory tree. As an example, foo/bar/qux.pyc
will be deleted by rm **/*.pyc
but not by */*.pyc
.
The globstar shell options must be enabled. To enable globstar
:
shopt -s globstar
and to check its status:
shopt globstar
If you want to scan to the end of the string (stripping out a newline if there), just use:
char *x = "19 cool kid";
sscanf (x, "%d %[^\n]", &age, buffer);
That's because %s
only matches non-whitespace characters and will stop on the first whitespace it finds. The %[^\n]
format specifier will match every character that's not (because of ^
) in the selection given (which is a newline). In other words, it will match any other character.
Keep in mind that you should have allocated enough space in your buffer to take the string since you cannot be sure how much will be read (a good reason to stay away from scanf/fscanf
unless you use specific field widths).
You could do that with:
char *x = "19 cool kid";
char *buffer = malloc (strlen (x) + 1);
sscanf (x, "%d %[^\n]", &age, buffer);
(you don't need * sizeof(char)
since that's always 1 by definition).
Basically, you iterate over files under the given path, subtract the CreationTime
of each file found from the current time, and compare against the Days
property of the result. The -WhatIf
switch will tell you what will happen without actually deleting the files (which files will be deleted), remove the switch to actually delete the files:
$old = 15
$now = Get-Date
Get-ChildItem $path -Recurse |
Where-Object {-not $_.PSIsContainer -and $now.Subtract($_.CreationTime).Days -gt $old } |
Remove-Item -WhatIf
You can also use the new Java 8 API
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowTest{
public static void main(String args[]){
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
}
}
The DateTimeFormatter
class replaces the old SimpleDateFormat
. You can then create a ZonedDateTime
from which you can extract the desired epoch time.
The main advantage is that you are now thread safe.
Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
If you don't want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId
How to tell on Ubuntu if apache2 is running:
sudo service apache2 status
/etc/init.d/apache2 status
ps aux | grep apache
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
Hopefully this would get you started
See it live on http://ideone.com/l23He (using stdin)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ";");
tok && *tok;
tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %s\n", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}
Output:
Field 3 would be nazwisko
Field 3 would be Kowalski
Field 3 would be Nowak
Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.
@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {
@ApiObjectField(description = "The code which is to be verified.")
@NotBlank(message = "mandatory")
private final String code;
@ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
private final String maskedMobileNumber;
public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
public String getcode() {
return code;
}
public String getMaskedMobileNumber() {
return maskedMobileNumber;
}
}
The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been
public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH
but it still didn't go.
I checked with python -version
and go to know that it was still taking the anaconda path.
I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH
.
Issue Solved!
Very simple:
python.exe
(provided you have given path of it in environmental variables)Then, In the same command prompt window the python interpreter will start with >>>
This worked for me.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
function dragStart(event) {_x000D_
event.dataTransfer.setData("Text", event.target.id);_x000D_
}_x000D_
_x000D_
function allowDrop(event) {_x000D_
event.preventDefault();_x000D_
}_x000D_
_x000D_
function drop(event) {_x000D_
$("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td> Bhanu Pratap </td><td> India </td><td> 3 years </td><td> Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
}
_x000D_
.droptarget {_x000D_
float: left;_x000D_
min-height: 100px;_x000D_
min-width: 200px;_x000D_
border: 1px solid black;_x000D_
margin: 15px;_x000D_
padding: 10px;_x000D_
border: 1px solid #aaaaaa;_x000D_
}_x000D_
_x000D_
[contentEditable=true]:empty:not(:focus):before {_x000D_
content: attr(data-text);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
<p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
</div>_x000D_
_x000D_
<div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
Thanks... :)
create a full-width View
with alignItems: "center"
then insert desired children inside.
import React from "react";
import {View} from "react-native";
export default class AbsoluteComponent extends React.Component {
render(){
return(
<View style={{position: "absolute", left: 0, right: 0, alignItems: "center"}}>
{this.props.children}
</View>
)
}
}
you can add properties like bottom: 30
for bottom aligned component.
$('#tblNewAttendees tbody tr).each((index, tr)=> {
//console.log(tr);
$(tr).children('td').each ((index, td) => {
console.log(td);
});
});
You can use this tr and td parameter also.
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="isiPad" value="value"/>
<c:choose>
<!-- if condition -->
<c:when test="${...}">Html Code</c:when>
<!-- else condition -->
<c:otherwise>Html code</c:otherwise>
</c:choose>
Just another idea since I am binding to a winforms combobox:
public enum DateRange {
[Display(Name = "None")]
None = 0,
[Display(Name = "Today")]
Today = 1,
[Display(Name = "Tomorrow")]
Tomorrow = 2,
[Display(Name = "Yesterday")]
Yesterday = 3,
[Display(Name = "Last 7 Days")]
LastSeven = 4,
[Display(Name = "Custom")]
Custom = 99
};
int something = (int)DateRange.None;
To get the int value from the display name from:
public static class EnumHelper<T>
{
public static T GetValueFromName(string name)
{
var type = typeof(T);
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DisplayAttribute)) as DisplayAttribute;
if (attribute != null)
{
if (attribute.Name == name)
{
return (T)field.GetValue(null);
}
}
else
{
if (field.Name == name)
return (T)field.GetValue(null);
}
}
throw new ArgumentOutOfRangeException("name");
}
}
usage:
var z = (int)EnumHelper<DateRange>.GetValueFromName("Last 7 Days");
Expanding on @goodside's repsonse:
In some cases you may want to pad a string with zeros (e.g. fips codes or other numeric-like factors). In OSX/Linux:
> sprintf("%05s", "104")
[1] "00104"
But because sprintf()
calls the OS's C sprintf()
command, discussed here, in Windows 7 you get a different result:
> sprintf("%05s", "104")
[1] " 104"
So on Windows machines the work around is:
> sprintf("%05d", as.numeric("104"))
[1] "00104"
This is not my prefered way to do this, cause of massive CPU consumption.
If that is actually your working code, then just keep it like that. Checking a boolean once a second causes NO measurable CPU load. None whatsoever.
The real problem is that the thread that checks the value may not see a change that has happened for an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.
private volatile boolean value;
Note that putting the access in a synchronized
block, such as when using the notification-based solution described in other answers, will have the same effect.
Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*
this is my approach about this. however I believe that the best solution is the answer from the user username tbd
var i = 0
var sum = 0
let example = 0
for elements in multiples{
i = i + 1
sum = multiples[ (i- 1)]
example = sum + example
}
Quick 'n dirty, regex-free, low-robustness chop-chop technique
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
mvn install primary jobs are to 1)Download The Dependencies and 2)Build The Project
while job 1 is nowadays taken care by IDs like intellij (they download for any dependency at POM)
mvn install is majorly now used for job 2.
I was trying to do something similar to this but instead remove the column from an embedded document. It took me a while to find a solution and this was the first post I came across so I thought I would post this here for anyone else trying to do the same.
So lets say instead your data looks like this:
{
name: 'book',
tags: [
{
words: ['abc','123'],
lat: 33,
long: 22
}, {
words: ['def','456'],
lat: 44,
long: 33
}
]
}
To remove the column words
from the embedded document, do this:
db.example.update(
{'tags': {'$exists': true}},
{ $unset: {'tags.$[].words': 1}},
{multi: true}
)
or using the updateMany
db.example.updateMany(
{'tags': {'$exists': true}},
{ $unset: {'tags.$[].words': 1}}
)
The $unset
will only edit it if the value exists but it will not do a safe navigation (it wont check if tags
exists first) so the exists is needed on the embedded document.
This uses the all positional operator ($[]
) which was introduced in version 3.6
Just coming from another question. I'd like to mention Pintos... I remembered my OS course with Nachos and Pintos seems to be the same kind of thing that can run on x86.
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class define
demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
Take a look at Jacksons built-in tree model feature.
And your code will be:
public void parse(String json) {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
you can use np.int_
:
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> np.int_(x)
array([[1, 2],
[1, 2]])
Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.
You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.
Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.
Git version 2.9.2
If you want to change the name of the local branch you are on:
git branch -m new_name
If you want to change the name of a different branch:
git branch -m old_name new_name
If you want to change the name of a different branch to a name that already exists:
git branch -M old_name new_name_that_already_exists
Note: The last command is destructive and will rename your branch, but you will lose the old branch with that name and those commits because branch names must be unique.
Ctrl + F11 and Ctrl + F12 both work.
For jQuery mobile, I had to do:
$('#id_of_textbox').live("keyup", function(event) {
if(event.keyCode == '13'){
$('#id_of_button').click();
}
});
Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass ViewBag
values in the class constructor.
Or if it's not a class, your only other alternative, is to use data
attributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.
Assuming you had this input:
<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />
Then in your JS file you could get it by using:
var myVal = $("#myInput").data("myValue");
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
select * from Header where userID like '%''%'
Hope this helps.
/usr/local/lib/node_modules
is the correct directory for globally installed node modules.
/usr/local/share/npm/lib/node_modules
makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:
/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules
The latter seems to be node modules that came with Node, e.g., lodash
, when the former is Node modules that I installed using npm
.
Third or nth maximum salary from salary table without using subquery
select salary from salary
ORDER BY salary DESC
OFFSET N-1 ROWS
FETCH NEXT 1 ROWS ONLY
For 3rd highest salary put 2 in place of N-1
@id/
and @android:id/
is not the same.
@id/
referencing ID in your application, @android:id/
referencing an item in Android platform.
Eclipse is wrong.
Try:
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id+" and "+$(event.target).attr('class'));
});
});
What really helped me here is spiv's tip (which I would vote up and comment on if I had the reputation points) for getting a stack trace out of an unprepared Python process. Except it didn't work until I modified the gdbinit script. So:
download http://svn.python.org/projects/python/trunk/Misc/gdbinit and put it in ~/.gdbinit
edit it, changing [edit: no longer needed; the linked file already has this change as of 2010-01-14]PyEval_EvalFrame
to PyEval_EvalFrameEx
Attach gdb: gdb -p PID
Get the python stack trace: pystack
Here is some other ways to scroll to bottom
fun ScrollView.scrollToBottom() {
// use this for scroll immediately
scrollTo(0, this.getChildAt(0).height)
// or this for smooth scroll
//smoothScrollBy(0, this.getChildAt(0).height)
// or this for **very** smooth scroll
//ObjectAnimator.ofInt(this, "scrollY", this.getChildAt(0).height).setDuration(2000).start()
}
Using
If you scrollview already laid out
my_scroll_view.scrollToBottom()
If your scrollview is not finish laid out (eg: you scroll to bottom in Activity onCreate
method ...)
my_scroll_view.post {
my_scroll_view.scrollToBottom()
}
I had similar problem, and I solved it as folows:
I working on MS SQL 2008, but in the NH configuration I had bad dialect: NHibernate.Dialect.MsSql2005Dialect if I correct it to: NHibernate.Dialect.MsSql2008Dialect then everything's working fine without a exception "No persister for: ..." David.
Version 2.6 and above:
PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> General -> Appearance -> Show line numbers checkbox
Version 2.5 and below:
Settings -> Editor -> General -> Appearance -> Show line numbers checkbox
Use aggregation function and $project
to get specific object field in document
db.getCollection('geolocations').aggregate([ { $project : { geolocation : 1} } ])
result:
{
"_id" : ObjectId("5e3ee15968879c0d5942464b"),
"geolocation" : [
{
"_id" : ObjectId("5e3ee3ee68879c0d5942465e"),
"latitude" : 12.9718313,
"longitude" : 77.593551,
"country" : "India",
"city" : "Chennai",
"zipcode" : "560001",
"streetName" : "Sidney Road",
"countryCode" : "in",
"ip" : "116.75.115.248",
"date" : ISODate("2020-02-08T16:38:06.584Z")
}
]
}
Select count(1) From V$session
where status='ACTIVE'
/
I had the same error in a demo app that was concerned with security and login state. None of the other solutions helped, but simply opening a new anonymous browser window did the trick.
Basically, there were cookies and tokens left from a previous version of the app which put AngularJS in a state that it was never supposed to reach. Hence the areq
assertions failed.
You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:
select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;
which will return "12345569".
also you can use this one:
select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual
which will return "12345569" for numbers and "StackOverFlow" for characters.
For info, in your .bowerrc
file you can add a no-proxy attribute. I don't know since when it is supported but it works on bower 1.7.4
.bowerrc :
{
"directory": "bower_components",
"proxy": "http://yourProxy:yourPort",
"https-proxy":"http://yourProxy:yourPort",
"no-proxy":"myserver.mydomain.com"
}
.bowerrc
should be located in the root folder of your Javascript project, the folder in which you launch the bower command. You can also have it in your home folder (~/.bowerrc
).
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.
@font-face {
font-family: 'glyphicons-halflings-regular';
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}
You can do this with transition events, so you build two CSS classes for the transition, one holding the animation other, holding the display none state. And you switch them after the animation is ended? In my case I can display the divs again if I press a button, and remove both classes.
Try the snippet below...
$(document).ready(function() {_x000D_
// Assign transition event_x000D_
$("table").on("animationend webkitAnimationEnd", ".visibility_switch_off", function(event) {_x000D_
// We check if this is the same animation we want_x000D_
if (event.originalEvent.animationName == "col_hide_anim") {_x000D_
// After the animation we assign this new class that basically hides the elements._x000D_
$(this).addClass("animation-helper-display-none");_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
$("button").click(function(event) {_x000D_
_x000D_
$("table tr .hide-col").toggleClass(function() {_x000D_
// We switch the animation class in a toggle fashion..._x000D_
// and we know in that after the animation end, there_x000D_
// is will the animation-helper-display-none extra_x000D_
// class, that we nee to remove, when we want to_x000D_
// show the elements again, depending on the toggle_x000D_
// state, so we create a relation between them._x000D_
if ($(this).is(".animation-helper-display-none")) {_x000D_
// I'm toggling and there is already the above class, then_x000D_
// what we want it to show the elements , so we remove_x000D_
// both classes..._x000D_
return "visibility_switch_off animation-helper-display-none";_x000D_
}_x000D_
else {_x000D_
// Here we just want to hide the elements, so we just_x000D_
// add the animation class, the other will be added_x000D_
// later be the animationend event..._x000D_
return "visibility_switch_off";_x000D_
}_x000D_
});_x000D_
});_x000D_
});
_x000D_
table th {_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
table td {_x000D_
background-color: white;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
.animation-helper-display-none {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
table tr .visibility_switch_off {_x000D_
animation-fill-mode: forwards;_x000D_
animation-name: col_hide_anim;_x000D_
animation-duration: 1s;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes col_hide_anim {_x000D_
0% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}_x000D_
_x000D_
@-moz-keyframes col_hide_anim {_x000D_
0% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}_x000D_
_x000D_
@-o-keyframes col_hide_anim {_x000D_
0% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}_x000D_
_x000D_
@keyframes col_hide_anim {_x000D_
0% {opacity: 1;}_x000D_
100% {opacity: 0;}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<theader>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th class='hide-col'>Age</th>_x000D_
<th>Country</th>_x000D_
</tr>_x000D_
</theader>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Name</td>_x000D_
<td class='hide-col'>Age</td>_x000D_
<td>Country</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<button>Switch - Hide Age column with fadeout animation and display none after</button>
_x000D_
I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days.
I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane.
However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for.
switch(position) {
case 0:
setContentView(R.layout.xml0);
break;
case 1:
setContentView(R.layout.xml1);
break;
default:
setContentView(R.layout.default);
break;
}
i hope this will do the job!
You should use container-fluid
, not container
. See example: http://www.bootply.com/onAFpJcslS
Well, OpenSSL should do it handily from a #12 file:
openssl pkcs12 -in pkcs-12-certificate-file -out pem-certificate-file
openssl pkcs12 -in pkcs-12-certificate-and-key-file -out pem-certificate-and-key-file
Maybe more details on what the error/failure is?
You may use TypeToken to load the json string into a custom object.
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
Documentation:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for
List<String>
, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as
Class<?>
orList<? extends CharSequence>
.
Kotlin:
If you need to do it in Kotlin you can do it like this:
val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)
Or you can see this answer for various alternatives.
The following vim plugin handles that automatically through its "Bracketed Paste" mode: https://github.com/wincent/terminus
Sets up "Bracketed Paste" mode, which means you can forget about manually setting the 'paste' option and simply go ahead and paste in any mode.
dynamic MyDynamic = new ExpandoObject();
You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *
, and to access a field, you use .
, so you can use:
cout << (*kwadrat).val1;
Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:
cout << kwadrat->val1;
These are defined to be identical. As you can see, the ->
basically just combines a *
and a .
into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the .
without dereferencing a pointer first:
Kwadrat kwadrat2(2,3,4);
cout << kwadrat2.val1;
The ::
is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:
struct something {
static int x; // this only declares `something::x`. Often found in a header
};
int something::x; // this defines `something::x`. Usually in .cpp/.cc/.C file.
In this case, since x
is static
, it's not associated with any particular instance of something
. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:
something::x = 10;
std::cout << something::x;
Note, however, that it's also permitted to access a static member as if it was a member of a particular object:
something s;
s.x = 1;
At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.
I think this is caused by force-quitting your app on the iPhone prior to pressing the stop button in Xcode. Sometimes when you press the stop button in Xcode, then it takes extra time to quit the app if it hung. But just be patient, it will eventually quit most of the time.
If you are using HTML5 forms, you can use attribute min="0"
for form element <input type="number" />
. This is supported by all major browsers. It does not involve Javascript for such simple tasks, but is integrated in new html standard.
It is documented on https://www.w3schools.com/tags/att_input_min.asp
There is a way to do this. Using the ActionChains API you can move the mouse over a containing element, adjust by some offset (relative to the middle of that element) to put the "cursor" over the desired button (or other element), and then click at that location. Here's how to do it using webdriver in Python:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
elem = browser.find_element_by_selector(".some > selector")
ac = ActionChains(browser)
ac.move_to_element(elem).move_by_offset(x_offset, y_offset).click().perform()
Y'all are much to quick to dismiss the question. There are a number of reasons one might to need to click at a specific location, rather than on an element. In my case I have an SVG bar chart with an overlay element that catches all the clicks. I want to simulate a click over one of the bars, but since the overlay is there Selenium can't click on the element itself. This technique would also be valuable for imagemaps.
You can use $(window).resize() to detect if the viewport is resized.
jQuery does not have any function to consistently detect the correctly width and height of the viewport[1] when there is a scroll bar present.
I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for javascript.
Here is my solution:
// A function for detecting the viewport minimum width.
// You could use a similar function for minimum height if you wish.
var min_width;
if (Modernizr.mq('(min-width: 0px)')) {
// Browsers that support media queries
min_width = function (width) {
return Modernizr.mq('(min-width: ' + width + ')');
};
}
else {
// Fallback for browsers that does not support media queries
min_width = function (width) {
return $(window).width() >= width;
};
}
var resize = function() {
if (min_width('768px')) {
// Do some magic
}
};
$(window).resize(resize);
resize();
My answer will probably not help resizing a iframe to 100% viewport width with a margin on each side, but I hope it will provide solace for webdevelopers frustrated with browser incoherence of javascript viewport width and height calculation.
Maybe this could help with regards to the iframe:
$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');
[1] You can use $(window).width() and $(window).height() to get a number which will be correct in some browsers, but incorrect in others. In those browsers you can try to use window.innerWidth and window.innerHeight to get the correct width and height, but i would advice against this method because it would rely on user agent sniffing.
Usually the different browsers are inconsistent about whether or not they include the scrollbar as part of the window width and height.
Note: Both $(window).width() and window.innerWidth vary between operating systems using the same browser. See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238
I wonder if this question has been answered well: how css margins work and why is it that margin-top:-5; is not the same as margin-bottom:5;?
Margin is distance from the surroundings of the element. margin-top says "... distance from surroundings as we measure from top 'side' of the element's 'box' and margin-bottom being the distance from the bottom 'side' of the 'box'". Then margin-top:5; is concerned with the top 'side' perimeter,-5 in that case; anything approaching from top 'side' can overlap top 'side' of element by 5, and margin-bottom:5; means distance between element bottom 'side' and surrounding is 5.
Basically that but affected by float'ed elements and the like: http://www.w3.org/TR/CSS2/box.html#margin-properties.
http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/
I stand to be corrected.
Use a ArrayAdapter backed by an ArrayList. To change the data, just update the data in the list and call adapter.notifyDataSetChanged().
Yet another ridiculous case: it somehow happened that two projects in the same solution had the same ProjectId
- one of those was a test project and that confused Test Runner.
Removing and readding test projects to the solution changed the ProjectId
and fixed the issue.
I guess you passed a List or an Array to the Adapter. If you keep the instance of this added collection, you can do a
collection.clear();
listview.getAdapter().notifyDataSetChanged();
this'll work only if you instantiated the adapter with collection and it's the same instance.
Also, depending on the Adapter you extended, you may not be able to do this. SimpleAdapter is used for static data, thus it can't be updated after creation.
PS. not all Adapters have a clear() method. ArrayAdapter does, but ListAdapter or SimpleAdapter don't
If your code cannot be updated on some reason, just change your switch ... continue
to switch ... break
, as in previous versions of PHP it was meant to work this way.
Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:
function compute() {
if ( $('input[name=type]:checked').val() != undefined ) {
var a = parseInt($('input[name=service_price]').val());
var b = parseInt($('input[name=modem_price]').val());
var total = a+b;
$('#total_price').val(a+b);
}
}
and this should work.
Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.
To convert a generic list to data table, you could use the DataTableGenerator
This library lets you convert your list into a data table with multi-feature like
Ubuntu 14.04:
simple cat -e <filename>
works just fine.
This displays Unix line endings (\n
or LF) as $
and Windows line endings (\r\n
or CRLF) as ^M$
.
Call GoogleMap.setMyLocationEnabled(true)
in your Activity
, and add this 2 lines code in the Manifest
:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
If you are using Atlassian SourceTree app, you could use the reset option in the context menu.
Building on the excellent answer above by fir3rpho3nixx and David Schmitt, I have modified their code and added the ShouldInheritOrImplementTypedGenericInterface test (last one).
/// <summary>
/// Find out if a child type implements or inherits from the parent type.
/// The parent type can be an interface or a concrete class, generic or non-generic.
/// </summary>
/// <param name="child"></param>
/// <param name="parent"></param>
/// <returns></returns>
public static bool InheritsOrImplements(this Type child, Type parent)
{
var currentChild = parent.IsGenericTypeDefinition && child.IsGenericType ? child.GetGenericTypeDefinition() : child;
while (currentChild != typeof(object))
{
if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
return true;
currentChild = currentChild.BaseType != null && parent.IsGenericTypeDefinition && currentChild.BaseType.IsGenericType
? currentChild.BaseType.GetGenericTypeDefinition()
: currentChild.BaseType;
if (currentChild == null)
return false;
}
return false;
}
private static bool HasAnyInterfaces(Type parent, Type child)
{
return child.GetInterfaces().Any(childInterface =>
{
var currentInterface = parent.IsGenericTypeDefinition && childInterface.IsGenericType
? childInterface.GetGenericTypeDefinition()
: childInterface;
return currentInterface == parent;
});
}
[Test]
public void ShouldInheritOrImplementNonGenericInterface()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(IFooInterface)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterface()
{
Assert.That(typeof(GenericFooBase)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterfaceByGenericSubclass()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
}
[Test]
public void ShouldNotInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
{
Assert.That(new GenericFooImplementor<string>().GetType()
.InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
}
[Test]
public void ShouldInheritOrImplementNonGenericClass()
{
Assert.That(typeof(FooImplementor)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void ShouldInheritOrImplementAnyBaseType()
{
Assert.That(typeof(GenericFooImplementor<>)
.InheritsOrImplements(typeof(FooBase)), Is.True);
}
[Test]
public void ShouldInheritOrImplementTypedGenericInterface()
{
GenericFooImplementor<int> obj = new GenericFooImplementor<int>();
Type t = obj.GetType();
Assert.IsTrue(t.InheritsOrImplements(typeof(IGenericFooInterface<int>)));
Assert.IsFalse(t.InheritsOrImplements(typeof(IGenericFooInterface<String>)));
}
You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...
Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.
An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.
However, see this question for whether or not you should do that.
mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name
should probably be
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
Since the deprecation of RequestOptions, sending data as body in a DELETE request is not supported.
If you look at the definition of DELETE, it looks like this:
delete<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
You can send payload along with the DELETE request as part of the params in the options object as follows:
this.http.delete('http://testAPI:3000/stuff', { params: {
data: yourData
}).subscribe((data)=>.
{console.log(data)});
However, note that params only accept data as string or string[] so you will not be able to send your own interface data unless you stringify it.
To have 4-space tabs in most files, real 8-wide tab char in Makefiles, and automatic indenting in various files including C/C++, put this in your ~/.vimrc
file:
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Use filetype detection and file-based automatic indenting.
filetype plugin indent on
" Use actual tab chars in Makefiles.
autocmd FileType make set tabstop=8 shiftwidth=8 softtabstop=0 noexpandtab
endif
" For everything else, use a tab width of 4 space chars.
set tabstop=4 " The width of a TAB is set to 4.
" Still it is a \t. It is just that
" Vim will interpret it to be having
" a width of 4.
set shiftwidth=4 " Indents will have a width of 4.
set softtabstop=4 " Sets the number of columns for a TAB.
set expandtab " Expand TABs to spaces.
For me the issue was because of Case sensitivity. I was using ~{fragments/Base}
instead of ~{fragments/base}
(The name of the file was base.html
)
My development environment was windows but the server hosting the application was Linux so I was not seeing this issue during development since windows' paths are not case sensitive.
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.