I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.
You should almost always use a Collator for dictionary based sorting.
For case insensitive collator searching for the English language you do the following:
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);
Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.
You can get the favicon URL from the website's HTML.
Here is the favicon
element:
<link rel="icon" type="image/png" href="/someimage.png" />
You should use a regular expression here. If no tag found, look for favicon.ico
in the site root directory. If nothing found, the site does not have a favicon.
<div ng-hide="myvar == null"></div>
or
<div ng-show="myvar != null"></div>
Slow, ugly, platform-specific... but one-liner ;-)
import subprocess
contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]
I know this question was asked a while ago, but in case useful, the here
package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj
file resides in, so the following will often suffice without having to define the file path to your working directory:
library(here)
if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}
localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3
<%@page import="java.util.Enumeration"%>
<%
Enumeration in = request.getParameterNames();
while(in.hasMoreElements()) {
String paramName = in.nextElement().toString();
out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
}
%>
key = datr
key2 = datr2
key3 = datr3
create an intent and set an action for it while passing the url to the intent
yourbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String theurl = "http://google.com";
Uri urlstr = Uri.parse(theurl);
Intent urlintent = new Intent();
urlintent.setData(urlstr);
urlintent.setAction(Intent.ACTION_VIEW);
startActivity(urlintent);
The scalar formatter supports collecting the exponents. The docs are as follows:
class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter
Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.
your technique would be:
from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3)) # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)
To get the exponent displayed in the format x10^5
, instantiate the ScalarFormatter with useMathText=True
.
You could also use:
xfmt.set_useOffset(10000)
To get a result like this:
Every maven project should stop depending on xerces, they probably don't really. XML APIs and an Impl has been part of Java since 1.4. There is no need to depend on xerces or XML APIs, its like saying you depend on Java or Swing. This is implicit.
If I was boss of a maven repo I'd write a script to recursively remove xerces dependencies and write a read me that says this repo requires Java 1.4.
Anything that actually breaks because it references Xerces directly via org.apache imports needs a code fix to bring it up to Java 1.4 level (and has done since 2002) or solution at JVM level via endorsed libs, not in maven.
To give an extra solution to the above 'This app is incompatible with your...' problem, let me share my solution for a different problem cause. I tried installing an app on a low-end Samsung Galaxy Y (GT-S6350) device and got this error from the Play store. To test various AndroidManifest configurations, I created an account and followed the routine as described in https://stackoverflow.com/a/5449397/372838 until my device showed up in the supported device list.
It turned out that a lot of devices become incompatible when you use the Camera permission:
<uses-permission android:name="android.permission.CAMERA" />
When I removed that specific permission, the application was available for 1180 devices instead of 870. Hope it will help someone
Anwer is here How to dynamically add a style for text-align using jQuery
A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy
and lblEditModifiedOn
- when I was editing a row, so that the correct ModifiedBy and ModifiedOn
would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating
event it showed the new values I entered in the OldValues
list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource
attached to the GridView
.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound
event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
You don't need to use jquery.
var myString = 'abc';
var n = myString.length;
n will be 3.
Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:
static String intToString(int num, int digits) {
assert digits > 0 : "Invalid number of digits";
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
Here's one approach. Using a combination of the answers above do the following:
As a formula, just use the example below with <> replaced with your range reference.
=SUM(IF(ISERROR(DATEVALUE(TEXT(<<RANGE HERE>>, "MM/dd/yyyy"))), 0, 1))
You must enter this as an array formula with CTRL + SHIFT + ENTER.
They tell what size can be stored in a integer variable. To remember the size you can think in terms of :-) 2 beer( 2 bytes) , 4 beer(4 bytes) or 8 beer( 8 bytes).
Int16 :-2 beers/bytes = 16 bit = 2^16 = 65536 = 65536/2 = -32768 to 32767
Int32 :- 4 beers/bytes = 32 bit = 2^32 = 4294967296 = 4294967296/2 = -2147483648 to 2147483647
Int64 :- 8 beer/ bytes = 64 bit = 2^64 = 18446744073709551616 = 18446744073709551616 /2 = -9223372036854775808 to 9223372036854775807
In short you can store more than 32767 value in int16 , more than 2147483647 value in int32 and more than 9223372036854775807 value in int64.
To understand above calculation you can check out this video int16 vs int32 vs int64
As already mentioned if you can use await
. If you need to run the code synchronously like you mention .GetAwaiter().GetResult()
, .Result
or .Wait()
is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;
Syncronously calling an async method
Task.Run(() => asyncMethod()).Wait();
No deadlock issues will occur due to the use of Task.Run
.
Source:
https://stackoverflow.com/a/32429753/3850405
Update:
Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.
Source:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
An example of an associated full GC also shows the collectors used for the old and permanent generations:
3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)]
[ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K)
[PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]
Finally, breaking down one line of your example log output:
8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
With HTML5 you can do
<input type="number">
You can also use a regex pattern to limit the input text.
<input type="text" pattern="^[0-9]*$" />
In the documentaion http://contactform7.com/text-fields/#textarea
[textarea* message id:contact-message 10x2 placeholder "Your Message"]
The above will generate a textarea with cols="10" and rows="2"
<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>
Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.
Installation
npm install --save-dev unminified-webpack-plugin
Usage
var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new UnminifiedWebpackPlugin()
]
};
By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^
This feature already exists in Ubuntu and Debian, in the command-not-found
package.
I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.
In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.
So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.
Edit: I only just noticted the previous reply, after posting. 100% agree.
It also worth noting that Concat works in constant time and in constant memory. For example, the following code
long boundary = 60000000;
for (long i = 0; i < boundary; i++)
{
list1.Add(i);
list2.Add(i);
}
var listConcat = list1.Concat(list2);
var list = listConcat.ToList();
list1.AddRange(list2);
gives the following timing/memory metrics:
After lists filled mem used: 1048730 KB
concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
Transient :
First need to know where it needed how it bridge the gap.
1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.
2) Transient keyword cannot be used along with static keyword.
3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.
Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.
Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.
The expression len(l)
is evaluated only one time, at the moment the range()
builtin is evaluated. The range object constructed at that time does not change; it can't possibly know anything about the object l
.
P.S. l
is a lousy name for a value! It looks like the numeral 1, or the capital letter I.
These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".
Logical operators for boolean indexing in Pandas
It's important to realize that you cannot use any of the Python logical operators (and
, or
or not
) on pandas.Series
or pandas.DataFrame
s (similarly you cannot use them on numpy.array
s with more than one element). The reason why you cannot use those is because they implicitly call bool
on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:
>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.
However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array
, pandas.Series
, pandas.DataFrame
, or any other (conforming) numpy.array
subclass:
and
has np.logical_and
or
has np.logical_or
not
has np.logical_not
numpy.logical_xor
which has no Python equivalent but is a logical "exclusive or" operation So, essentially, one should use (assuming df1
and df2
are pandas DataFrames):
np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)
However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):
np.bitwise_and
or the &
operatornp.bitwise_or
or the |
operatornp.invert
(or the alias np.bitwise_not
) or the ~
operatornp.bitwise_xor
or the ^
operatorTypically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:
(df1 < 10) | (df2 > 10) # instead of the wrong df1 < 10 | df2 > 10
This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10
(where a
and b
are for example simple integers) and don't need the parenthesis.
It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:
>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])
>>> np.logical_and(a1, a2)
array([False, False, False, True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)
And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:
>>> a3 = np.array([1, 2, 3, 4])
>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])
Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
and | np.logical_and | np.bitwise_and | &
-------------------------------------------------------------------------------------
or | np.logical_or | np.bitwise_or | |
-------------------------------------------------------------------------------------
| np.logical_xor | np.bitwise_xor | ^
-------------------------------------------------------------------------------------
not | np.logical_not | np.invert | ~
Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise.
However be careful with the bitwise invert on plain Python bool
s because the bool will be interpreted as integers in this context (for example ~False
returns -1
and ~True
returns -2
).
For those situations where width of the items you do want to flex-end
is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start
with flex:1
This will cause the pseudo flex-start
item to fill the container, just format it to text-align:left
or whatever.
git checkout master -- myplugin.js
master = branch name
myplugin.js = file name
instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0;
once your window has scrolled pass a certain height:
jQuery
$(window).scroll(function(){
if ($(this).scrollTop() > 135) {
$('#task_flyout').addClass('fixed');
} else {
$('#task_flyout').removeClass('fixed');
}
});
css
.fixed {position:fixed; top:0; left:0;}
You could do this array(0)= array(0,1,2,3)
.
Sub add_new(data_array() As Variant, new_data() As Variant)
Dim ar2() As Variant, fl As Integer
If Not (isEmpty(data_array)) = True Then
fl = 0
Else
fl = UBound(data_array) + 1
End If
ReDim Preserve data_array(fl)
data_array(fl) = new_data
End Sub
Sub demo()
Dim dt() As Variant, nw(0, 1) As Variant
nw(0, 0) = "Hi"
nw(0, 1) = "Bye"
Call add_new(dt, nw)
nw(0, 0) = "Good"
nw(0, 1) = "Bad"
Call add_new(dt, nw)
End Sub
Let me illustrate you from my personal example in a very redundant way.
Sometimes macOS or Linux automatically sets up environment variable for you unlike Windows. But that's not the case always. So let's check it. The line immediately after echo $JAVA_HOME would be empty if the environment variable is not set. It must be empty in your case.
Now we need to check if we have bash_profile file. You saw that in my case we already have bash_profile. If not we have to create a bash_profile file.
Now let's open bash_profile file. macOS opens it using it's default TextEdit program.
This is the file where environment variables are kept. If you have opened a new bash_profile file, it must be empty. In my case, it was already set for python programming language and Anaconda distribution. Now, i need to add environment variable for Java which is just adding the first line. YOU MUST TYPE the first line VERBATIM. JUST the first line. Save and close the TextEdit. Then close the terminal.
Open the terminal again. Let's check if the environment variable is set up.
To bash into a running container, type this:
docker exec -t -i container_name /bin/bash
or
docker exec -ti container_name /bin/bash
or
docker exec -ti container_name sh
Use Webview to load gif like as
webView = (WebView) findViewById(R.id.webView);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/1.gif");
I just came across this same problem. I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that matplotlib
's plot_surface
wants. My data happened to be in a pandas.DataFrame
so here is the matplotlib.plot_surface
example with the modifications to plot 3 1-D arrays.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')
That is the original example. Adding this next bit on creates the same plot from 3 1-D arrays.
# ~~~~ MODIFICATION TO EXAMPLE BEGINS HERE ~~~~ #
import pandas as pd
from scipy.interpolate import griddata
# create 1D-arrays from the 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
xyz = {'x': x, 'y': y, 'z': z}
# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x'])))
# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')
# ~~~~ MODIFICATION TO EXAMPLE ENDS HERE ~~~~ #
plt.show()
Here are the resulting figures:
$('.list-toggle').click(function() {
var $listSort = $('.list-sort');
if ($listSort.attr('colspan')) {
$listSort.removeAttr('colspan');
} else {
$listSort.attr('colspan', 6);
}
});
Here's a working fiddle example.
See the answer by @RienNeVaPlus below for a more elegant solution.
Sometimes I use a boolean variable. Naive, if you want, but I find it quite flexible and comfortable to read. Testing a variable may avoid testing again complex conditions and may also collect results from several tests in inner loops.
x_loop_must_break = False
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
x_loop_must_break = True
break
if x_loop_must_break: break
In your .gradle
change MinSDK, for example:
build.gradle
(Module: app)
minSdkVersion 9
minSdkVersion 14
etc.
This works too. It seems shortest working notation:
!$('#selector:checked')
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.
The feature doesn't prevent any other type of data forgery or tampering based attacks.
To use it, decorate the action method or controller with the ValidateAntiForgeryToken
attribute and place a call to @Html.AntiForgeryToken()
in the forms posting to the method.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
This is the way I got it working for me:
Tasks:
- name: checking if the file 1 exists
stat:
path: /path/to/foo abc.xts
register: stat_result
- name: moving file 1
command: mv /path/to/foo abc.xts /tmp
when: stat_result.stat.exists == True
the playbook above, will check if file abc.xts exists before move the file to tmp folder.
I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!
I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.
{
"testCases" :
{
"case.1" :
{
"scenario" : "this the case 1.",
"result" : ["this is a very long line which is not easily readble.",
"so i would like to write it in multiple lines.",
"but, i do NOT require any new lines in the output."]
}
}
}
}
The join in back again whenever required with
result.join(" ")
If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.
Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.
No one says anything about php-doc, but for me that is also a very significant argument for the preference of const
:
/**
* My foo-bar const
* @var string
*/
const FOO = 'BAR';
"SMTP = localhost",
"smtp_port = 25",
"; sendmail_path = ".
Credit: How to configure WAMP (localhost) to send email using Gmail?
Additionally, if you can't see the "Provide Export Compliance Information" button make sure you have the right role in your App Store Connect or talk to the right person (Account Holder, Admin, or App Manager).
This happens when you have previously changed your icon or the ic_launcher; and when that ic_launcher no longer exists in your base folder.
Try adding a png image and giving the same name and then copy it to your drawable folder.Now re build the project.
You could use streams in Java 8. To always get 10 entries at the most, you could do:
dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());
You should replace the old OpenSSL binary file by the new one via a symlink:
sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`
Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.
You might notice using class selector to get value of ASP.NET RadioButton
controls is always empty and here is the reason.
You create RadioButton
control in ASP.NET
as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET
renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET
we don't want to use RadioButton
control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton
using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});
setInterval as suggested by SLaks was exactly what I needed to make my timer. (Thanks mate!)
Using setInterval and this great blog post I ended up creating the following function to display a timer inside my "box_header" div. I hope this helps anyone else with similar requirements!
function get_elapsed_time_string(total_seconds) {
function pretty_time_string(num) {
return ( num < 10 ? "0" : "" ) + num;
}
var hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
var minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
var seconds = Math.floor(total_seconds);
// Pad the minutes and seconds with leading zeros, if required
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
return currentTimeString;
}
var elapsed_seconds = 0;
setInterval(function() {
elapsed_seconds = elapsed_seconds + 1;
$('#box_header').text(get_elapsed_time_string(elapsed_seconds));
}, 1000);
Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).
Try EncodingChecker
File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.
File Encoding Checker requires .NET 4 or above to run.
For encoding detection, File Encoding Checker uses the UtfUnknown Charset Detector library. UTF-16 text files without byte-order-mark (BOM) can be detected by heuristics.
Here is another way using WebRequest, I hope it will work for you
$user = 'whatever'
$pass = 'whatever'
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }
Invoke-WebRequest -Credential $credential -Headers $headers -Uri "https://dc01.test.local/"
To invoke the procedure from the SQLPlus command line, try one of these:
CALL test_sp_1();
EXEC test_sp_1
My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything
$ pip install pip-review
$ pip-review --local --interactive
You never throw a C++ exception by accessing invalid memory. You are just giving an example of the general idea of referencing an arbitrary memory location. I could do the same like this:
unsigned int q = 123456;
*(double*)(q) = 1.2;
Here I am simply treating 123456 as the address of a double and write to it. Any number of things could happen:
q
might in fact genuinely be a valid address of a double, e.g. double p; q = &p;
. q
might point somewhere inside allocated memory and I just overwrite 8 bytes in there. q
points outside allocated memory and the operating system's memory manager sends a segmentation fault signal to my program, causing the runtime to terminate it. The way you set it up it is a bit more reasonable that the returned address points into a valid area of memory, as it will probably just be a little further down the stack, but it is still an invalid location that you cannot access in a deterministic fashion.
Nobody will automatically check the semantic validity of memory addresses like that for you during normal program execution. However, a memory debugger such as valgrind
will happily do this, so you should run your program through it and witness the errors.
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.
So if you say
for c in session.query(Stuff).all():
c.foo = c.foo+1
session.commit()
it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.
Instead you should do this:
session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()
This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.
In the almost-released 0.5 series you could also use this method for updating:
session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()
That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False
to the update statement and get rid of that select.
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
It most likely means the hostname can't be resolved.
import socket
socket.getaddrinfo('localhost', 8080)
If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.
I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!
SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');
I suggest that you should not do it like this.
Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage
.
You should do it like this to let MVC do all the model binding for you:
[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
//your logic to process input parameters.
}
In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:
[HttpPost]
public void Confirmation()
{
var content = Request.Content.ReadAsStringAsync().Result;
}
In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.
You have to store the content as a fact:
- set_fact:
string_to_echo: "{{ command_output.stdout }}"
Try this one
.responsive-container{
display:table;
}
.img-container{
display:table-cell;
vertical-align: middle;
}
For PyCharm 5 (or 2016.1), you can:
var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))
With Java 8 you can simply convert your list to a stream allowing you to write:
import java.util.List;
import java.util.stream.Collectors;
List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
.filter(a -> Objects.equals(a.value3, "three"))
.collect(Collectors.toList());
Note that
a -> Objects.equals(a.value3, "three")
is a lambda expressionresult
is a List
with a Sample
typelist.parallelStream()
instead of list.stream()
(read this)If you can't use Java 8, you can use Apache Commons library and write:
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
Collection result = CollectionUtils.select(list, new Predicate() {
public boolean evaluate(Object a) {
return Objects.equals(((Sample) a).value3, "three");
}
});
// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);
Note that:
Object
to Sample
at each iterationSample[]
, you need extra code (as shown in my sample)Bonus: A nice blog article talking about how to find element in list.
Here is obscure solution: define macro function:
#define Z(x) \
(x==0 ? 'A' : \
(x==1 ? 'B' : \
(x==2 ? 'C' : '\0')))
char x[] = { Z(0), Z(1), Z(2) };
Add an abstraction layer, for example, a YAML file like in this project https://github.com/larytet/dockerfile-generator which looks like
centos7:
base: centos:centos7
packager: rpm
install:
- $build_essential_centos
- rpm-build
run:
- $get_release
env:
- $environment_vars
A short Python script/make can generate all Dockerfiles from the configuration file.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
You can use the python-n2w library, Just do
pip install n2w
then simply
print(n2w.convert(your-number-here))
This one more version - this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.
as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6
1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.
Right click on the 'hello" (or whatever your project name is.)
Choose "Properties" from the context menu.
Choose Configuration Properties>Linker>System.
For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
Choose "Console (/SUBSYSTEM:CONSOLE)"
Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)
Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.
Again, CTRL-F5 and the subsystem hints work together; they are not separate options.
the first two bounds default to 0 and the length of the sequence, as before, and a stride of -1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.
name="ravi"
print(name[::-1]) #ivar
You can do it as simple as this, I did it in react hooks :
(myNumber == 12) ? "true" : "false"
it was equal to this long if function below :
if (myNumber == 12) {
"true"
} else {
"false"
}
Hope it helps ^_^
Briefly, the way I have done this is:
Read the file (a db dump eg $ mysqldump db > db.sql
)
$sql = file_get_contents(db.sql);
Import it using mysqli::multi_query
if ($mysqli->multi_query($sql)) {
$mysqli->close();
} else {
throw new Exception ($mysqli->error);
}
Watch out mysqli_query supports async queries. More here: http://php.net/manual/en/mysqli.multi-query.php and here https://stackoverflow.com/a/6652908/2002493
1) PYTHONPATH
is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:
# make python look in the foo subdirectory of your home directory for
# modules and packages
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
Here I use the sh
syntax. For other shells (e.g. csh
,tcsh
), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).
2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.
3) The folder where your modules live is dependent on PYTHONPATH
and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls
-- where does ls
live? /usr/bin
? /bin
? 99% of the time, you don't need to care -- Just use ls
and be happy that it lives somewhere on your PATH
so the shell can find it.
4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.
5) Configure PYTHONPATH
to include the directory where your module resides and python will be able to find your module.
Code from the above answer by Dutchie432
.FixedHeightContainer {
float:right;
height: 250px;
width:250px;
padding:3px;
background:#f00;
}
.Content {
height:224px;
overflow:auto;
background:#fff;
}
This HTML code show up only Upload File button
<form action="/action_page.php">
<input type="button" id="id" value="Upload File" onclick="document.getElementById('file').click();" />
<input type="file" style="display:none;" id="file" name="file" onchange="this.form.submit()"/>
</form>
You can avoid get undefined in '$' this way
window.addEventListener("DOMContentLoaded", function(){
// Your code
});
EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure
VARIABLE = value
Normal setting of a variable, but any other variables mentioned with the value
field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared
VARIABLE := value
Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.
VARIABLE ?= value
Setting of a variable only if it doesn't have a value. value
is always evaluated when VARIABLE
is accessed. It is equivalent to
ifeq ($(origin FOO), undefined)
FOO = bar
endif
See the documentation for more details.
VARIABLE += value
Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)
I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?
html:
<div id="content">
<div id='bg'></div>
<h2>What is Lorem Ipsum?</h2>
<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
css:
#content {
text-align: left;
width: 75%;
margin: auto;
position: relative;
}
#bg {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
opacity: .4;
width: 100%;
height: 100%;
}
Yes, for Virtualbox provider do something like this:
Vagrant.configure("2") do |config|
# ...other options...
config.vm.provider "virtualbox" do |p|
p.name = "something-else"
end
end
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng
are empty
, if they are, use NULL
instead of '$intLat'
or '$intLng'
.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
If you're on linux then you can grab the guest processes with
ps axuw | grep vmware-vmx
As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD
You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:
shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"
Alongside with other motions that are already mentioned here, there is also /{pattern}<CR>
motion, so if you know that you want to delete to line that contains foo, you could do dV/foo<CR>
. V
is here to force motion be line-wise because by default /
is characterwise.
Should it be necessary to manually remove a service:
You will have to reboot before the list gets updated in services
Making more general the @showdev answer.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
Example:
getObjectByValue(data, "code", "DZ" );
I have figured out that I can convert the keyCode of the event to a character by using the following function:
var char = String.fromCharCode(v_code);
From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).
Thanks for all your help guys.
Thank you Felix Kling, but his answer need a little change:
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
React.render(<MySelect />, document.body);
I found a solution.
One just has to add the following code:
// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0
// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0
// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;
// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;
Restored old answer (for reference and devs willing to support iOS below 6.0):
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;
On the side: both enum values yield to 0
anyway.
If you wish to take into account the ellipsoid being used you can find the formulae here http://www.ordnancesurvey.co.uk/oswebsite/gps/docs/A_Guide_to_Coordinate_Systems_in_Great_Britain.pdf
see Annexe B
The document contains lots of other useful stuff
B
The above methods did not work for me in Windows 8 Pro.
Just set the path to
C:\Program Files\Java\jdk1.7.0_07\
Where C is your drive in which you have installed the JDK.
Don't forget the backward slash at the end.
memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more
For me, this was due to the fact that I was trying to debug using eclipse yet also running Android Studio. Both programs were trying to monitor android devices on the similar ports. Either quit all IDEs other than one, or modify the port number used for debugging in the IDE preferences so they are not similar.
I have found that a button works, but that you'll want to add style="height: 100%;"
to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1
You can take a look at source-code-wordle.de, I have analyzed there the most frequently used suffixes of class names of the .NET framework and some other libraries.
The top 20 are:
Now you should be able to do it directly in the IB.
Not sure though, if this was available when the question was posted originally.
I would unpack your gem in the application vendor folder
gem unpack your.gem --target /path_to_app/vendor/gems/
Then add the path on the Gemfile to link unpacked gem.
gem 'your', '2.0.1', :path => 'vendor/gems/your'
You can try this:
use database
go
declare @temp as int
select @temp = count(1) from sys.schemas where name = 'newSchema'
if @temp = 0
begin
exec ('create SCHEMA temporal')
print 'The schema newSchema was created in database'
end
else
print 'The schema newSchema already exists in database'
go
Just make option#1 Select Language:
Yes. Use Reflection. With Reflection, you can do things like:
//given object of some type
object myObjectFromSomewhere;
Type myObjOriginalType = myObjectFromSomewhere.GetType();
PropertyInfo[] myProps = myObjOriginalType.GetProperties();
And then you can use the resulting PropertyInfo classes to compare all manner of things.
You can use the @RequestHeader
annotation with HttpHeaders
method parameter to gain access to all request headers:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
You can use java.awt.Robot
to achieve this task.
below is the code of server, which saves the captured screenshot as image in your Directory.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.
package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
@Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
Although divmod() has been mentioned, I didn't see what I considered to be a nice example. Here's mine:
q=972021.0000 # For example
days = divmod(q, 86400)
# days[0] = whole days and
# days[1] = seconds remaining after those days
hours = divmod(days[1], 3600)
minutes = divmod(hours[1], 60)
print "%i days, %i hours, %i minutes, %i seconds" % (days[0], hours[0], minutes[0], minutes[1])
Which outputs:
11 days, 6 hours, 0 minutes, 21 seconds
May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML
<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
What you've made is a dictionary and not a Set.
The update
method in dictionary is used to update the new dictionary from a previous one, like so,
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
Whereas in sets, it is used to add elements to the set.
>>> D.update([1, 2])
>>> D
set([1, 2])
We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account>
element, after parsing the reader will index the </Accounts>
closing tag.
The parsing code looks something like this:
public class Account
{
string _accountId;
string _nameOfKin;
Statements _statmentsAvailable;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read node attributes
_accountId = reader.GetAttribute( "accountId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
switch( reader.Name )
{
// Read element for a property of this class
case "NameOfKin":
_nameOfKin = reader.ReadElementContentAsString();
break;
// Starting sub-list
case "StatementsAvailable":
_statementsAvailable = new Statements();
_statementsAvailable.Read( reader );
break;
default:
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statements
class just reads in the <StatementsAvailable>
node
public class Statements
{
List<Statement> _statements = new List<Statement>();
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
if( reader.IsStartElement() )
{
if( reader.Name == "Statement" )
{
var statement = new Statement();
statement.ReadFromXml( reader );
_statements.Add( statement );
}
else
{
reader.Skip();
}
}
else
{
reader.Read();
break;
}
}
}
}
The Statement
class would look very much the same
public class Statement
{
string _satementId;
public void ReadFromXml( XmlReader reader )
{
reader.MoveToContent();
// Read noe attributes
_statementId = reader.GetAttribute( "statementId" );
...
if( reader.IsEmptyElement ) { reader.Read(); return; }
reader.Read();
while( ! reader.EOF )
{
....same basic loop
}
}
}
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
For problems where it seems to be an error on a line you think is correct, you can often remove/comment the line where the error appears to be and, if the error moves to the next line, there are two possibilities.
Either both lines have a problem or the previous line has a problem which is being carried forward. The most likely case is the second option (even more so if you remove another line and it moves again).
For example, the following Python program twisty_passages.py
:
xyzzy = (1 +
plugh = 7
generates the error:
File "twisty_passages.py", line 2
plugh = 7
^
SyntaxError: invalid syntax
despite the problem clearly being on line 1.
In your particular case, that is the problem. The parentheses in the line before your error line is unmatched, as per the following snippet:
# open parentheses: 1 2 3
# v v v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
# ^ ^
# close parentheses: 1 2
Depending on what you're trying to achieve, the solution may be as simple as just adding another closing parenthesis at the end, to close off the sqrt
function.
I can't say for certain since I don't recognise the expression off the top of my head. Hardly surprising if (assuming PSAT is the enzyme, and the use of the typeMolecule
identifier) it's to do with molecular biology - I seem to recall failing Biology consistently in my youth :-)
Quoting from Conda: Myths and Misconceptions (a comprehensive description):
...
Reality: Conda and pip serve different purposes, and only directly compete in a small subset of tasks: namely installing Python packages in isolated environments.
Pip, which stands for Pip Installs Packages, is Python's officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI). Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).
In short, pip is a general-purpose manager for Python packages; conda is a language-agnostic cross-platform environment manager. For the user, the most salient distinction is probably this: pip installs python packages within any environment; conda installs any package within conda environments. If all you are doing is installing Python packages within an isolated environment, conda and pip+virtualenv are mostly interchangeable, modulo some difference in dependency handling and package availability. By isolated environment I mean a conda-env or virtualenv, in which you can install packages without modifying your system Python installation.
Even setting aside Myth #2, if we focus on just installation of Python packages, conda and pip serve different audiences and different purposes. If you want to, say, manage Python packages within an existing system Python installation, conda can't help you: by design, it can only install packages within conda environments. If you want to, say, work with the many Python packages which rely on external dependencies (NumPy, SciPy, and Matplotlib are common examples), while tracking those dependencies in a meaningful way, pip can't help you: by design, it manages Python packages and only Python packages.
Conda and pip are not competitors, but rather tools focused on different groups of users and patterns of use.
Those are varargs
they are used to create a method that receive any number of arguments.
For instance PrintStream.printf method uses it, since you don't know how many would arguments you'll use.
They can only be used as final position of the arguments.
varargs
was was added on Java 1.5
use
select 1/3.0
This will do the job.
Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link
And then if you have something like blue ocean, the choices would look something like this:
You define and access your variables like this:
pipeline {
agent any
parameters {
string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
}
stages {
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
echo "flag: ${params.DEPLOY_ENV}"
}
}
}
}
Automated builds will pick up the default params. But if you do it manually then you get the option to choose.
And then assign values like this:
Try this:
Project -> Properties -> Java Build Path -> Add Class Folder.
If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :
Create a 2 line script called zz.sh
#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
Currently, simply executing the script sends both STDOUT and STDERR to the screen.
./zz.sh
Now start with the standard redirection :
zz.sh > zfile.txt
In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.
The above is the same as :
zz.sh 1> zfile.txt
Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.
zz.sh 2> zfile.txt
Combining the above two, you get:
zz.sh 1> zfile.txt 2>&1
Explanation:
Eventually, you can pack the whole thing inside nohup command & to run it in the background:
nohup zz.sh 1> zfile.txt 2>&1&
If you're not using AngularJS UI Bootstrap, here's how I did it.
I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.
angular.module('yourApp', []).
directive('myModal',
['$rootScope','$log','$compile',
function($rootScope, $log, $compile) {
var _scope = null;
var _element = null;
var _onModalShow = function(event) {
_element.after($compile(event.target)(_scope));
};
return {
link: function(scope, element, attributes) {
_scope = scope;
_element = element;
$(element).on('show.bs.modal',_onModalShow);
}
};
}]);
I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.
Note: The entire scope is now visible to your modal so you can also access $scope.users in it.
<div my-modal id="encouragementModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h3>Confirm encouragement?</h3>
</div>
<div class="modal-body">
Do you really want to encourage <b>{{aModel.userName}}</b>?
</div>
<div class="modal-footer">
<button class="btn btn-info"
ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
Confirm
</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
</div>
</div>
Trying with a different version of gcc worked for me - gcc 4.9 in my case.
The easiest way is to use the replace
method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']
) and what you want to replace them with (the string 'A'
in this case):
>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0 A
1 B
2 A
3 D
4 A
This creates a new Series of values so you need to assign this new column to the correct column name:
df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')
The way that is blessed by Java 7 documentation:
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String string1 = "2001-07-04T12:08:56.235-0700";
Date result1 = df1.parse(string1);
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);
You can find more examples in section Examples at SimpleDateFormat javadoc.
UPD 02/13/2020: There is a completely new way to do this in Java 8
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
book_shop[ch1] -= 1
There's no difference - they are the same.
PHP Manual for exit
:
Note: This language construct is equivalent to
die()
.
PHP Manual for die
:
This language construct is equivalent to
exit()
.
You can use this small Python 3 script (using only standard library modules) to grab the list of available versions for a package from PyPI using JSON API and print them in reverse chronological order. Unlike some other Python solutions posted here, this doesn't break on loose versions like django
's 2.2rc1
or uwsgi
's 2.0.17.1
:
#!/usr/bin/env python3
import json
import sys
from urllib import request
from pkg_resources import parse_version
def versions(pkg_name):
url = f'https://pypi.python.org/pypi/{pkg_name}/json'
releases = json.loads(request.urlopen(url).read())['releases']
return sorted(releases, key=parse_version, reverse=True)
if __name__ == '__main__':
print(*versions(sys.argv[1]), sep='\n')
Save the script and run it with the package name as an argument, e.g.:
python versions.py django
3.0a1
2.2.5
2.2.4
2.2.3
2.2.2
2.2.1
2.2
2.2rc1
...
Make sure you are calling typeof on the actual function, not a string literal:
function x() {
console.log("hi");
}
typeof "x"; // returns "string"
typeof x; // returns "function"
What I'm guessing is that you need to set those input elements to runat="server".
So you won't be able to access the control
<input type="text" name="email" id="myTextBox" />
But you'll be able to work with
<input type="text" name="email" id="myTextBox" runat="server" />
And read from it by using
string myStringFromTheInput = myTextBox.Value;
Just stick in a file and call it "ServiceModelSamples.bat" or something.
You could add "@echo off" as line one, so the command doesn't get printed to the screen:
@echo off
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
Below will list all the distinct data types of all the table in the provided schema name.
\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv' delimiter as ',' CSV header
drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.
$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));
From the test,
it('should allow passing locals to the expression', inject(function($rootScope) {
expect($rootScope.$eval('a+1', {a: 2})).toBe(3);
$rootScope.$eval(function(scope, locals) {
scope.c = locals.b + 4;
}, {b: 3});
expect($rootScope.c).toBe(7);
}));
We also can pass locals for evaluation expression.
You can use ..\path
to go one level up, ..\..\path
to go two levels up from path.
You can use Path
class too.
Almost all answers assume the ID column is ordered (and perhaps auto incremented). There are situations, however, when the ID column is not ordered, hence the ORDER BY statement makes no sense.
The last inserted ID might not always be the highest ID, it is just the last (unique) entry.
One possible solution for such a situation is to create a row id on the fly:
SET @r = 0;
SELECT * FROM (SELECT *, (@r := @r + 1) AS r_id FROM uat3187) AS tmp
ORDER BY r_id DESC LIMIT 1;
meda's answer is completely legit, but when I copied the code I got an error!
Somewhere in the "php://input"
there's an invalid character (maybe one of the quotes?).
When I typed the "php://input"
code manually, it worked.
Took me a while to figure out!
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
I made a bash script to switch between different PHP versions on Ubuntu.
Hope it helps someone.
Here's the script: (save it in /usr/local/bin/sphp.sh, don't forget to add +x flag with command: sudo chmod +x /usr/local/bin/sphp.sh)
#!/bin/bash_x000D_
_x000D_
# Usage_x000D_
if [ $# -ne 1 ]; then_x000D_
echo "Usage: sphp [phpversion]"_x000D_
echo "Example: sphp 7.2"_x000D_
exit 1_x000D_
fi_x000D_
_x000D_
currentversion="`php -r \"error_reporting(0); echo str_replace('.', '', substr(phpversion(), 0, 3));\"`"_x000D_
newversion="$1"_x000D_
_x000D_
majorOld=${currentversion:0:1}_x000D_
minorOld=${currentversion:1:1}_x000D_
majorNew=${newversion:0:1}_x000D_
minorNew=${newversion:2:1}_x000D_
_x000D_
if [ $? -eq 0 ]; then_x000D_
if [ "${newversion}" == "${currentversion}" ]; then_x000D_
echo "PHP version [${newversion}] is already being used"_x000D_
exit 1_x000D_
fi_x000D_
_x000D_
echo "PHP version [$newversion] found"_x000D_
echo "Switching from [php${currentversion}] to [php${newversion}] ... "_x000D_
_x000D_
printf "a2dismod php$majorOld.$minorOld ... "_x000D_
sudo a2dismod "php${majorOld}.${minorOld}"_x000D_
printf "[OK] and "_x000D_
_x000D_
printf "a2enmod php${newversion} ... "_x000D_
sudo a2enmod "php${majorNew}.${minorNew}"_x000D_
printf "[OK]\n"_x000D_
_x000D_
printf "update-alternatives ... "_x000D_
sudo update-alternatives --set php "/usr/bin/php${majorNew}.${minorNew}"_x000D_
printf "[OK]\n"_x000D_
_x000D_
sudo service apache2 restart_x000D_
printf "[OK] apache2 restarted\n"_x000D_
else_x000D_
echo "PHP version $majorNew.$minorNew was not found."_x000D_
echo "Try \`sudo apt install php@${newversion}\` first."_x000D_
exit 1_x000D_
fi_x000D_
_x000D_
echo "DONE!"
_x000D_
\d will not match the decimal point. Use the following for the decimal.
const re = /^\d*(\.\d+)?$/
'123'.match(re) // true
'123.3'.match(re) // true
'123!3'.match(re) // false
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
Use this code for iCheck:
$('.i-checks').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green',
}).on('ifChanged', function(e) {
// Get the field name
var isChecked = e.currentTarget.checked;
if (isChecked == true) {
}
});
Not sure what you are trying to do, but you have two select clauses. Do this instead:
SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A
JOIN ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id
Update:
You could probably reduce it to something like this:
SELECT o.orders_id,
op1.products_id,
op1.quantity,
op2.products_id,
op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id
WHERE op1.products_id = 180
AND op2.products_id = 181
If you still need to Debug IE 7, the emulation mode of IE 11 is working pretty well.
Go to menu: Dev Tools, then to emulation and set it. It also gives error line information.
Set up invironment variable in Advanced System Settings. In Command prompt it should behave like this :
C:\Windows\system32>echo %http_proxy%
http://username:passowrd@proxy:port
C:\Windows\system32>echo %https_proxy%
Later , Simply
pip install whatEver
should work.
If you have trouble with rails s
, sometimes terminal fails.
And you should try to use:
./bin/rails
To access command.
I usually use
DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)
Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...
A handle is whatever you want it to be.
A handle can be a unsigned integer used in some lookup table.
A handle can be a pointer to, or into, a larger set of data.
It depends on how the code that uses the handle behaves. That determines the handle type.
The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.
A shared service is the best approach
export class SharedService {
globalVar:string;
}
But you need to be very careful when registering it to be able to share a single instance for whole your application. You need to define it when registering your application:
bootstrap(AppComponent, [SharedService]);
But not to define it again within the providers
attributes of your components:
@Component({
(...)
providers: [ SharedService ], // No
(...)
})
Otherwise a new instance of your service will be created for the component and its sub-components.
You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular 2:
You should notice that you can also define Observable
properties in the service to notify parts of your application when your global properties change:
export class SharedService {
globalVar:string;
globalVarUpdate:Observable<string>;
globalVarObserver:Observer;
constructor() {
this.globalVarUpdate = Observable.create((observer:Observer) => {
this.globalVarObserver = observer;
});
}
updateGlobalVar(newValue:string) {
this.globalVar = newValue;
this.globalVarObserver.next(this.globalVar);
}
}
See this question for more details:
I used the below to solve this problem.
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.
Camel Case is usually without spaces between words.
Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.
I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.
I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.
$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));
function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
pStr = pStr + pPadStr;
return pStr;
}
See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html
To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.Net">
<listeners>
<add name="MyTraceFile"/>
<add name="MyConsole"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="MyTraceFile"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.trace.log" />
<add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose" />
</switches>
</system.diagnostics>
Redirecting Input
Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.
The general format for redirecting input is:
[n]<word
Redirecting Output
Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.
The general format for redirecting output is:
[n]>word
Moving File Descriptors
The redirection operator,
[n]<&digit-
moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n.
Similarly, the redirection operator
[n]>&digit-
moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.
man bash
Type /^REDIRECT
to locate to the redirection
section, and learn more...
An online version is here: 3.6 Redirections
Lots of the time, man
was the powerful tool to learn Linux.
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx
where xxx is gcc or ar or ld, etc
You can remove the spaces before casting to int
:
(int)str_replace(' ', '', $b);
Also, if you want to strip other commonly used digit delimiters (such as ,
), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):
(int)str_replace(array(' ', ','), '', $b);
I used this way in my code
$(function(){
$('.block').affix();
})
On EF6.2, you can use HasIndex()
to add indexes for migration through fluent API.
https://github.com/aspnet/EntityFramework6/issues/274
Example
modelBuilder
.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
On EF6.1 onwards, you can use IndexAnnotation()
to add indexes for migration in your fluent API.
http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex
You must add reference to:
using System.Data.Entity.Infrastructure.Annotations;
Basic Example
Here is a simple usage, adding an index on the User.FirstName
property
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
Practical Example:
Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName
and User.LastName
, with an index name "IX_FirstNameLastName"
modelBuilder
.Entity<User>()
.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));
modelBuilder
.Entity<User>()
.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(60)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));
NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is
search:
(\w+\\.someMethod\\(\\))
replace:
((TypeName)$1)
Here:
In search:
First and last (
, )
depicts a group in regex
\w
depicts words (alphanumeric + underscore)
+
depicts one or more (ie one or more of alphanumeric + underscore)
.
is a special character which depicts any character (ie .+
means
one or more of any character). Because this is a special character
to depict a .
we should give an escape character with it, ie \.
someMethod
is given as it is to be searched.
The two parenthesis (
, )
are given along with escape character
because they are special character which are used to depict a group
(we will discuss about group in next point)
In replace:
It is given ((TypeName)$1)
, here $1
depicts the
group. That is all the characters that are enclosed within the first
and last parenthesis (
, )
in the search field
Also make sure you have checked the 'Regular expression' option in find an replace box
"my, tags are, in here".split(/[ ,]+/)
the result is :
["my", "tags", "are", "in", "here"]
If you google. "Count down for loop python" you get these, which are pretty accurate.
how to loop down in python list (countdown)
Loop backwards using indices in Python?
I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
In C# the code looks like:
Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);
or
var dictionary = new Dictionary<string, int> {
{"sample1", 1},
{"sample2", 2}
};
In JavaScript:
var dictionary = {
"sample1": 1,
"sample2": 2
}
A C# dictionary object contains useful methods, like dictionary.ContainsKey()
In JavaScript, we could use the hasOwnProperty
like:
if (dictionary.hasOwnProperty("sample1"))
console.log("sample1 key found and its value is"+ dictionary["sample1"]);
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
Don't know why @Janos deleted his answer, but it's correct: your data frame Train
doesn't have a column named pre
. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train
has columns called residual.sugar
, total.sulfur
, alcohol
and quality
. You need to change either your formula or your data frame so they're consistent with each other.
And just to clarify: Pre
is an object containing a formula. That formula contains a reference to the variable pre
. It's the latter that has to be consistent with the data frame.
SOLUTION
This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.
1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"
2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"
3) Insert command to register url
netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone
NOTE:
netsh http delete urlacl url=http://{ip_addr}:{port}/
This misled me a bit - it should be setImageResource
instead of setBackgroundResource
:) !!
The following works fine :
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setImageResource(R.drawable.actions_record);
while when using the setBackgroundResource
the actual imagebutton's image
stays while the background image is changed which leads to a ugly looking imageButton object
Thanks.
PSH> $cred = Get-Credential
PSH> $cred | Export-CliXml c:\temp\cred.clixml
PSH> $cred2 = Import-CliXml c:\temp\cred.clixml
That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.
You'll need to open the workbook to refer to it.
Sub Setwbk()
Dim wbk As Workbook
Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
Master Benchmark Data Sheet.xlsx")
End Sub
* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:
Why do I have to "set" it?
Set
is how VBA assigns object variables. Since a Range
and a Workbook
/Worksheet
are objects, you must use Set
with these.
Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".
outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
items = line.split( ',' )
outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()
You can change the mysql root password by logging in to the database directly (mysql -h your_host -u root) then run
SET PASSWORD FOR root@localhost = PASSWORD('yourpassword');
OK some answers about malloc were already posted.
The more interesting part is how free works (and in this direction, malloc too can be understood better).
In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).
So returning 40 Bytes to the OS will just not work. So what does free do?
Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.
The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.
There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.
Why does your code crash:
The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.
This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!
Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.
Static member functions must refer to static variables of that class. So in your case,
static void CP_StringToPString( std::string& inString, unsigned char *outString);
Since your member function CP_StringToPstring
is static, the parameters in that function, inString
and outString
should be declared as static too.
The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.
You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.
Before running ./configure
try running autoreconf -f -i
. The autoreconf program automatically runs autoheader, aclocal, automake, autopoint and libtoolize as required.
Edit to add: This is usually caused by checking out code from Git instead of extracting it from a .zip
or .tar.gz
archive. In order to trigger rebuilds when files change, Git does not preserve files' timestamps, so the configure
script might appear to be out of date. As others have mentioned, there are ways to get around this if you don't have a sufficiently recent version of autoreconf
.
Another edit: This error can also be caused by copying the source folder extracted from an archive with scp to another machine. The timestamps can be updated, suggesting that a rebuild is necessary. To avoid this, copy the archive and extract it in place.
Here is my submission!
if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.
The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.
The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.
// Server_x000D_
var io1 = require('socket.io').listen(8321);_x000D_
_x000D_
io1.on('connection', function(socket1) {_x000D_
socket1.on('bar', function(msg1) {_x000D_
console.log(msg1);_x000D_
});_x000D_
});_x000D_
_x000D_
// Mirror_x000D_
var ioIn = require('socket.io').listen(8123);_x000D_
var ioOut = require('socket.io-client');_x000D_
var socketOut = ioOut.connect('http://localhost:8321');_x000D_
_x000D_
_x000D_
ioIn.on('connection', function(socketIn) {_x000D_
socketIn.on('foo', function(msg) {_x000D_
socketOut.emit('bar', msg);_x000D_
});_x000D_
});_x000D_
_x000D_
// Client_x000D_
var io2 = require('socket.io-client');_x000D_
var socket2 = io2.connect('http://localhost:8123');_x000D_
_x000D_
var msg2 = "hello";_x000D_
socket2.emit('foo', msg2);
_x000D_
Alexy's answer almost worked for me except that I was getting this error:
timebase 1/90000 not supported by MPEG 4 standard, the maximum admitted value for the timebase denominator is 65535
I just had to add a parameter (-r 65535/2733) to the command and it worked. The full command was thus:
ffmpeg -i in.mp4 -vf "transpose=1" -r 65535/2733 out.mp4
I actually found an extension method that will do what I want nicely
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
you can test if have exactly some values, by example:
for(MyBoolean b : MyBoolean.values()) {
switch(b) {
case TRUE:
break;
case FALSE:
break;
default:
throw new IllegalArgumentException(b.toString());
}
for(String s : new String[]{"TRUE", "FALSE" }) {
MyBoolean.valueOf(s);
}
If someone removes or adds a value, some of test fails.
array_map('trim', $data)
would convert all subarrays into null
. If it is needed to trim spaces only for strings and leave other types as it is, you can use:
$data = array_map(
function ($item) {
return is_string($item) ? trim($item) : $item;
},
$data
);
With Protractor, you can use the following approach
var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);
So your code will look something like,
emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');
btnLoginEl.click();
var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);
expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');
Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.
Reference: Protractor ExpectedConditions
Most of the issues I've seen with developers complaining that Get Latest doesn't do what they expect stem from the fact that they're performing a Get Latest from Solution Explorer rather than from Source Control Explorer. Solution Explorer only gets the files that are part of the solution and ignores anything that may be required by files within the solution, and therefore part of source control, whereas Source Control explorer compares your local workspace against the repository on the server to determine which files are needed.
Use below line of code :
UIBarButtonItem *newBackButton =
[[UIBarButtonItem alloc] initWithTitle:@"hello"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.leftBarButtonItems =[[NSArray alloc] initWithObjects:newBackButton, nil];
self.navigationItem.leftItemsSupplementBackButton = YES;
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
As Foo
is a class can you not create virtual overloaded Initialise()
methods? Then they would be available to sub-classes and still extensible?
public class Foo
{
...
public Foo() {...}
public virtual void Initialise(int i) {...}
public virtual void Initialise(int i, int i) {...}
public virtual void Initialise(int i, int i, int i) {...}
...
public virtual void Initialise(int i, int i, ..., int i) {...}
...
public virtual void SomethingElse() {...}
...
}
This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.
I've really taken recently to display: table
to give things a fixed size such as to enable margin: 0 auto
to work. Has made my life a lot easier. You just need to get past the fact that 'table' display doesn't mean table html.
It's especially useful for responsive design where things just get hairy and crazy 50% left this and -50% that just become unmanageable.
style
{
display: table;
margin: 0 auto
}
In addition if you've got two buttons and you want them the same width you don't even need to know the size of each to get them to be the same width - because the table will magically collapse them for you.
(this also works if they're inline and you want to center two buttons side to side - try doing that with percentages!).
One thing to consider: Screenreaders
For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.
For distributing and loading the proper SWT-library, you might find this link usefull: http://www.chrisnewland.com/select-correct-swt-jar-for-your-os-and-jvm-at-runtime-191
You may want to add this to your bootstrap project to check active breakpoint visually
<script type='text/javascript'>
$(document).ready(function () {
var mode;
$('<div class="mode-informer label-info" style="z-index:1000;position: fixed;bottom:10px;left:10px">%mode%</div>').appendTo('body');
var checkMode = function () {
if ($(window).width() < 768) {
return 'xs';
}
else if ($(window).width() >= 768 && $(window).width() < 992) {
return 'sm';
}
else if ($(window).width() >= 992 && $(window).width() < 1200) {
return 'md';
}
else {
return 'lg';
}
};
var compareMode = function () {
if (mode !== checkMode()) {
mode = checkMode();
$('.mode-informer').text(mode).animate({
bottom: '100'
}, 100, function () {
$('.mode-informer').animate({bottom: 10}, 100)
});
}
};
$(window).on('resize', function () {
compareMode()
});
compareMode();
});
</script>
Here is the BOOTPLY
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.