If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Apple-Tz: 0',
'X-Apple-Store-Front: 143444,12'
));
return Labels;
should do the trick!
public static ArtworkData[] GetDataRecords(int UsersID)
{
ArtworkData[] Labels;
Labels = new ArtworkData[3];
return Labels;
}
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Open file.txt
in append mode and redirect stdout
there.2>&1
: Redirect stderr
to "where stdout
is currently going". In this case, that is a file opened in append mode. In other words, the &1
reuses the file descriptor which stdout
currently uses.>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.seed(9002)
>>> random.randint(1, 10)
3
You try this.
Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).
Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.
I got the same error ("Uncaught SyntaxError: Unexpected token <" ) at these two lines when testing a sample application .
<script type = "text/javascript" src="raphael-min.js"></script>
<script type = "text/javascript" src="kuma-gauge.jquery.js"></script>
After a control, I realized that, local file locations are not correct and my local server app returns default page as the result. Client app can find the files but the founded files are default page, not the *.js files. So I receive Uncaught SyntaxError: Unexpected token <
I changed to orginal location on the intenet andit solved.
<script type = "text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
<script type = "text/javascript" src="//www.jqueryscript.net/demo/Creating-Animated-Gauges-Using-jQuery-Raphael-js-kumaGauge/js/kuma-gauge.jquery.js"></script>
you can use flex display such as below code:
.example{_x000D_
background-color:red;_x000D_
height:90px;_x000D_
width:90px;_x000D_
display:flex;_x000D_
align-items:center; /*for vertically center*/_x000D_
justify-content:center; /*for horizontally center*/_x000D_
}
_x000D_
<div class="example">_x000D_
<h6>Some text</h6>_x000D_
</div>
_x000D_
to get different sizes, you can use the type parameter:
You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.
Use the START command:
start [programPath]
If the path to the program contains spaces remember to add quotes. In this case you also need to provide a title for the opening console window
start "[title]" "[program path]"
If you need to provide arguments append them at the end (outside the command quotes)
start "[title]" "[program path]" [list of command args]
Use the /b option to avoid opening a new console window (but in that case you cannot interrupt the application using CTRL-C
C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.
Example
ClassOne.hpp:
class ClassOne
{
public:
ClassOne(); // note, no function body
int method(); // no body here either
private:
int member;
};
ClassOne.cpp:
#include "ClassOne.hpp"
// implementation of constructor
ClassOne::ClassOne()
:member(0)
{}
// implementation of "method"
int ClassOne::method()
{
return member++;
}
main.cpp:
#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler
int main(int argc, char* argv[])
{
ClassOne c1;
c1.method();
return 0;
}
It's actually fairly easy, just enter it as a latitude,longitude pair, ie 46.38S,115.36E (which is in the middle of the ocean). You'll want to convert it to decimal though (divide the minutes portion by 60 and add it to the degrees [I've done that with your example]).
Try to use the source website for the gems, i.e rubygems.org. Use http instead of https. This method does not involve any work such as installing certs and all that.
Example -
gem install typhoeus --source http://rubygems.org
This works, but there is one caveat though.
The gem is installed, but the documentation is not because of cert errors. Here is the error I get
Parsing documentation for typhoeus-0.7.0 WARNING: Unable to pull
data from 'https://rubygems.org/': SSL_connect returned=1 errno=0
state=SSLv3 read server certificate B: certificate verify failed
(https://rubygems.org/latest_specs.4.8.gz)
You can use git add --patch <filename>
(or -p
for short), and git will begin to break down your file into what it thinks are sensible "hunks" (portions of the file). It will then prompt you with this question:
Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?
Here is a description of each option:
If the file is not in the repository yet, you can first do git add -N <filename>
. Afterwards you can go on with git add -p <filename>
.
Afterwards, you can use:
git diff --staged
to check that you staged the correct changesgit reset -p
to unstage mistakenly added hunksgit commit -v
to view your commit while you edit the commit message.Note this is far different than the git format-patch
command, whose purpose is to parse commit data into a .patch
files.
Reference for future: Git Tools - Interactive Staging
Here a method that resolves a relative path from a base path regardless they are in the same or in a different root:
public static String GetRelativePath(String path, String base){
final String SEP = "/";
// if base is not a directory -> return empty
if (!base.endsWith(SEP)){
return "";
}
// check if path is a file -> remove last "/" at the end of the method
boolean isfile = !path.endsWith(SEP);
// get URIs and split them by using the separator
String a = "";
String b = "";
try {
a = new File(base).getCanonicalFile().toURI().getPath();
b = new File(path).getCanonicalFile().toURI().getPath();
} catch (IOException e) {
e.printStackTrace();
}
String[] basePaths = a.split(SEP);
String[] otherPaths = b.split(SEP);
// check common part
int n = 0;
for(; n < basePaths.length && n < otherPaths.length; n ++)
{
if( basePaths[n].equals(otherPaths[n]) == false )
break;
}
// compose the new path
StringBuffer tmp = new StringBuffer("");
for(int m = n; m < basePaths.length; m ++)
tmp.append(".."+SEP);
for(int m = n; m < otherPaths.length; m ++)
{
tmp.append(otherPaths[m]);
tmp.append(SEP);
}
// get path string
String result = tmp.toString();
// remove last "/" if path is a file
if (isfile && result.endsWith(SEP)){
result = result.substring(0,result.length()-1);
}
return result;
}
Immutable Strings also prevent concurrency-related issues.
If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2)
into cell G2, here is how I did it.
Range("G2")="=sumifs(B2:B10,A2:A10," & _
"F2)"
To split a line of code, add an ampersand, space and underscore.
You could always use "%p" in order to display 8 bit hex numbers.
int main (void)
{
uint8_t a;
uint32_t b;
a=15;
b=a<<28;
printf("%p", b);
return 0;
}
Output:
0xf0000000
boto3 also has a method for uploading a file directly:
s3 = boto3.resource('s3')
s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')
http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file
These solutions are working in case when target database is blank. In case when both databases already have some data you need something more complicated http://byalexblog.net/merge-sql-databases
You can experiment with the native DB driver for Excel in language/platform of your choice. In Java world, you can try with http://code.google.com/p/sqlsheet/ which provides a JDBC driver for working with Excel sheets directly. Similarly, you can get drivers for the DB technology for other platforms.
However, I can guarantee that you will soon hit a wall with the number of features these wrapper libraries provide. Better way will be to use Apache HSSF/POI or similar level of library but it will need more coding effort.
I have not played with 3D yet, but I know a good place for ressources on 3D for HTML5.
http://www.html5rocks.com/en/gaming
And here is a tutorial on how to create your 3D models with the Three.js
Framework.
http://www.html5rocks.com/en/tutorials/three/intro/
This may help you. Good luck.
T[]
int
constant or int
expression, see n
below)T[]
has one read-only field: length
and an index operator [int]
for reading/writing data at certain indices.1.
String[] array= new String[]{};
what is the use of { } here ?
It initializes the array with the values between { }
. In this case 0 elements, so array.length == 0
and array[0] throws IndexOutOfBoundsException: 0
.
2. what is the diff between
String array=new String[];
andString array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[]
not just String
. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing
String array=new String[10]{};
got error why ?
(Again, ignoring the missing []
before array
) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}
.
Just make up your mind and use one of those - Java thinks.
help me i am confused
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).
You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:
Company: Vodafone
------------------
LSE symbol: VOD
in Google: LON:VOD
in Yahoo: VOD.L
NASDAQ symbol: VOD
in Google: NASDAQ:VOD
in Yahoo: VOD
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
Define the float property of the check element to none:
float: none;
And center the parent element:
text-align: center;
It was the only that works for me.
You can use pandas.cut
:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
...and then value_counts
or groupby
and aggregate size
:
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
By default cut
return categorical
.
Series
methods like Series.value_counts()
will use all categories, even if some categories are not present in the data, operations in categorical.
You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:
static class Extensions
{
public static string GetColumn(this DataRow Row, int Ordinal)
{
return Row.Table.Columns[Ordinal].ColumnName;
}
}
Then call it using:
string MyColumnName = MyRow.GetColumn(5);
I think you can just do
std::string s( MyVector.begin(), MyVector.end() );
where MyVector is your std::vector.
You can use plt.rcParams["font.size"]
for setting font_size
in matplotlib
and also you can use plt.rcParams["font.family"]
for setting font_family
in matplotlib
. Try this example:
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]
plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')
Shortcut by creating AppendString (AS) macro ...
#define AS(A,B) [(A) stringByAppendingString:(B)]
NSString *myString = @"This"; NSString *test = AS(myString,@" is just a test");
Note:
If using a macro, of course just do it with variadic arguments, see EthanB's answer.
My Python version is Python 3.5.2 and the solution proposed in the accepted answer didn't work for me. I've still were given an error
FileNotFoundError: [Errno 2] No such file or directory
when I was running my_script.py
from the terminal. Although it worked fine when I run it through Run/Debug Configurations from PyCharm IDE (PyCharm 2018.3.2 (Community Edition)).
Solution:
instead of using:
my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path
as suggested in the accepted answer, I used:
my_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) + some_rel_dir_path
Explanation:
Changing os.path.dirname(__file__)
to os.path.dirname(os.path.abspath(__file__))
solves the following problem:
When we run our script like that: python3 my_script.py
the __file__
variable has a just a string value of "my_script.py" without path leading to that particular script. That is why method dirname(__file__)
returns an empty string "". That is also the reson why my_path = os.path.abspath(os.path.dirname(__file__)) + some_rel_dir_path
is actually the same thing as my_path = some_rel_dir_path
. Consequently FileNotFoundError: [Errno 2] No such file or directory
is given when trying to use open
method because there is no directory like "some_rel_dir_path".
Running script from PyCharm IDE Running/Debug Configurations worked because it runs a command python3 /full/path/to/my_script.py
(where "/full/path/to" is specified by us in "Working directory" variable in Run/Debug Configurations) instead of justpython3 my_script.py
like it is done when we run it from the terminal.
Hope that will be useful.
This is a simple way of doing it:
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateOnly.format(cal.getTime()));
Thanks it working
here i am done with this by qty field is zero means it shown that cells are in red color
int count = 0;
foreach (DataGridViewRow row in ItemDg.Rows)
{
int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
if (qtyEntered <= 0)
{
ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
ItemDg[1, count].Style.BackColor = Color.Red;
ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory
}
ItemDg[0, count].Value = "0";//assign a default value to quantity enter
count++;
}
}
I found an even better solution to this. Its caused because php is running as another user by default.
so to fix this do
sudo nano /etc/php/7.0/fpm/pool.d/www.conf
then edit the
user = "put user that owns the directories"
group = "put user that owns the directories"
then:
sudo systemctl reload php7.0-fpm
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
Try This, Mine worked this way. To get any data of tag just replace the "a" with the tag you want.
from bs4 import BeautifulSoup as bs
import urllib
url="http://currentaffairs.gktoday.in/month/current-affairs-january-2015"
soup = bs(urllib.urlopen(url))
for link in soup.findAll('a'):
print link.string
Install Windows Mobile Device Center for your architecture. (It will install older versions of .NET if needed.) In USB to PC settings on device uncheck Enable advanced network and tap OK. This worked for me on 2 different Windows 10 PCs.
If you add the extension .SH
to the environment variable PATHEXT
, you will be able to run shell scripts from PowerShell by only using the script name with arguments:
PS> .\script.sh args
If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:
PS> script args
Note: sh.exe or another *nix shell must be associated with the .sh extension.
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
if(typeof theObject['key'] != 'undefined'){
//key exists, do stuff
}
//or
if(typeof theObject.key != 'undefined'){
//object exists, do stuff
}
I'm writing here because no one seems to give the right answer..
I know it's old...
Somebody might question the same thing..
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
this usualy works on Checkboxes and Radio buttons... but, each name should be the same.
<input type="text" value="2" name="pages_title[]">
<input type="text" value="1" name="pages_title[]">
var x = $('input[name="pages_title[]"]').val();
that is "supposed" to get you all the fields in comma separated values. never tried it with text boxes, so cant guarantee it.
as @John commented:
to iterate over them.
$('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });
EDIT: Not allways you need just to answer the OP questions, sometimes you need to teach them better methods. (sorry if that sounds Arrogant)
COMMENT: defining inputs as
<input type="text" value="1" name="pages_title[1]">
<input type="text" value="2" name="pages_title[2]">
is breaking the array, each input has a unique name, therefor, it is not an array anymore.
Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below example to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
This uses javascript, not jquery directly. It might help get you started.
function updateTextInput(val) {_x000D_
document.getElementById('textInput').value=val; _x000D_
}
_x000D_
<input type="range" name="rangeInput" min="0" max="100" onchange="updateTextInput(this.value);">_x000D_
<input type="text" id="textInput" value="">
_x000D_
In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.
snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811
The index of the current array item has been available for some time now via @index:
{{#each array}}
{{@index}}: {{this}}
{{/each}}
For object iteration, use @key instead:
{{#each object}}
{{@key}}: {{this}}
{{/each}}
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningIt's an abstract reference value to a resource, often memory or an open file, or a pipe.
Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers... you use the index for the system API calls, and the system can change the pointer in the table at will.
Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) - the handle should therefore be treated as simply an opaque value meaningful only to the API.
I should add that in any modern operating system, even the so-called "real pointers" are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.
The easiest way to convert a std::string
to a LPWSTR
is in my opinion:
std::string
to a std::vector<wchar_t>
wchar_t
in the vector.std::vector<wchar_t>
has a templated ctor which will take two iterators, such as the std::string.begin()
and .end()
iterators. This will convert each char to a wchar_t
, though. That's only valid if the std::string
contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="shoppingCartParentModule" >
<div ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="name in names">
<p>{{name.username}}</p>
</div>
</div>
</div>
</body>
<script>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [
{product_name: "Product 1", price: 50},
{product_name: "Product 2", price: 20},
{product_name: "Product 3", price: 180}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [
{username: "Nitin"},
{username: "Mukesh"}
];
}
);
angular.module("shoppingCartParentModule",["shoppingCart","namesList"])
</script>
</html>
Try this:
$("input[name='<%=RadioButtonList1.UniqueID %>']:checked").val()
To clear all inputs, including hidden fields, using JQuery:
// Behold the power of JQuery.
$('input').val('');
Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.
Could be something like
$('option').attr('selected', false);
If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. It's using the gender value of the data passed in or uses default.
if(data['gender'] == ''){
$('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
$('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};
import UIKit
extension CALayer {
func makeSnapshot() -> UIImage? {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
return screenshot
}
}
extension UIView {
func makeSnapshot() -> UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) }
} else {
return layer.makeSnapshot()
}
}
}
let image = view.makeSnapshot()
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
@IBOutlet var viewForScreenShot: UIView!
@IBOutlet var screenShotRenderer: UIImageView!
@IBAction func makeViewScreenShotButtonTapped2(_ sender: UIButton) {
screenShotRenderer.image = viewForScreenShot.makeSnapshot()
}
}
Main.storyboard
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_2214957" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Acg-GO-mMN">
<rect key="frame" x="67" y="28" width="240" height="128"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="4Fr-O3-56t">
<rect key="frame" x="72" y="49" width="96" height="30"/>
<constraints>
<constraint firstAttribute="height" constant="30" id="cLv-es-h7Q"/>
<constraint firstAttribute="width" constant="96" id="ytF-FH-gdm"/>
</constraints>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
</subviews>
<color key="backgroundColor" red="0.0" green="0.47843137250000001" blue="1" alpha="0.49277611300000002" colorSpace="custom" customColorSpace="sRGB"/>
<color key="tintColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerX" secondItem="Acg-GO-mMN" secondAttribute="centerX" id="egj-rT-Gz5"/>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerY" secondItem="Acg-GO-mMN" secondAttribute="centerY" id="ymi-Ll-WIV"/>
</constraints>
</view>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="SQq-IE-pvj">
<rect key="frame" x="109" y="214" width="157" height="30"/>
<state key="normal" title="make view screen shot"/>
<connections>
<action selector="makeViewScreenShotButtonTapped2:" destination="BYZ-38-t0r" eventType="touchUpInside" id="KSY-ec-uvA"/>
</connections>
</button>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="CEZ-Ju-Tpq">
<rect key="frame" x="67" y="269" width="240" height="128"/>
<constraints>
<constraint firstAttribute="width" constant="240" id="STo-iJ-rM4"/>
<constraint firstAttribute="height" constant="128" id="tfi-zF-zdn"/>
</constraints>
</imageView>
</subviews>
<color key="backgroundColor" red="0.95941069162436543" green="0.95941069162436543" blue="0.95941069162436543" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="top" secondItem="SQq-IE-pvj" secondAttribute="bottom" constant="25" id="6x1-iB-gKF"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="leading" secondItem="CEZ-Ju-Tpq" secondAttribute="leading" id="LUp-Be-FiC"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="top" secondItem="Acg-GO-mMN" secondAttribute="bottom" constant="58" id="Qu0-YT-k9O"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="Qze-zd-ajY"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="trailing" secondItem="CEZ-Ju-Tpq" secondAttribute="trailing" id="b1d-sp-GHD"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="centerX" secondItem="CEZ-Ju-Tpq" secondAttribute="centerX" id="qCL-AF-Cro"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="u5Y-eh-oSG"/>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="vkx-JQ-pOF"/>
</constraints>
</view>
<connections>
<outlet property="screenShotRenderer" destination="CEZ-Ju-Tpq" id="8QB-OE-ib6"/>
<outlet property="viewForScreenShot" destination="Acg-GO-mMN" id="jgL-yn-8kk"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="32.799999999999997" y="37.331334332833585"/>
</scene>
</scenes>
</document>
final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
.stream()
//depending on how you want to join K and V use different delimiter
.map(entry ->
String.join(":", entry.getKey(),entry.getValue()))
.forEach(System.out::println);
The easiest (but somewhat dirty) way:
String result = "" + a + b + c + d + e
Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.
Open Applicaction -> Accessories -> Terminal
Type commandline as below...
sudo apt-get install openjdk-7-jdk
Type commandline as below...
apt-cache search jdk
(Note: openjdk-7-jdk is symbolically used here. You can choose the JDK version as per your requirement.)
For "JAVA_HOME" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
For "PATH" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export PATH=$PATH:/usr/lib/jvm/java-7-openjdk/bin
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
Check for "open jdk" installation, just type command in "Terminal" as shown below
javac -version
You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass
With these examples you will still get an error when trying to round the number 1.005 the solution is to either use a library like Math.js or this function:
function round(value: number, decimals: number) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
If you wot hard code :)
bool strCanBeInt(std::string string){
for (char n : string) {
if (n != '0' && n != '1' && n != '2' && n != '3' && n != '4' && n != '5'
&& n != '6' && n != '7' && n != '8' && n != '9') {
return false;
}
}
return true;
}
int strToInt(std::string string) {
int integer = 0;
int numInt;
for (char n : string) {
if(n == '0') numInt = 0;
if(n == '1') numInt = 1;
if(n == '2') numInt = 2;
if(n == '3') numInt = 3;
if(n == '4') numInt = 4;
if(n == '5') numInt = 5;
if(n == '6') numInt = 6;
if(n == '7') numInt = 7;
if(n == '8') numInt = 8;
if(n == '9') numInt = 9;
if (integer){
integer *= 10;
}
integer += numInt;
}
return integer;
}
Already @Abubakkar Rangara answered easy way to handle your problem
Alternative is :
String[] result = null;
if(fieldName.endsWith(",")) {
String[] result = fieldName.split(",");
for(int i = 1; i < result.length - 1; i++) {
result[0] = result[0].concat(result[i]);
}
}
You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.
Came across this looking for something else.
While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}"
where # is the starting number of the array element we want to preserve forward:
#!/bin/bash
someVar="${1}"
someOtherVar="${2}"
set -- "${@:3}"
input=${@}
[[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"
echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"
Basically, the set -- "${@:3}"
just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.
May I suggest a php+css solution I used on my site? It's simple and no js problems :)
url to page: <a href="page.php?tab=menu1">link to menu1</a>
<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
<li class="<? if ($tab=='menu1' OR $tab=='menu2')
{
echo "";
}
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
<li class="<? if ($tab=='menu1')
{
echo "active";
}
?>"><a data-toggle="tab" href="#menu1">News</a></li>
<li class="<? if ($tab=='menu2')
{
echo "active";
}
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2')
{
echo "";
}
else {
echo "in active";
}
?>
">
<h3>Prodotti</h3>
<p>Contenuto della pagina, zona prodotti</p>
</div>
<div id="menu1" class="tab-pane fade <? if ($tab=='menu1')
{
echo "in active";
}
?>">
<h3>News</h3>
<p>Qui ci saranno le news.</p>
</div>
<div id="menu2" class="tab-pane fade <? if ($tab=='menu2')
{
echo "in active";
}
?>">
<h3>Gallery</h3>
<p>Qui ci sarà la gallery</p>
</div>
</div>
I have changed the folder hierarchy
/shop/shop_name/base.html To /shop_name/shop/base.html
and then below would work.
{% extends shop_name|add:"/shop/base.html"%}
Now its able to extend the base.html page.
If anyone is targeting yahoo rss feed may benefit from this snippet
<?php
$rssUrl="http://news.yahoo.com/rss/topstories";
//====================================================
$xml=simplexml_load_file($rssUrl) or die("Error: Cannot create object");
//====================================================
$featureRss = array_slice(json_decode(json_encode((array) $xml ), true ), 0 );
/*Just to see what is in it
use this function PrettyPrintArray()
instead of var_dump($featureRss);*/
function PrettyPrintArray($rssData, $level) {
foreach($rssData as $key => $Items) {
for($i = 0; $i < $level; $i++)
echo(" ");
/*if content more than one*/
if(!is_array($Items)){
//$Items=htmlentities($Items);
$Items=htmlspecialchars($Items);
echo("Item " .$key . " => " . $Items . "<br/><br/>");
}
else
{
echo($key . " => <br/><br/>");
PrettyPrintArray($Items, $level+1);
}
}
}
PrettyPrintArray($featureRss, 0);
?>
You may want to run it in your browser first to see what is there and before looping and style it up pretty simple
To grab the first item description
<?php
echo($featureRss['channel']['item'][0]['description']);
?>
<?php
pclose(popen("start /B test.bat", "r")); die();
?>
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
Same happened to me after I changed computer name. To fix that, just locate listener.ora file and replace old computer name with the new one
jQuery
$(function() {
$("td[colspan=3]").find("div").hide();
$("tr").click(function(event) {
var $target = $(event.target);
$target.closest("tr").next().find("div").slideToggle();
});
});
HTML
<table>
<thead>
<tr>
<th>one</th><th>two</th><th>three</th>
</tr>
</thead>
<tbody>
<tr>
<td><p>data<p></td><td>data</td><td>data</td>
</tr>
<tr>
<td colspan="3">
<div>
<table>
<tr>
<td>data</td><td>data</td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable
To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.
I also made some minor changes to HTML and corresponding jQuery.
NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.
Credit to Peter Ajtai
As an alternative, there is always perl:
ps aux | perl -lane 'print $F[3]'
Or, if you want to get all fields starting at field #3 (as stated in one of the answers above):
ps aux | perl -lane 'print @F[3 .. scalar @F]'
You might forgetting to include.. StartUp.cs/Configure()
app.UseSwagger();
Check if you forgot to include, you error must be remove.
[Newtonsoft.Json.JsonObject(Title = "root")]
public class TestMain
this is the only attrib you need to add to get your code working.
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
you should use regular expressions to find all you need:
import re
p = re.compile(r'(\d+)') # a pattern for a number
for line in file :
if num in p.findall(line) :
print line
regular expression will return you all numbers in a line as a list, for example:
>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']
so you don't match '200' or '220' for '20'.
The nature of wanting to include the row where A == 5
and all rows upto but not including the row where A == 8
means we will end up using iloc
(loc
includes both ends of slice).
In order to get the index labels we use idxmax
. This will return the first position of the maximum value. I run this on a boolean series where A == 5
(then when A == 8
) which returns the index value of when A == 5
first happens (same thing for A == 8
).
Then I use searchsorted
to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc
.
i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]
numpy
you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.
def find_between(df, col, v1, v2):
vals = df[col].values
mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
idx = df.index.values
i1, i2 = idx.searchsorted([mx1, mx2])
return df.iloc[i1:i2]
find_between(df, 'A', 5, 8)
First I would recommend you always refer docs before you start a new thing.
We have SchedulerFactory
which schedules Job based on the Cron Expression given to it.
//Create instance of factory
SchedulerFactory schedulerFactory=new StdSchedulerFactory();
//Get schedular
Scheduler scheduler= schedulerFactory.getScheduler();
//Create JobDetail object specifying which Job you want to execute
JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);
//Associate Trigger to the Job
CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");
//Pass JobDetail and trigger dependencies to schedular
scheduler.scheduleJob(jobDetail,trigger);
//Start schedular
scheduler.start();
MyJob.class
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("My Logic");
}
}
You have duplicate style attributes on each element.
style="opacity:0.8"
This certainly does not display on Firefox for me because of this error. If it displays on Chrome, best raise a Chrome bug.
THE CORRECT WAY IS :
UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data
You can use xpath utility. It's installed with the Perl XML-XPath package.
Usage:
/usr/bin/xpath [filename] query
or XMLStarlet. To install it on opensuse use:
sudo zypper install xmlstarlet
or try cnf xml
on other platforms.
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
Agreed with Yuri Tkachenko's answer.
I wanna point this out.
It's a pretty specific scenario. BUT it happens.
When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.
So, make sure it ends with .gif extension
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
Although I already wrote an overview of different kinds of popups, most people just need an Alert.
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
My fuller answer is here.
I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.
~250 ns for
import re
~3 µs for
re.search('[a-zA-Z]', string)
~6 µs for
any(c.isalpha() for c in string)
~850 ns for
string.upper().isupper()
Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.
But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.
Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.
This link is helpful: How to read HTML as XML?
You would have to convert the int into a string.
# This program calculates a workers gross pay
hours = float(raw_input("Enter hours worked: \n"))
rate = float(raw_input("Enter your hourly rate of pay: \n"))
gross = hours * rate
print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $" + str(gross)
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.
The OP's question: What is the difference between the return and exit statement in BASH functions with respect to exit codes?
Firstly, some clarification is required:
A (return|exit) statement is not required to terminate execution of a (function|shell). A (function|shell) will terminate when it reaches the end of its code list, even with no (return|exit) statement.
A (return|exit) statement is not required to pass a value back from a terminated (function|shell). Every process has a built-in variable $?
which always has a numeric value. It is a special variable that cannot be set like "?=1", but it is set only in special ways (see below *).
The value of $? after the last command to be executed in the (called function | sub shell) is the value that is passed back to the (function caller | parent shell). That is true whether the last command executed is ("return [n]"| "exit [n]") or plain ("return" or something else which happens to be the last command in the called function's code.
In the above bullet list, choose from "(x|y)" either always the first item or always the second item to get statements about functions and return, or shells and exit, respectively.
What is clear is that they both share common usage of the special variable $?
to pass values upwards after they terminate.
* Now for the special ways that $?
can be set:
$?
in the terminated function.$?
in the parent shell will be equal to the final value of $?
in the terminated sub shell.$?
depending upon their result. But some don't.$?
with argument, and terminate execution.It is worth noting that $?
can be assigned a value by calling exit in a sub shell, like this:
# (exit 259)
# echo $?
3
<asp:LinkButton ID="mybutton" Text="Link Button" runat="server"></asp:LinkButton>
With Hover effects :
#mybutton
{
background-color: #000;
color: #fff;
font-size: 20px;
width: 150px;
font-weight: bold;
}
#mybutton:hover
{
background-color: #fff;
color: #000;
}
An alternative to overriding VerifyRenderingInServerForm is to remove the grid from the controls collection while you do the render, and then add it back when you are finished before the page loads. This is helpful if you want to have some generic helper method to get grid html because you don't have to remember to add the override.
Control parent = grid.Parent;
int GridIndex = 0;
if (parent != null)
{
GridIndex = parent.Controls.IndexOf(grid);
parent.Controls.Remove(grid);
}
grid.RenderControl(hw);
if (parent != null)
{
parent.Controls.AddAt(GridIndex, grid);
}
Another alternative to avoid the override is to do this:
grid.RenderBeginTag(hw);
grid.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grid.Rows)
{
row.RenderControl(hw);
}
grid.FooterRow.RenderControl(hw);
grid.RenderEndTag(hw);
To check if Zookeeper is accessible. One method is to simply telnet to the proper port and execute the stats command.
root@host:~# telnet localhost 2181
Trying 127.0.0.1...
Connected to myhost.
Escape character is '^]'.
stats
Zookeeper version: 3.4.3-cdh4.0.1--1, built on 06/28/2012 23:59 GMT
Clients:
Latency min/avg/max: 0/0/677
Received: 4684478
Sent: 4687034
Outstanding: 0
Zxid: 0xb00187dd0
Mode: leader
Node count: 127182
Connection closed by foreign host.
You do not need to do this. Here is how to create a co-variance method:
http://www.youtube.com/watch?v=RqAfC4JXd4A
Alternatively you can use statistical analysis package that Excel has.
If you don't want to use any object, you can still use setattr()
inside your current module:
import sys
current_module = module = sys.modules[__name__] # i.e the "file" where your code is written
setattr(current_module, 'variable_name', 15) # 15 is the value you assign to the var
print(variable_name) # >>> 15, created from a string
Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.
For those that want to use reduce, the following will also work:
reduce(set.intersection, list_of_sets)
It is better to use two layer validation for files upload.
First you can check for the mimeType and validate it.
Second you should look to convert the first 4 bytes of your file to hexadecimal and then compare it with the magic numbers. Then it will be a really secure way to check for file validations.
Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).
Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).
Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.
(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)
The "Leader key" is a way of extending the power of VIM's shortcuts by using sequences of keys to perform a command. The default leader key is backslash. Therefore, if you have a map of <Leader>Q, you can perform that action by typing \Q.
/* The algorithm is from the book "Discrete Mathematics and Its
Applications 5th Edition" by Kenneth H. Rosen.
(base^exp)%mod
*/
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int power = base % mod;
for (int i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
Answer if you only want to use for each loop ..
for (WebElement s : options) {
int i = options.indexOf(s);
System.out.println(options.get(i).getText());
}
You can specify USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER
one line before the CMD
or ENTRYPOINT
if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
The only surefire option to find the current session.save_path
value is always to check with phpinfo()
in exactly the environment where you want to find out the session storage directory.
Reason: there can be all sorts of things that change session.save_path
, either by overriding the php.ini
value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');
. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.
This code make clean dataframe:
df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()
without considering this to be a good idea...
select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))
Function
-- Author: bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50))
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int
Select @i=CHARINDEX('.',@NumStr)
if @i=0
begin
set @i=LEN(@NumStr)
Set @Outstr=''
end
else
begin
Set @Outstr=SUBSTRING(@NUmStr,@i,50)
Set @i=@i -1
end
Set @run=0
While @i>0
begin
if @Run=3
begin
Set @Outstr=','+@Outstr
Set @run=0
end
Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr
Set @i=@i-1
Set @run=@run + 1
end
RETURN @OutStr
END
GO
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
implements
means a behaviour will be defined for abstract
methods (except for abstract classes obviously), you define the implementation.
extends
means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends
another interface instead of implementing it.
On a side note, remember that even if an abstract
class can define abstract
methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
For a working doodle/proof of concept of an approach to utilize pure JavaScript along with the familiar and declarative pattern behind XSLT's matching expressions and recursive templates, see https://gist.github.com/brettz9/0e661b3093764f496e36
(A similar approach might be taken for JSON.)
Note that the demo also relies on JavaScript 1.8 expression closures for convenience in expressing templates in Firefox (at least until the ES6 short form for methods may be implemented).
Disclaimer: This is my own code.
Try this so you allow enough time for the first process to start.. else it will spawn 2 processes because the first one is not still running when you run the second one... This can happen if your computer is too fast..
@echo off
start /d iexplore.exe http://google.com
PING 1.1.1.1 -n 1 -w 2000 >NUL
START /d iexplore.exe blablabla
replace blablabla with another address
ORACLE DATABASE example:
select *
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')
Invoking console.time('label')
will record the current time in milliseconds, then later calling console.timeEnd('label')
will display the duration from that point.
The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label:
console.time('test');
//some code
console.timeEnd('test'); //Prints something like that-> test: 11374.004ms
For more information, see Mozilla's developer docs on console.time
.
For my case gulp-ignore was perfect. As option you may pass a function there:
function condition(file) {
// do whatever with file.path
// return boolean true if needed to exclude file
}
And the task would look like this:
var gulpIgnore = require('gulp-ignore');
gulp.task('task', function() {
gulp.src('./**/*.js')
.pipe(gulpIgnore.exclude(condition))
.pipe(gulp.dest('./dist/'));
});
Actually, my problem was about equals and hashcode of my entities. A legacy code can bring a lot of problems, never forget to check it out. All I've done was just keep delete-orphan strategy and correct equals and hashcode.
Another way to make the parser raise the same exception is the following incorrect clause.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
system_user_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The nested SELECT
statement in the IN
clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.
For sake of completeness, the correct syntax is as follows.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The stored procedure of which this query is a portion not only parsed, but returned the expected result.
For client side files, you cannot get a list of files in a user's local directory.
If the user has provided uploaded files, you can access them via their input
element.
<input type="file" name="client-file" id="get-files" multiple />
<script>
var inp = document.getElementById("get-files");
// Access and handle the files
for (i = 0; i < inp.files.length; i++) {
let file = inp.files[i];
// do things with file
}
</script>
You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?
void *myThread()
{
return (void *) 42;
}
and then in main:
printf("%d\n",(int)status);
If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.
this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller
var html2pdf = (function(html2canvas, jsPDF) {
declared in html2pdf.js.
So I added just after the import declarations in my angular-controller this declaration:
declare function html2pdf(html2canvas, jsPDF): any;
then, from a method of my angular controller I'm calling this function:
generate_pdf(){
this.someService.loadContent().subscribe(
pdfContent => {
html2pdf(pdfContent, {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { dpi: 192, letterRendering: true },
jsPDF: { unit: 'in', format: 'A4', orientation: 'portrait' }
});
}
);
}
Hope it helps
I have found that %CD%
gives the path the script was called from and not the path of the script, however, %~dp0
will give the path of the script itself.
The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.
I had this problem to install laravel/lumen.
It can be resolved with the following command:
$ sudo chown -R $USER ~/.composer/
Thanks to everyone that posted solutions, I combined multiple approaches to provide some more advanced disabled
functionality. Here is a gist, and the code is below.
This provides for multiple levels of defense so that Anchors marked as disable actually behave as such.
Using this approach, you get an anchor that you cannot:
- click
- tab to and hit return
- tabbing to it will move focus to the next focusable element
- it is aware if the anchor is subsequently enabled
1. Include this css, as it is the first line of defense. This assumes the selector you use is 'a.disabled'
a.disabled {
pointer-events: none;
cursor: default;
}
2. Next, instantiate this class such as (with optional selector):
$ ->
new AnchorDisabler()
Here is the coffescript class:
class AnchorDisabler
constructor: (selector = 'a.disabled') ->
$(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)
isStillDisabled: (ev) =>
### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
target = $(ev.target)
return true if target.hasClass('disabled')
return true if target.attr('disabled') is 'disabled'
return false
onFocus: (ev) =>
### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
return unless @isStillDisabled(ev)
focusables = $(':focusable')
return unless focusables
current = focusables.index(ev.target)
next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))
next.focus() if next
onClick: (ev) =>
# disabled could be dynamically removed
return unless @isStillDisabled(ev)
ev.preventDefault()
return false
onKeyup: (ev) =>
# 13 is the js key code for Enter, we are only interested in disabling that so get out fast
code = ev.keyCode or ev.which
return unless code is 13
# disabled could be dynamically removed
return unless @isStillDisabled(ev)
ev.preventDefault()
return false
This is what css is for... HTML doesn't allow for unequal padding. When you say that you don't want to use style sheets, does this mean you're OK with inline css?
<table>
<tr>
<td style="padding: 5px 10px 5px 5px;">Content</td>
<td style="padding: 5px 10px 5px 5px;">Content</td>
</tr>
</table>
You could also use JS to do this if you're desperate not to use stylesheets for some reason.
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
I used following code:
The reason I used hashCode was because I was getting some garbage values appended to the ip address when I used getHostAddress
. But hashCode
worked really well for me as then I can use Formatter to get the ip address with correct formatting.
Here is the example output :
1.using getHostAddress
: ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
2.using hashCode
and Formatter
: ***** IP=238.194.77.212
As you can see 2nd methods gives me exactly what I need.
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ip = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i(TAG, "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
First you have to add an ArrayList to the Map
ArrayList<Item> al = new ArrayList<Item>();
Items.add("theKey", al);
then you can add an item to the ArrayLIst that is inside the Map like this:
Items.get("theKey").add(item); // item is an object of type Item
SELECT MIN(Date) AS Date FROM tbl_Employee /*To get First date Of Employee*/
You can see a complete example using java 8, recursion and streams -> Dijkstra algorithm with java
Here is the max value and the indexes it appears at:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
... d[x].append(i)
...
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]
Later: for the satisfaction of @SilentGhost
>>> from itertools import takewhile
>>> import heapq
>>>
>>> def popper(heap):
... while heap:
... yield heapq.heappop(heap)
...
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>>
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]
Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'")
the way you wanted.
There are jQuery plugins to that effect, like json2xml.
Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.
It should be at least this:
public function login(Request $loginCredentials){
$data = $loginCredentials->all();
return $data['username'];
}
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
You can do this by selecting every element of the class that is the sibling of the same class and inverting it, which will select pretty much every element on the page, so then you have to select by the class again.
eg:
<style>
:not(.bar ~ .bar).bar {
color: red;
}
<div>
<div class="foo"></div>
<div class="bar"></div> <!-- Only this will be selected -->
<div class="foo"></div>
<div class="bar"></div>
<div class="foo"></div>
<div class="bar"></div>
</div>
Even if it is an old thread, maybe some is interested.
If it is an option to you to use the same method inside the same class and archive different return types, use generics: Oracle Lesson Generics
Simple example for generic value holder class:
class GenericValue<T> {
private T myValue;
public GenericValue(T myValue) { this.myValue = myValue; }
public T getVal() { return myValue; }
}
And use it like this:
public class ExampleGenericValue {
public static void main(String[] args) {
GenericValue<Integer> intVal = new GenericValue<Integer>(10);
GenericValue<String> strVal = new GenericValue<String>("go on ...");
System.out.format("I: %d\nS: %s\n", intVal.getVal(), strVal.getVal());
}
}
... will result in the following output:
I: 10
S: go on ...
After some searching, I was able to find the information_schema.routines
table and the information_schema.parameters
tables. Using those, one can construct a query for this purpose. LEFT JOIN, instead of JOIN, is necessary to retrieve functions without parameters.
SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
WHERE routines.specific_schema='my_specified_schema_name'
ORDER BY routines.routine_name, parameters.ordinal_position;
If you order a vector x
, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.
x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile
Restarting VS2012 should fix the problem.
You're missing the return statement because if your list size is 0, the for loop will never execute, thus the if will never run, and thus you will never return.
Move the if statement out of the loop.
We can also use logging to print data on the console.
Example:
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
I just wanted to chime in that I hit this after updating Android Studio components.
What worked for me was to open gradle-wrapper.properties and update the gradle version used. As of now for my projects the line reads:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
Use mvn --help
and you can see the options list.
There is an option like -nsu,--no-snapshot-updates Suppress SNAPSHOT updates
So use command mvn install -nsu
can force compile with local repository.
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
You either haven't selected a CPU/ABI target in the dropdown below the target, or you haven't installed a system image. Open your SDK manager and ensure that you've installed ARM EABI v7a System Image
under the Android 4.2 section.
<role rolename="tomcat"/>
<role rolename="manager-gui"/>
<role rolename="admin-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<user username="admin" password="admin" roles="tomcat,manager-gui,admin-gui,manager-script,manager-jmx"/>
Close all the session, once closed, ensure open the URL in incognito mode login again and it should start working
I tested 3 methods to do that...
Method1:
const FriendCard:any = require('./../pages/FriendCard')
Method2:
import * as FriendCard from './../pages/FriendCard';
Method3:
if you can find something like this in tsconfig.json:
{ "compilerOptions": { ..., "allowJs": true }
then you can write:
import FriendCard from './../pages/FriendCard';
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
This adds custom text at the beginning of your file:
echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv
You just have to replace the break
with a return
statement.
Think of the code inside the Foreach-Object
as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue
, break
, ...).
Start MySQL Workbench, then Server -> Options File and look at bottom of the window; it will say something like "Configuration File: C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"
(And note the subtle difference between "ProgramData" and "Program Files" - easy to gloss over if you're looking for a quick answer.)
When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”
For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
In another way,
If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”
There won't be any "merge commit" in fast-forwarding merge.
Console.WriteLine("hoeveel keer moet je de zin schrijven?");
int aantal = Convert.ToInt32(Console.ReadLine());
int counter = 0;
while ( counter <= aantal)
{
Console.WriteLine("Ik mag geen stiften gooien");
counter = counter + 1;
The best and most accurate method I found was to download the bfg.jar file: https://rtyley.github.io/bfg-repo-cleaner/
Then run the commands:
git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository
If you want to delete files then use the delete-files option instead:
java -jar bfg.jar --delete-files *.pyc
Try the above which will run with any list type.
public DataTable ListToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
To avoid escaping lot of characters:
echo <<<MYSCRIPT
... script here...
MYSCRIPT;
or just turn off php parsing for a while:
?>
...your script here
<?php
The solution is increasing the values given the wait_timeout
and the connect_timeout
parameters in your options file, under the [mysqld]
tag.
I had to recover a 400MB mysql backup and this worked for me (the values I've used below are a bit exaggerated, but you get the point):
[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE
connect_timeout = 1000000
net_write_timeout = 1000000
wait_timeout = 1000000
max_allowed_packet = 1024M
interactive_timeout = 1000000
net_buffer_length = 200M
net_read_timeout = 1000000
set GLOBAL delayed_insert_timeout=100000
Blockquote
Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY
format.
If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD
format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC()
.
You could use this jQuery plugin waitForImage or you could put you images into an hidden div or (width:0 and height:0) and use onload event on images.
If you only have like 2-3 images you can bind events and trigger them in a chain so after every image you can do some code.
As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.
I currently also have that requirement of waiting for some services to be up and running before others start. Also read the suggestions here and on some other places. But most of them require that the docker-compose.yml
some how has to be changed a bit.
So I started working on a solution which I consider to be an orchestration layer around docker-compose itself and I finally came up with a shell script which I called docker-compose-profile
.
It can wait for tcp connection to a certain container even if the service does not expose any port to the host directy. The trick I am using is to start another docker container inside the stack and from there I can (usually) connect to every service (as long no other network configuration is applied).
There is also waiting method to watch out for a certain log message.
Services can be grouped together to be started in a single step before another step will be triggered to start.
You can also exclude some services without listing all other services to start (like a collection of available services minus some excluded services).
This kind of configuration can be bundled to a profile.
There is a yaml configuration file called dcp.yml
which (for now) has to be placed aside your docker-compose.yml file.
For your question this would look like:
command:
aliases:
upd:
command: "up -d"
description: |
Create and start container. Detach afterword.
profiles:
default:
description: |
Wait for rabbitmq before starting worker.
command: upd
steps:
- label: only-rabbitmq
only: [ rabbitmq ]
wait:
- 5@tcp://rabbitmq:5432
- label: all-others
You could now start your stack by invoking
dcp -p default upd
or even simply by
dcp
as there is only a default profile to run up -d
on.
There is a tiny problem. My current version does not (yet) support special waiting condition like the ony You actually need. So there is no test to send a message to rabbit.
I have been already thinking about a further waiting method to run a certain command on host or as a docker container. Than we could extend that tool by something like
...
wait:
- service: rabbitmq
method: container
timeout: 5
image: python-test-rabbit
...
having a docker image called python-test-rabbit
that does your check.
The benefit then would be that there is no need anymore to bring the waiting part to your worker. It would be isolated and stay inside the orchestration layer.
May be someone finds this helpful to use. Any suggestions are very welcome.
You can find this tool at https://gitlab.com/michapoe/docker-compose-profile
You can use php for making multi-page website.
<?
php include 'header.php';
?>
(Above code will dump all html code before this)Your site body content.
The ensurepip
module was added in version 3.4 and then backported to 2.7.9.
So make sure your Python version is at least 2.7.9 if using Python 2, and at least 3.4 if using Python 3.
I tried with the following code snippet. It worked well. :-)
com.sun.org.apache.xml.internal.security.utils.Base64.encode("The string to encode goes here");
After spending a lot of time with this issue, Here is what I got working
$state.go('stateName',params,{
// prevent the events onStart and onSuccess from firing
notify:false,
// prevent reload of the current state
reload:false,
// replace the last record when changing the params so you don't hit the back button and get old params
location:'replace',
// inherit the current params on the url
inherit:true
});
The first preserves the original stacktrace:
try { ... }
catch
{
// Do something.
throw;
}
The second allows you to change the type of the exception and/or the message and other data:
try { ... } catch (Exception e)
{
throw new BarException("Something broke!");
}
There's also a third way where you pass an inner exception:
try { ... }
catch (FooException e) {
throw new BarException("foo", e);
}
I'd recommend using:
This is function with inverted option
It will return:
function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){
$value = $newNumber - $oldNumber;
$change = '';
$sign = '';
$result = 0.00;
if ( $invert ) {
if ( $value > 0 ) {
// going UP
$change = 'up';
$sign = '+';
if ( $oldNumber > 0 ) {
$result = ($newNumber / $oldNumber) * 100;
} else {
$result = 100.00;
}
}elseif ( $value < 0 ) {
// going DOWN
$change = 'down';
//$value = abs($value);
$result = ($oldNumber / $newNumber) * 100;
$result = abs($result);
$sign = '-';
}else {
// no changes
}
}else{
if ( $newNumber > $oldNumber ) {
// increase
$change = 'up';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
}else{
$result = 100.00;
}
$sign = '+';
}elseif ( $oldNumber > $newNumber ) {
// decrease
$change = 'down';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
} else {
$result = 100.00;
}
$sign = '-';
}else{
// no change
}
$result = abs($result);
}
$result_formatted = number_format($result, 2);
if ( $invert ) {
if ( $change == 'up' ) {
$change = 'down';
}elseif ( $change == 'down' ) {
$change = 'up';
}else{
//
}
if ( $sign == '+' ) {
$sign = '-';
}elseif ( $sign == '-' ) {
$sign = '+';
}else{
//
}
}
if ( $format ) {
$formatted = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
} else{
$formatted = $result_formatted;
}
return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
Why not take a collection, likely a Map such as a HashMap, and use it as the nucleus of your own combo box model class that implements the ComboBoxModel interface? Then you could access your combo box's items easily via their key Strings rather than ints.
For instance...
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
public class MyComboModel<K, V> implements ComboBoxModel {
private Map<K, V> nucleus = new HashMap<K, V>();
// ... any constructors that you want would go here
public void put(K key, V value) {
nucleus.put(key, value);
}
public V get(K key) {
return nucleus.get(key);
}
@Override
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
// ... plus all the other methods required by the interface
}
Try this, it's pure Ruby so there's no need to add any peripheral frameworks
if @players.include?(p.name) == false do
...
end
I was struggling with a similar logic for a few days, and after checking several forums and Q&A boards to little avail it turns out the solution was actually pretty simple.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(time);
String formattedTime = output.format(d);
This works. You have to use two SimpleDateFormats, one for input and one for output, but it will give you just what you are wanting.
When building a GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents
.
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
The only trick is that most web services need +
character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded
specification). But URLComponents
will not percent escape it. Apple contends that +
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded
requests and really should not be passed unescaped.
Apple acknowledges that we have to percent escaping the +
characters, but advises that we do it manually:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a +
character and you have a server that interprets them as spaces.
So, combining that with your sendRequest
routine, you end up with something like:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
(200 ..< 300) ~= response.statusCode, // is statusCode 2XX
error == nil else { // was there no error, otherwise ...
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
And you'd call it like:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
Personally, I'd use JSONDecoder
nowadays and return a custom struct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.
See previous revision of this answer for Swift 2 and manual percent escaping renditions.
You can't. A DateTime in .NET always have a time, defaulting to 00:00:00:000. The Date property of a DateTime is also a DateTime (!), thus having a time defaulting to 00:00:00:000 as well.
This is a shortage in the .NET Framework, and it could be argued that DateTime in .NET violates the Single Responsibility Principle.
XML file:
<Spinner
android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Java file:
public class SpinnerExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] arraySpinner = new String[] {
"1", "2", "3", "4", "5", "6", "7"
};
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
}
Just follow two steps for clicking a any button using code.
focus the button or element which you want to click
WebBrowser1.Document.GetElementById("place id here").Focus()
simulate mouse click using this following code
SendKeys.Send("{ENTER}")
if (listView1.Items.Count > 0)
{
listView1.Items[0].Selected = true;
listView1.Select();
}
list items do not appear selected unless the control has the focus (or you set the HideSelection
property to false)
if ($string =~ m/something/) {
# Do work
}
Where something
is a regular expression.
new ES6:
'import' should be used with 'export' key words to share variables/arrays/objects between js files:
export default myObject;
//....in another file
import myObject from './otherFile.js';
old skool:
'require' should be used with 'module.exports'
module.exports = myObject;
//....in another file
var myObject = require('./otherFile.js');
Easy!
Just split the incoming address list on the ";" character, and add them to the mail message:
foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
mailMessage.To.Add(address);
}
In this example, addresses
contains "[email protected];[email protected]
".
Perhaps you should divide your content like such using floats:
<div style="overflow: auto;">
<div style="float: left; width: 600px;">
Here is my content!
</div>
<div style="float: right; width: 300px;">
Here is my sidebar!
</div>
</div>
Notice the overflow: auto;
, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div
to have an overflow: auto
(or overflow: hidden
) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.
Given your container width 600px.
If you want only bigger images than that to fit inside, add: CSS:
#ImageContainer img {
max-width: 600px;
}
If you want ALL images to take the avaiable (600px) space:
#ImageContainer img {
width: 600px;
}
The ASP.NET Web API has replaced the WCF Web API previously mentioned.
I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".
Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.
Here's how your example would look when implemented using the ASP.NET Web API Client Library:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsoleProgram
{
public class DataObject
{
public string Name { get; set; }
}
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json";
private string urlParameters = "?api_key=123";
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
// Make any other calls using HttpClient here.
// Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}
}
}
If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?
For more details, including other examples, see Call a Web API From a .NET Client (C#)
This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
in iis manager click directory to protect.
choose authorization rules.
add deny anonymous users rule.
add allow all users rule.
go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.
the directory is now protected. only people with user accounts can access the folder over the web.
In windows
$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);
for Angular 8 - a mixture of null checking and @ViewChild
static: false
hackery
for a paging control waiting for async data
@ViewChild(MatPaginator, { static: false }) set paginator(paginator: MatPaginator) {
if(!paginator) return;
paginator.page.pipe(untilDestroyed(this)).subscribe(pageEvent => {
const updated: TSearchRequest = {
pageRef: pageEvent.pageIndex,
pageSize: pageEvent.pageSize
} as any;
this.dataGridStateService.alterSearchRequest(updated);
});
}
I use div by adding contenteditable true instead of using textarea.
Hope can help you.
$("#your_textarea").on('keydown', function(e){//textarea keydown events
if(e.key == "Enter")
{
if(e.shiftKey)//jump new line
{
// do nothing
}
else // do sth,like send message or else
{
e.preventDefault();//cancell the deafult events
}
}
})
For me this worked:
INSERT INTO [MyTable]
([ValidFrom]
,[ValidTo])
VALUES
('2020-01-27 14:54:11.000'
,'2023-01-27 14:52:50.000')
You have to set the default option by passing a third argument.
{{ Form::select('myselect', [1, 2], 2, ['id' => 'myselect']) }}
You can read the documentation here.
Try this:
body
{
background:url("images/plaid.jpg") no-repeat fixed center;
}
jsfiddle example: http://jsfiddle.net/Q9Zfa/
This can also happen when the redirect_uri
submitted with the https://www.facebook.com/dialog/oauth request is not present in the list of Valid OAuth redirect URIs under:
After much trial and error, when I added the redirect_uri
that I was using (https://www.facebook.com/connect/login_success.html in my case), I suddenly got to the step past this error.
200,300, 400, 500 are all very generic. If you want generic, 400 is OK.
422 is used by an increasing number of APIs, and is even used by Rails out of the box.
No matter which status code you pick for your API, someone will disagree. But I prefer 422 because I think of '400 + text status' as too generic. Also, you aren't taking advantage of a JSON-ready parser; in contrast, a 422 with a JSON response is very explicit, and a great deal of error information can be conveyed.
Speaking of JSON response, I tend to standardize on the Rails error response for this case, which is:
{
"errors" :
{
"arg1" : ["error msg 1", "error msg 2", ...]
"arg2" : ["error msg 1", "error msg 2", ...]
}
}
This format is perfect for form validation, which I consider the most complex case to support in terms of 'error reporting richness'. If your error structure is this, it will likely handle all your error reporting needs.
use the val() function
Good article here: Cross-domain communication with iframes
Also you can directly set document.domain the same in both frames (even
document.domain = document.domain;
code has sense because resets port to null), but this trick is not general-purpose.
curl -sS https://getcomposer.org/installer | sudo php
sudo mv composer.phar /usr/local/bin/composer
export PATH="$HOME/.composer/vendor/bin:$PATH"
If you have installed by this way simply
Delete composer.phar from where you've putted it.
In this case path will be /usr/local/bin/composer
Note: There is no need to delete the exported path.
Use the NotificationManager to cancel your notification. You only need to provide your notification id
mNotificationManager.cancel(YOUR_NOTIFICATION_ID);
also check this link See Developer Link
Technically both answers above are correct, but since you are setting your ImageView to fill_parent
instead of wrap_content
, the image within is not centered, but the ImageView itself is.
Give your ImageView the attributes:
android:scaleType="centerInside"
android:gravity="center"
The scaleType is really only necessary in this case if the image exceeds the size of the ImageView. You may also want different scaleTypes. In conclusion, android:gravity
is what you're looking for in this case, but if your ImageView is set to wrap_content
, you should set the ImageView's gravity (android:layout_gravity
) to be centered within the parent.
Are you talking about getchar
function?
In python the with
keyword is used when working with unmanaged resources (like file streams). It is similar to the using
statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally
blocks.
From Python Docs:
The
with
statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.The
with
statement is a control-flow structure whose basic structure is:with expression [as variable]: with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has
__enter__()
and__exit__()
methods).
Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with
with using
.
The netdom.exe command line program can be used. This is available from the Windows XP Support Tools or Server 2003 Support Tools (both on the installation CD).
Usage guidelines here
Try to use it this way:
let current_time = moment().format("HH:mm")
You need to use a pointer to a member function, not just a pointer to a function.
class A {
int f() { return 1; }
public:
int (A::*x)();
A() : x(&A::f) {}
};
int main() {
A a;
std::cout << (a.*a.x)();
return 0;
}
you may check this http://coenraets.org/blog/2011/10/sample-application-with-jquery-mobile-and-phonegap/ and you can also check http://mobile.tutsplus.com/category/tutorials/phonegap/ which provide you with a good sample
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);