I tried a lot of things as mentioned in the above answers. The SQLmapper was very confusing as to where to put it. Non managed POJOs only were a problem. I was trying various ways and one easy way I got it worked was as usual. I am using hibernate-jpa-2.1.
List<TestInfo> testInfoList = factory.createNativeQuery(QueryConstants.RUNNING_TEST_INFO_QUERY)
.getResultList();
The only thing to take care was that POJO has same member variable names as that of the query ( all in lowercase). And apparently I didn't even need to tell the target class along with query as we do with TypedQueries in JPQL.
TestInfo.class
@Setter
@Getter
@NoArgsConstructor
@ToString
public class TestInfo {
private String emailid;
private Long testcount;
public TestInfo(String emailId, Long testCount) {
super();
this.emailid = emailId;
this.testcount = testCount;
}
}
For people out there asking how to setup proxy server in chrome which needs authentication should follow these steps.
I think you are trying to run an emulator based on x86. I got the same error when I just download the HAXM under Extras category of Android SDK Manager. Actually, you need install it. Go to the directory of extras and run the installation of HAXM. Hope this will solve your problem.
You can use an iterator.
typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
// iterator->first = key
// iterator->second = value
// Repeat if you also want to iterate through the second map.
}
I created a simple templated function, Sequence()
, for generating sequences of numbers. The functionality follows the seq()
function in R (link). The nice thing about this function is that it works for generating a variety of number sequences and types.
#include <iostream>
#include <vector>
template <typename T>
std::vector<T> Sequence(T min, T max, T by) {
size_t n_elements = ((max - min) / by) + 1;
std::vector<T> vec(n_elements);
min -= by;
for (size_t i = 0; i < vec.size(); ++i) {
min += by;
vec[i] = min;
}
return vec;
}
Example usage:
int main()
{
auto vec = Sequence(0., 10., 0.5);
for(auto &v : vec) {
std::cout << v << std::endl;
}
}
The only caveat is that all of the numbers should be of the same inferred type. In other words, for doubles or floats, include decimals for all of the inputs, as shown.
Updated: June 14, 2018
You can use a backslash at the end of a line.
So this:
a\
b\
c
will then look like:
a
b
c
Notice that there is no backslash at the end of the last line (after the 'c' character).
First I need to say that your code,
MyClass *myclass;
myclass->DoSomething();
will cause an undefined behavior. Because the pointer "myclass" isn't pointing to any "MyClass" type objects.
Here I have three suggestions for you:-
option 1:- You can simply declare and use a MyClass type object on the stack as below.
MyClass myclass; //allocates memory for the object "myclass", on the stack.
myclass.DoSomething();
option 2:- By using the new operator.
MyClass *myclass = new MyClass();
Three things will hapen here.
i) Allocates memory for the "MyClass" type object on the heap.
ii) Allocates memory for the "MyClass" type pointer "myclass" on the stack.
iii) pointer "myclass" points to the memory address of "MyClass" type object on the heap
Now you can use the pointer to access member functions of the object after dereferencing the pointer by "->"
myclass->DoSomething();
But you should free the memory allocated to "MyClass" type object on the heap, before returning from the scope unless you want it to exists. Otherwise it will cause a memory leak!
delete myclass; // free the memory pointed by the pointer "myclass"
option 3:- you can also do as below.
MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.
Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope.
So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.
The answer above was meant for Python 2. If you're using Python 3, here is the code.
>>> import socket
>>> print(socket.gethostbyname('google.com'))
8.8.8.8
>>>
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
In Android Studio 1.1, the simplest way is to open your project manifest file
, then point to each part of the package name
that you want to change it and press
SHIFT + F6 , then choose rename package
and write the new name in the dialog box. That's all.
Runtime describes software/instructions that are executed while your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.
Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.
You are correct that runtime code is library code, but library code is a more general term, describing the code produced by any library. Runtime code is specifically the code required to implement the features of the language itself.
The string
constants may be what you want. (docs)
>>> import string >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
If you want all printable characters:
>>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.
This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.
On Ubuntu, placed your id_rsa
and id_rsa.pub
files in /var/lib/jenkins/.ssh
Make Jenkins own them
sudo chown -R jenkins /var/lib/jenkins/.ssh/
Make sure that Jenkins key is added as deploy key with RW access in GitHub (or similar) - use the id_rsa.pub
key for this.
Now everything should jive with the SCM Sync Plugin.
It's very simple:
$(":button:contains('Authenticate')").prop("disabled", true).addClass("ui-state-disabled");
@Namphibian's suggestion helped me a lot...
went a little further though and added columns and views to the script
just enter your schema's name below and it will do the rest
-- set your table name here
SET @MY_SCHEMA = "";
-- tables
SELECT DISTINCT
CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=@MY_SCHEMA
AND TABLE_TYPE="BASE TABLE"
UNION
-- table columns
SELECT DISTINCT
CONCAT("ALTER TABLE ", C.TABLE_NAME, " CHANGE ", C.COLUMN_NAME, " ", C.COLUMN_NAME, " ", C.COLUMN_TYPE, " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.COLUMNS as C
LEFT JOIN INFORMATION_SCHEMA.TABLES as T
ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLLATION_NAME is not null
AND C.TABLE_SCHEMA=@MY_SCHEMA
AND T.TABLE_TYPE="BASE TABLE"
UNION
-- views
SELECT DISTINCT
CONCAT("CREATE OR REPLACE VIEW ", V.TABLE_NAME, " AS ", V.VIEW_DEFINITION, ";") as queries
FROM INFORMATION_SCHEMA.VIEWS as V
LEFT JOIN INFORMATION_SCHEMA.TABLES as T
ON V.TABLE_NAME = T.TABLE_NAME
WHERE V.TABLE_SCHEMA=@MY_SCHEMA
AND T.TABLE_TYPE="VIEW";
If you want a simple no-jquery solution to prevent all transitions:
body.no-transition * {
transition: none !important;
}
document.body.classList.add("no-transition");
// do your work, and then either immediately remove the class:
document.body.classList.remove("no-transition");
// or, if browser rendering takes longer and you need to wait until a paint or two:
setTimeout(() => document.body.classList.remove("no-transition"), 1);
// (try changing 1 to a larger value if the transition is still applying)
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
public static void main(String... args) throws IOException {
final int runs = 5 * 1000 * 1000;
final ServerSocket ss = new ServerSocket(0);
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket serverConn = ss.accept();
String line = "Hello World!\n";
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
for (int count = 0; count < runs; count++)
br.write(line);
serverConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Socket conn = new Socket("localhost", ss.getLocalPort());
long start = System.nanoTime();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
List<String> responseData = new ArrayList<String>();
while ((line = in.readLine()) != null) {
responseData.add(line);
}
long time = System.nanoTime() - start;
System.out.println("Average time to read a line was " + time / runs + " ns.");
conn.close();
ss.close();
}
prints
Average time to read a line was 158 ns.
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
Still prints
Average time to read a line was 159 ns.
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.
I am not about your PHP configuration but until PHP 5.2.6 , PHP does have some problem with SOAP client :
It's not quite what you asked for, but
git log --graph --simplify-by-decoration --pretty=format:'%d' --all
does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration
is the big trick here for limiting the refs shown.
I use a similar command to view my log. I've been able to completely replace my gitk
usage with it:
git log --graph --oneline --decorate --all
I use it by including these aliases in my ~/.gitconfig file:
[alias]
l = log --graph --oneline --decorate
ll = log --graph --oneline --decorate --branches --tags
lll = log --graph --oneline --decorate --all
Edit: Updated suggested log command/aliases to use simpler option flags.
I checked the source code of TaskOfResult.cs
(Source code of TaskOfResult.cs):
If Task
is not completed, Task.Result
will call Task.Wait()
method in getter
.
public TResult Result
{
get
{
// If the result has not been calculated yet, wait for it.
if (!IsCompleted)
{
// We call NOCTD for two reasons:
// 1. If the task runs on another thread, then we definitely need to notify that thread-slipping is required.
// 2. If the task runs inline but takes some time to complete, it will suffer ThreadAbort with possible state corruption.
// - it is best to prevent this unless the user explicitly asks to view the value with thread-slipping enabled.
//#if !PFX_LEGACY_3_5
// Debugger.NotifyOfCrossThreadDependency();
//#endif
Wait();
}
// Throw an exception if appropriate.
ThrowIfExceptional(!m_resultWasSet);
// We shouldn't be here if the result has not been set.
Contract.Assert(m_resultWasSet, "Task<T>.Result getter: Expected result to have been set.");
return m_result;
}
internal set
{
Contract.Assert(m_valueSelector == null, "Task<T>.Result_set: m_valueSelector != null");
if (!TrySetResult(value))
{
throw new InvalidOperationException(Strings.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
}
If We call GetAwaiter
method of Task
, Task
will wrapped TaskAwaiter<TResult>
(Source code of GetAwaiter()), (Source code of TaskAwaiter) :
public TaskAwaiter GetAwaiter()
{
return new TaskAwaiter(this);
}
And If We call GetResult()
method of TaskAwaiter<TResult>
, it will call Task.Result
property, that Task.Result
will call Wait()
method of Task
( Source code of GetResult()):
public TResult GetResult()
{
TaskAwaiter.ValidateEnd(m_task);
return m_task.Result;
}
It is source code of ValidateEnd(Task task)
( Source code of ValidateEnd(Task task) ):
internal static void ValidateEnd(Task task)
{
if (task.Status != TaskStatus.RanToCompletion)
HandleNonSuccess(task);
}
private static void HandleNonSuccess(Task task)
{
if (!task.IsCompleted)
{
try { task.Wait(); }
catch { }
}
if (task.Status != TaskStatus.RanToCompletion)
{
ThrowForNonSuccess(task);
}
}
This is my conclusion:
As can be seen GetResult()
is calling TaskAwaiter.ValidateEnd(...)
, therefore Task.Result
is not same GetAwaiter.GetResult()
.
I think GetAwaiter().GetResult()
is a beter choice instead of .Result
because it don't wrap exceptions.
I read this at page 582 in C# 7 in a Nutshell (Joseph Albahari & Ben Albahari) book
If an antecedent task faults, the exception is re-thrown when the continuation code calls
awaiter.GetResult()
. Rather than callingGetResult
, we could simply access the Result property of the antecedent. The benefit of callingGetResult
is that if the antecedent faults, the exception is thrown directly without being wrapped inAggregateException
, allowing for simpler and cleaner catch blocks.
Source: C# 7 in a Nutshell's page 582
HashSet implementations are, of course, much much faster -- less overhead because there's no ordering. A good analysis of the various Set implementations in Java is provided at http://java.sun.com/docs/books/tutorial/collections/implementations/set.html.
The discussion there also points out an interesting 'middle ground' approach to the Tree vs Hash question. Java provides a LinkedHashSet, which is a HashSet with an "insertion-oriented" linked list running through it, that is, the last element in the linked list is also the most recently inserted into the Hash. This allows you to avoid the unruliness of an unordered hash without incurring the increased cost of a TreeSet.
To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.
This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT
Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field]
, because they can be altered.
Laravel for example uses [parent table]_[referencing field]_foreign
as naming convention. You can show the names of the foreign keys by using this query, as shown here:
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';
Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.
You should use something like this:
<div style="text-align:center">
<input type="submit" />
</div>
Or you could use something like this. By giving the element a width and specifying auto
for the left and right margins the element will center itself in its parent.
<input type="submit" style="width: 300px; margin: 0 auto;" />
You can accomplish this via Maps. Something like
Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");
But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do
class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);
No need to import any library:
>>> bytearray.fromhex("7061756c").decode()
'paul'
To be complete, this
can also be used to refer to the outer object
class Outer {
class Inner {
void foo() {
Outer o = Outer.this;
}
}
}
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
Example 2 on w3schools shows what you are trying to achieve.
<?php header("Content-type:application/pdf"); // It will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // The PDF source is in original.pdf readfile("original.pdf"); ?>
Also remember that,
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)
DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.
If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:
SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
foreach (DataRow dr in dt.Rows)
{
MessageBox.Show(dr["Column1"].ToString());
}
To read a specific cell in a row:
int rowNum // row number
string columnName = "DepartureTime"; // database table column name
dt.Rows[rowNum][columnName].ToString();
It is important to keep in mind that let is lazy evaluated and not putting side-effect methods in it otherwise you would not be able to change from let to before(:each) easily. You can use let! instead of let so that it is evaluated before each scenario.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p>
tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
_x000D_
document.getElementById('output').innerHTML = lengthOfName;_x000D_
};
_x000D_
<p id="output"></p>
_x000D_
Try the below query
CREATE TABLE card_types (
card_type_id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL default '',
PRIMARY KEY (card_type_id),
) ENGINE = MyISAM ;
I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.
if ($handle = opendir('.')) {
$result = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
$result [date('Y-m-d H:i:s',filemtime($file)).$file] =
"<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
closedir($handle);
krsort($result);
echo implode('', $result);
}
Initialize the current cursor. Use it to get the position of X and Y
this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;
Old thread I know.......
Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.
I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).
Before you add any drag or drop operation to an event you have to call this function first:
simulateTouchEvents(<object>);
You can also block all components/children for input or to speed up event handling by using the following syntax:
simulateTouchEvents(<object>, true); // ignore events on childs
Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).
function simulateTouchEvents(oo,bIgnoreChilds)
{
if( !$(oo)[0] )
{ return false; }
if( !window.__touchTypes )
{
window.__touchTypes = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
}
$(oo).bind('touchstart touchmove touchend', function(ev)
{
var bSame = (ev.target == this);
if( bIgnoreChilds && !bSame )
{ return; }
var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
e = ev.originalEvent;
if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type] )
{ return; } //allow multi-touch gestures to work
var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;
if( b || window.__touchInputs[ev.target.tagName] )
{ return; } //allow default clicks to work (and on inputs)
// https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(newEvent);
e.preventDefault();
ev.stopImmediatePropagation();
ev.stopPropagation();
ev.preventDefault();
});
return true;
};
What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.
Result: Every element on a draggable element is still working.
Happy coding, greetz, Erwin Haantjes
Try using setAttribute on the result:
result.setAttribute("class","red");
Change ng-disabled="!contractTypeValid"
to [disabled]="!contractTypeValid"
Your root
account, and this statement applies to any account, may only have been added with localhost access (which is recommended).
You can check this with:
SELECT host FROM mysql.user WHERE User = 'root';
If you only see results with localhost
and 127.0.0.1
, you cannot connect from an external source. If you see other IP addresses, but not the one you're connecting from - that's also an indication.
You will need to add the IP address of each system that you want to grant access to, and then grant privileges:
CREATE USER 'root'@'ip_address' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'ip_address';
If you see %
, well then, there's another problem altogether as that is "any remote source". If however you do want any/all systems to connect via root, use the %
wildcard to grant access:
CREATE USER 'root'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
Finally, reload the permissions, and you should be able to have remote access:
FLUSH PRIVILEGES;
http://en.wikibooks.org/wiki/LaTeX/Formatting
use \alltt
environment instead. Then set size using the same commands as outside verbatim environment.
If you had a IDE open with the same code, try doing a ctrl+z on each individual file that you have made changes to. It helped me recover my uncommited changes after doing git reset --hard.
on Mac, how I usually solve it
Hope this helps OP or someone else reading
you can simply do like this -
public void FullScreen() {
if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
final View v = this.activity.getWindow().getDecorView();
v.setSystemUiVisibility(8);
}
else if (Build.VERSION.SDK_INT >= 19) {
final View decorView = this.activity.getWindow().getDecorView();
final int uiOptions = 4102;
decorView.setSystemUiVisibility(uiOptions);
}
}
To check if a specific package is installed:
conda list html5lib
which outputs something like this if installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
or something like this if not installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
you don't need to type the exact package name. Partial matches are supported:
conda list html
This outputs all installed packages containing 'html':
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
sphinxcontrib-htmlhelp 1.0.2 py_0
sphinxcontrib-serializinghtml 1.1.3 py_0
I am also phase these error and i am little bit change in modelClass which are implemented Serializable interface like:
At that Model class also implement Parcelable interface with writeToParcel() override method
Then just got error to "create creator" so CREATOR is write and also create with modelclass contructor with arguments & without arguments..
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
}
protected ArtistTrackClass(Parcel in) {
id = in.readString();
name = in.readString();
}
public ArtistTrackClass() {
}
public static final Creator<ArtistTrackClass> CREATOR = new Creator<ArtistTrackClass>() {
@Override
public ArtistTrackClass createFromParcel(Parcel in) {
return new ArtistTrackClass(in);
}
@Override
public ArtistTrackClass[] newArray(int size) {
return new ArtistTrackClass[size];
}
};
Here,
ArtistTrackClass -> ModelClass
Constructor with Parcel arguments "read our attributes" and writeToParcel() is "write our attributes"
If you can not use *ngif, [class.hide] works in angular 7. example:
<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
<mat-option *ngFor="let filter of gridOptions.columnDefs"
[class.hide]="filter.headerName=='Action'" [value]="filter.field">{{filter.headerName}}</mat-option>
</mat-select>
Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:
#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas
I'm not sure but it looks like that the background-color is inherited as transparent from the body.
Use angular-ui-bootstrap's typehead.
It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.
(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
Put 0 as default in SQL or add 0 into your area of table
Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
This worked for me though:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
base.OnModelCreating(modelBuilder);
}
Another option is it to have the script set itself as the process group leader, and trap a killpg on your process group on exit.
Post data to backend using retrofit
implementation 'com.squareup.retrofit2:retrofit:2.8.1'
implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'
public interface UserService {
@POST("users/")
Call<UserResponse> userRegistration(@Body UserRegistration
userRegistration);
}
public class ApiClient {
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.larntech.net/")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getService(){
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
That's because the color
input only accepts three attributes: "primary"
, "accent"
or "warn"
. Hence, you'll have to style the icons the CSS way:
Add a class to style your icon:
.white-icon {
color: white;
}
/* Note: If you're using an SVG icon, you should make the class target the `<svg>` element */
.white-icon svg {
fill: white;
}
Add the class to your icon:
<mat-icon class="white-icon">menu</mat-icon>
Never use 777 for directories on your live server, but on your own machine, sometimes we need to do more than 775, because
chmod -R 775 storage
Means
7 - Owner can write
7 - Group can write
5 - Others cannot write!
If your webserver is not running as Vagrant, it will not be able to write to it, so you have 2 options:
chmod -R 777 storage
or change the group to your webserver user, supposing it's www-data
:
chown -R vagrant:www-data storage
You'll need AJAX if you want to update a part of your page without reloading the entire page.
main cshtml view
<div id="refTable">
<!-- partial view content will be inserted here -->
</div>
@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>
<script>
$(document).ready(function() {
$("#pY").on("click", function() {
var val = $('#yearSelect3').val();
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
});
});
</script>
You'll need to add the fields I have omitted. I've used a <button>
instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.
The HolidayPartialView gets rendered into html and the jquery done
callback inserts that html fragment into the refTable div.
HolidayController Update action
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.
view model
public class HolidayViewModel
{
IEnumerable<DateTime> Dates { get; set; }
}
HolidayPartialView.csthml
@model Your.Namespace.HolidayViewModel;
<table class="tblHoliday">
@foreach(var date in Model.Dates)
{
<tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
}
</table>
This is the stuff that gets inserted into your div.
More type safe code for Swift 3.0
extension UIResponder {
func owningViewController() -> UIViewController? {
var nextResponser = self
while let next = nextResponser.next {
nextResponser = next
if let vc = nextResponser as? UIViewController {
return vc
}
}
return nil
}
}
header( "refresh:5;url=wherever.php" );
this is the php way to set header
which will redirect you to wherever.php
in 5 seconds
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. (source php.net)
Use ThenByDescending
:
var hold = MyList.OrderBy(x => x.StartDate)
.ThenByDescending(x => x.EndDate)
.ToList();
You can also use query syntax and say:
var hold = (from x in MyList
orderby x.StartDate, x.EndDate descending
select x).ToList();
ThenByDescending
is an extension method on IOrderedEnumerable
which is what is returned by OrderBy
. See also the related method ThenBy
.
I found out why this happening.
After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.
Thank you everyone for trying to solve this. :)
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)
function. For instance, I wanted 3 decimal places:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'
specifies decimal format notation (more info here, you can also specify scientific notation) and the 3
specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number
function can be found here in the QString
documentation
Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.
Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
Dim arrToReturn() As Variant, myCollection As New Collection
For Each x In arr1: myCollection.Add x: Next
For Each y In arr2: myCollection.Add y: Next
ReDim arrToReturn(1 To myCollection.Count)
For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
joinArrays = arrToReturn
End Function
XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.
This is its function table:
a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
This operation is performed between every two corresponding bits of a number.
Example: 7 ^ 10
In binary: 0111 ^ 1010
0111
^ 1010
======
1101 = 13
Properties: The operation is commutative, associative and self-inverse.
It is also the same as addition modulo 2.
Update Swift 4.2
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: UIResponder.keyboardWillShowNotification, object: nil)
}
selector method:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
extension:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Update Swift 3.0
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: .UIKeyboardWillShow, object: nil)
}
selector method:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
extension:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Tip
UIKeyboardDidShowNotification or UIKeyboardWillShowNotification might called twice and got different result, this article explained why called twice.
In Swift 2.2
Swift 2.2 deprecates using strings for selectors and instead introduces new syntax: #selector
.
Something like:
private func setUpObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: .keyboardWillShow, name: UIKeyboardWillShowNotification, object: nil)
}
selector method:
@objc private func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
editorBottomCT.constant = keyboardHeight
}
extension:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(_:))
}
In my case it was an higher version of Google-play-services. I set them to 7.0.0 (not 8.x) and all was ok.
Insert a coloured box the full size of the slide, set colour to white with 100% transparency. select all, right-click save as picture, select PNG and save.
copy/paste inserted colour box to each slide and repeat
You can also hide spinner with following trick :
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity:0;
pointer-events:none;
}
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
The issue is probably due to /foo/bar not being owned by the writing process on a remote darwin (OS X) system. A solution to the issue is to set adequate owner on the remote site.
Since this answer has been voted, and therefore has been hopefully useful to someone, I'm extending it to make it clearer.
The reason why this happens is that rsync is probably trying to set an arbitrary modification time (mtime) when copying files.
In order to do this darwin's system utime()
function requires that the writing process effective uid is either the same as the file uid or super user's one, see opengroup utime's page.
Check this discussion on rsync mailing list as reference.
Here is a solution with Cygwin:
#!/bin/dash -e
if [ "$1" ]
then k=$(cygpath -w "$1")
elif [ "$#" != 0 ]
then k=
fi
Notepad2 ${k+"$k"}
If no path, pass no path
If path is empty, pass empty path
If path is not empty, convert to Windows format.
Then I set these variables:
export EDITOR=notepad2.sh
export GIT_EDITOR='dash /usr/local/bin/notepad2.sh'
EDITOR allows script to work with Git
GIT_EDITOR allows script to work with Hub commands
If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:
$('body').animate({ scrollTop: $(document).height() });
If you are not using https in api calls, Please add this key "App Uses Non-Exempt Encryption" in your info.plist and set it to "NO"
Just in case you're using .NET 2.0 and don't have access to LINQ:
static T First<T>(IEnumerable<T> items)
{
using(IEnumerator<T> iter = items.GetEnumerator())
{
iter.MoveNext();
return iter.Current;
}
}
This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.
Call it like so:
List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);
Or
int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);
You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:
static T ElementAt<T>(IEnumerable<T> items, int index)
{
using(IEnumerator<T> iter = items.GetEnumerator())
{
for (int i = 0; i <= index; i++, iter.MoveNext()) ;
return iter.Current;
}
}
Calling it like so:
int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);
Of course if you do have access to LINQ, then there are plenty of good answers posted already...
In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...
var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
if(sortAscending) {
qry = qry.OrderBy(x=>x.Property);
} else {
qry = qry.OrderByDescending(x=>x.Property);
}
Any use? You can create the entire "order" dynamically, but it is more involved...
Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.
Use brackets:
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND
(date='$Date_Today'
OR date='$Date_Yesterday'
OR date='$Date_TwoDaysAgo'
OR date='$Date_ThreeDaysAgo'
OR date='$Date_FourDaysAgo'
OR date='$Date_FiveDaysAgo'
OR date='$Date_SixDaysAgo'
OR date='$Date_SevenDaysAgo'
)
");
But you should alsos have a look at the IN
operator. So you can say ´date IN ('$date1','$date2',...)`
But if you have always a set of consecutive days why don't you do the following for the date part
date <= $Date_Today AND date >= $Date_SevenDaysAgo
Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest
I stumbled over the same question and I've found a solution.
First make sure you upgrade to LESS 1.6 at least.
You can use npm
for that case.
Now you can use the following mixin:
.if (@condition, @property, @value) when (@condition = true){
@{property}: @value;
}
Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:
.myHeadline {
.if(@include-lineHeight, line-height, '35px');
}
If @include-lineheight resolves to true LESS will print the line-height: 35px
and it will skip the mixin if @include-lineheight is not true.
FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.
Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.
/*for reich text editor */
public options: Object = {
charCounterCount: true,
height: 300,
inlineMode: false,
toolbarFixed: false,
fontFamilySelection: true,
fontSizeSelection: true,
paragraphFormatSelection: true,
events: {
'froalaEditor.blur': (e, editor) => { this.handleContentChange(editor.html.get()); }}
use -n
parameter to install like for cocoapods:
sudo gem install cocoapods -n /usr/local/bin
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
There is an interesting difference between the two popular solutions above:
If you create the bare repository like this:
cd /outside_of_any_repo mkdir my_remote.git cd my_remote.git git init --bare
and then
cd /your_path/original_repo
git remote add origin /outside_of_any_repo/my_remote.git
git push --set-upstream origin master
Then git sets up the configuration in 'original_repo' with this relationship:
original_repo origin --> /outside_of_any_repo/my_remote.git/
with the latter as the upstream remote. And the upstream remote doesn't have any other remotes in its configuration.
However, if you do it the other way around:
(from in directory original_repo) cd .. git clone --bare original_repo /outside_of_any_repo/my_remote.git
then 'my_remote.git' winds up with its configuration having 'origin' pointing back to 'original_repo' as a remote, with a remote.origin.url equating to local directory path, which might not be appropriate if it is going to be moved to a server.
While that "remote" reference is easy to get rid of later if it isn't appropriate, 'original_repo' still has to be set up to point to 'my_remote.git' as an up-stream remote (or to wherever it is going to be shared from). So technically, you can arrive at the same result with a few more steps with approach #2. But #1 seems a more direct approach to creating a "central bare shared repo" originating from a local one, appropriate for moving to a server, with fewer steps involved. I think it depends on the role you want the remote repo to play. (And yes, this is in conflict with the documentation here.)
Caveat: I learned the above (at this writing in early August 2019) by doing a test on my local system with a real repo, and then doing a file-by-file comparison between the results. But! I am still learning, so there could be a more correct way. But my tests have helped me conclude that #1 is my currently-preferred method.
If you want to use .get you can do it like this
http.get(url, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log(chunk);
});
});
I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e;
leads to an unhandeled exception, so I just did this:
try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {
throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}
Worked for me....:)
If you want case-insensitive comparison, use lower
or upper
:
if name.lower() == "jesse":
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
You could use the random.sample
function from the standard library to select k elements from a population:
import random
random.sample(range(low, high), n)
In case of a rather large range of possible numbers, you could use itertools.islice
with an infinite random generator:
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10)) # Take first 10 random elements
After the question update it is now clear that you need n distinct (unique) numbers.
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = set()
# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
items.add(x)
For xCode 10, first you need to add the image in your assetsCatalogue and then type this:
let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))
For beginners, let imageView
is the name of the UIImageView
object we are about to create.
An example for embedding an image into a viewControler
file would look like this:
import UIKit
class TutorialViewCotroller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
view.addSubview(imageView)
}
}
Please notice that I did not use any extension for the image file name, as in my case it is a group of images.
You can use the CLI too, like:
ng build -prod --output-path=production
# or
ng serve --output-path=devroot
PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.
This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb
files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb
files. So effectively pdb files are really a boon to developers while debugging a program.
Generally it is not recommended to exclude the generation of *.pdb
files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb
files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.
If you still want to disable generation of *.pdb
files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none
from "Debug Info" drop-down box -> press OK as shown in the snapshot below.
Note: This setting will have to be done separately for "Debug" and "Release" build configurations.
I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:
const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function
The fix was:
const car = await carFactory.getCar();
car.drive()
Posting this incase it helps anyone else facing this error.
Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.
Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.
You do say that the comparison is for sorting purposes. Then I suggest instead:
"a".localeCompare("b");
It returns -1
since "a" < "b"
, 1
or 0
otherwise, like you need for Array.prototype.sort()
Keep in mind that sorting is locale dependent. E.g. in German, ä
is a variant of a
, so "ä".localeCompare("b", "de-DE")
returns -1
. In Swedish, ä
is one of the last letters in the alphabet, so "ä".localeCompare("b", "se-SE")
returns 1
.
Without the second parameter to localeCompare
, the browser's locale is used. Which in my experience is never what I want, because then it'll sort differently than the server, which has a fixed locale for all users.
<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />
Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/
I did below and it works like charm.
<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>
var ans = 334 + '';
var temp = ans.toLowerCase();
alert(temp);
Have the same problem while using sourcetree Reason was Maybe switching the System Proxy from on to off while sourcetree was open. For some reason this was written into the config file of a project. This can be easily deleted over sourcetree by "Settings" -> "Edit configuration file". Just delete it out there under http
The solution that worked for me was to right click on the project --> Maven --> Update Project then click OK.
.done()
terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail()
.
In practical terms, if you do not plan to attach more steps to a promise, you should use .done()
. For more details see why promises need to be done
go to your jdk path where you installed your java
For e.g In my PC JDK installed in the following path
"C:\Program Files\Java\jdk1.7.0_17\";
After go to the lib folder e.g "C:\Program Files\Java\jdk1.7.0_17\lib"
in the lib directory there is tool.jar file
Copy this file and past it in the lib forlder of jre7 directory for e.g
"C:\Program Files\Java\jre7\lib"
I have had this issue in a case where the static
function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.
My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface
From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.
create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode
How to spin up a zookeper environment within minutes on docker for windows, linux or mac:
One time set up:
docker network create dn
Run server in a terminal window:
docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper
Run client in a second terminal window:
docker run -it --rm --network dn zookeeper zkCli.sh -server zook
See also documentation of image on dockerhub
It's simple as:
$('#action').val("1");
#action
is hidden input field id.
This only works if you control both the outside page and the iframe page.
On the outside page, make the iframe
unscrollable.
<iframe src="" height=200 scrolling=no></iframe>
On the iframe page, add this.
<!doctype html>
...
<style>
html, body {height:100%; overflow:hidden}
body {overflow:auto; -webkit-overflow-scrolling:touch}
</style>
This works because modern browsers uses html
to determine the height, so we just give that a fixed height and turn the body
into a scrollable node.
If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace HowToCopyTextFiles
{
class Program
{
static void Main(string[] args)
{
string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
}
}
}
JDK (Java Development Kit)
Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…
Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient.
JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.
JRE (Java Runtime Environment)
Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system
The Java Virtual Machine provides a platform-independent way of executing code; That mean compile once in any machine and run it any where(any machine).
JVM (Java Virtual Machine)
As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.
The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.
There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.
You can refer to event modifiers in vuejs to prevent form submission on enter
key.
It is a very common need to call
event.preventDefault()
orevent.stopPropagation()
inside event handlers.Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
To address this problem, Vue provides event modifiers for
v-on
. Recall that modifiers are directive postfixes denoted by a dot.
<form v-on:submit.prevent="<method>">
...
</form>
As the documentation states, this is syntactical sugar for e.preventDefault()
and will stop the unwanted form submission on press of enter key.
Here is a working fiddle.
new Vue({_x000D_
el: '#myApp',_x000D_
data: {_x000D_
emailAddress: '',_x000D_
log: ''_x000D_
},_x000D_
methods: {_x000D_
validateEmailAddress: function(e) {_x000D_
if (e.keyCode === 13) {_x000D_
alert('Enter was pressed');_x000D_
} else if (e.keyCode === 50) {_x000D_
alert('@ was pressed');_x000D_
} _x000D_
this.log += e.key;_x000D_
},_x000D_
_x000D_
postEmailAddress: function() {_x000D_
this.log += '\n\nPosting';_x000D_
},_x000D_
noop () {_x000D_
// do nothing ?_x000D_
}_x000D_
}_x000D_
})
_x000D_
html, body, #editor {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
<input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
<button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
<br /><br />_x000D_
_x000D_
<textarea v-model="log" rows="4"></textarea> _x000D_
</form>_x000D_
</div>
_x000D_
SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus % 2100%'
I encountered a similar situation, and it turns out that Codeigniter (the PHP framework I was using) actually sets its own time limit:
In system/core/Codeigniter.php, line 106 in version 2.1.3 the following appears:
if (function_exists("set_time_limit") == TRUE AND @ini_get("safe_mode") == 0)
{
@set_time_limit(300);
}
As there was no other way to avoid changing the core file, I removed it so as to allow configuration through php.ini, as well as give the infinite maximum execution time for a CLI request.
I recommend recording this change somewhere in the case of future CI version upgrades however.
I've briefly covered a simple way to do this with Google Spreadsheets (importHTML
) and in Python (Pandas read_html
and to_csv
) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.
Perhaps you get a blank page when you run from Visual Studio under development server using Windows authentication (previous topic).
If you deploy to IIS you can configure custom error pages for specific status codes, in this case 401. Add httpErrors under system.webServer:
<httpErrors>
<remove statusCode="401" />
<error statusCode="401" path="/yourapp/error/unauthorized" responseMode="Redirect" />
</httpErrors>
Then create ErrorController.Unauthorized method and corresponding custom view.
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.
The issue is that readPreference
setting defaults to primary
, which then somehow leads to the confusing slaveOk
error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.
Setting readPreference
to primaryPreferred
(or better to the ReadPreference.PRIMARY_PREFERRED
constant) solved it for me. Just pass it as an option to MongoClient.connect()
or to client.db()
or to any find()
, aggregate()
or other function.
const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
Don't give exact heights, but relative ones, adding up to 100%. For example:
#content {height: 80%;}
#footer {height: 20%;}
Add in
html, body {height: 100%;}
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Generate the object files with gcc, then use ar
to bundle them into a static library.
You can also use a small function that will loop through and remove any spaces.
This is very clean and simple.
Public Shared Function RemoveXtraSpaces(strVal As String) As String
Dim iCount As Integer = 1
Dim sTempstrVal As String
sTempstrVal = ""
For iCount = 1 To Len(strVal)
sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
Next
RemoveXtraSpaces = sTempstrVal
Return RemoveXtraSpaces
End Function
SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());
Example.
SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE());
You can also enable multiple GPU cores, like so:
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"
Assuming you want the whole regex to ignore case, you should look for the i
flag. Nearly all regex engines support it:
/G[a-b].*/i
string.match("G[a-b].*", "i")
Check the documentation for your language/platform/tool to find how the matching modes are specified.
If you want only part of the regex to be case insensitive (as my original answer presumed), then you have two options:
Use the (?i)
and [optionally] (?-i)
mode modifiers:
(?i)G[a-b](?-i).*
Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:
[gG][a-bA-B].*
One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.
My problem was our own collection class, which was flagged with [DataContract]. From my point of view, this was a clean approach and it worked fine with XmlSerializer but for the WCF endpoint it was breaking and we had to remove it. XmlSerializer still works without.
Not working
[DataContract]
public class AttributeCollection : List<KeyValuePairSerializable<string, string>>
Working
public class AttributeCollection : List<KeyValuePairSerializable<string, string>>
In case if you need a matrix with predefined numbers you can use the following code:
def matrix(rows, cols, start=0):
return [[c + start + r * cols for c in range(cols)] for r in range(rows)]
assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]
The ~
selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
Consider the following example:
.a ~ .b {_x000D_
background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
<li class="b">1st</li>_x000D_
<li class="a">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="b">5th</li>_x000D_
</ul>
_x000D_
.a ~ .b
matches the 4th and 5th list item because they:
.b
elements .a
.a
in HTML source order.Likewise, .check:checked ~ .content
matches all .content
elements that are siblings of .check:checked
and appear after it.
"Casting" is different than conversion. In this case, window.location.hash
will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
These conversions are ideal if you don't want an error to be thrown when page_number
is null
or undefined
. Whereas page_number.toString()
and page_number.toLocaleString()
will throw when page_number
is null
or undefined
.
When you only need to cast, not convert, this is how to cast to a string in TypeScript:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
The <string>
or as string
cast annotations tell the TypeScript compiler to treat page_number
as a string at compile time; it doesn't convert at run time.
However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>
, then to <string>
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
So it's easier to just convert, which handles the type at run time and compile time:
window.location.hash = String(page_number);
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
First, we choose stable (not static) data columns to form a Primary Key, precisely because updating Keys in a Relational database (in which the references are by Key) is something we wish to avoid.
For this issue, it doesn't matter if the Key is a Relational Key ("made up from the data"), and thus has Relational Integrity, Power, and Speed, or if the "key" is a Record ID, with none of that Relational Integrity, Power, and Speed. The effect is the same.
I state this because there are many posts by the clueless ones, who suggest that this is the exact reason that Record IDs are somehow better than Relational Keys.
The point is, the Key or Record ID is migrated to wherever a reference is required.
Second, if you have to change the value of the Key or Record ID, well, you have to change it. Here is the OLTP Standard-compliant method. Note that the high-end vendors do not allow "cascade update".
Write a proc. Foo_UpdateCascade_tr @ID, where Foo is the table name
Begin a Transaction
First INSERT-SELECT a new row in the parent table, from the old row, with the new Key or RID value
Second, for all child tables, working top to bottom, INSERT-SELECT the new rows, from the old rows, with the new Key or RID value
Third, DELETE the rows in the child tables that have the old Key or RID value, working bottom to top
Last, DELETE the row in the parent table that has the old Key or RID value
Commit the Transaction
The other answers are incorrect.
Disabling constraints and then enabling them, after UPDATing the required rows (parent plus all children) is not something that a person would do in an online production environment, if they wish to remain employed. That advice is good for single-user databases.
The need to change the value of a Key or RID is not indicative of a design flaw. It is an ordinary need. That is mitigated by choosing stable (not static) Keys. It can be mitigated, but it cannot be eliminated.
A surrogate substituting a natural Key, will not make any difference. In the example you have given, the "key" is a surrogate. And it needs to be updated.
There is nothing "tricky" about cascading all the required changes. Refer to the steps given above.
There is nothing that can be prevented re the universe changing. It changes. Deal with it. And since the database is a collection of facts about the universe, when the universe changes, the database will have to change. That is life in the big city, it is not for new players.
People getting married and hedgehogs getting buried are not a problem (despite such examples being used to suggest that it is a problem). Because we do not use Names as Keys. We use small, stable Identifiers, such as are used to Identify the data in the universe.
Don't update the PK! is the second-most hilarious thing I have read in a while. Add a new column is the most.
Use Case:
Select Case When @PaidThisMonth < @OwedPast
Then @PaidThisMonth Else @OwedPast End PaidForPast
As Inline table valued UDF
CREATE FUNCTION Minimum
(@Param1 Integer, @Param2 Integer)
Returns Table As
Return(Select Case When @Param1 < @Param2
Then @Param1 Else @Param2 End MinValue)
Usage:
Select MinValue as PaidforPast
From dbo.Minimum(@PaidThisMonth, @OwedPast)
ADDENDUM: This is probably best for when addressing only two possible values, if there are more than two, consider Craig's answer using Values clause.
To all the great answers, I want to add a small detail:
If You write plugins (e.g. DLLs or .so libraries to be loaded by a CAD system), then static is a life saver that avoids name collisions like this one:
Even worse: Step 3 may behave differently depending on compiler optimization, plugin load mechanism, etc.
I had this issue once with two helper functions (same name, different behaviour) in two plugins. Declaring them static solved the problem.
Let's not forget our relatively new friend, java-8 stream API. If you need to preprocess list before converting it to a set, it's better to have something like:
list.stream().<here goes some preprocessing>.collect(Collectors.toSet());
Sure is:
@media screen and (-webkit-min-device-pixel-ratio:0)
{
#element { properties:value; }
}
And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/
Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.
Also, these hacks may not be future proof.
width: 100%;
overflow: hidden;
I believe that should do the trick.
System.ComponentModel.DataAnnotations is contained in its own assembly so you need to make sure you have it refernced. Just simply:
1). Right click on Soloution and choose add.
2). Choose reference from the list.
3). Search " System.ComponentModel.DataAnnotation " and tick the check box on its left hand side and press ok.
Job done, shouldnt have any refernce errors.
There are multiple answers to this question, partly due to ambiguous question - the title is talking about classes loaded by the JVM, whereas the contents of the question says "may or may not be loaded by the JVM".
Assuming that OP needs classes that are loaded by the JVM by a given classloader, and only those classes - my need as well - there is a solution (elaborated here) that goes like this:
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class CPTest {
private static Iterator list(ClassLoader CL)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Class CL_class = CL.getClass();
while (CL_class != java.lang.ClassLoader.class) {
CL_class = CL_class.getSuperclass();
}
java.lang.reflect.Field ClassLoader_classes_field = CL_class
.getDeclaredField("classes");
ClassLoader_classes_field.setAccessible(true);
Vector classes = (Vector) ClassLoader_classes_field.get(CL);
return classes.iterator();
}
public static void main(String args[]) throws Exception {
ClassLoader myCL = Thread.currentThread().getContextClassLoader();
while (myCL != null) {
System.out.println("ClassLoader: " + myCL);
for (Iterator iter = list(myCL); iter.hasNext();) {
System.out.println("\t" + iter.next());
}
myCL = myCL.getParent();
}
}
}
One of the neat things about it is that you can choose an arbitrary classloader you want to check. It is however likely to break should internals of classloader class change, so it is to be used as one-off diagnostic tool.
If it doesn't/wouldn't run on the CPU, it's a script to me. If an interpreter needs to run on the CPU below the program, then it's a script and a scripting language.
No reason to make it any more complicated than this?
Of course, in most (99%) of cases, it's clear whether a language is a scripting language. But consider that a VM can emulate the x86 instruction set, for example. Wouldn't this make the x86 bytecode a scripting language when run on a VM? What if someone was to write a compiler that would turn perl code into a native executable? In this case, I wouldn't know what to call the language itself anymore. It'd be the output that would matter, not the language.
Then again, I'm not aware of anything like this having been done, so for now I'm still comfortable calling interpreted languages scripting languages.
See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/
You can use 'USING' instead of 'ON' as in the query
SELECT * FROM table1 LEFT JOIN table2 USING (id);
You need a table variable:
declare @values table
(
Value varchar(1000)
)
insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')
select blah
from foo
where myField in (select value from @values)
Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason
In the above given code
assign the php value to javascript variable.
<html>
<?php
$num = 1;
echo $num;
?>
<input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
<br>
<script>
var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var numeric
function Inc()
{
numeric = eVal(numeric) + 1;
alert("Increamented value: "+numeric);
}
</script>
</html>
One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.
From the answers above, the shortest oneliner to mimic Python's
file, ext = os.path.splitext(path)
presuming your file really does have an extension, is
EXT="${PATH##*.}"; FILE=$(basename "$PATH" .$EXT)
You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always"
. And use kubectl delete pod pod_name
.
A new container will be created and the latest image automatically downloaded, then the old container terminated.
Example:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: my_container
image: my_image:latest
imagePullPolicy: "Always"
I'm currently using Jenkins for automated builds and image tagging and it looks something like this:
kubectl --user="kube-user" --server="https://kubemaster.example.com" --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT"
Another trick is to intially run:
kubectl set image deployment/my-deployment mycontainer=myimage:latest
and then:
kubectl set image deployment/my-deployment mycontainer=myimage
It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always"
set.
Update:
another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds
. You can do this using kubectl edit deployment your_deployment
or kubectl apply -f your_deployment.yaml
or using a patch like this:
kubectl patch deployment your_deployment -p \
'{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}'
Just make sure you always change the number value.
alter table company drop constraint Company_CountryID_FK
If you are using the new Navigation Component, is simple as
findNavController().popBackStack()
It will do all the FragmentTransaction in behind for you.
When you want to remove a string, rather than replace it you can use String#delete
(or its mutator equivalent String#delete!
), e.g.:
x = "foo\nfoo"
x.delete!("\n")
x
now equals "foofoo"
In this specific case String#delete
is more readable than gsub
since you are not actually replacing the string with anything.
I think that is because you usually write your functions to manipulate data, and then lift it to Optional
using map
and similar functions. This adds the default Optional
behavior to it.
Of course, there might be cases, when it is necessary to write your own auxilary function that works on Optional
.
One more point I want to add. In spring-servlet.xml
we include component scan for Controller package.
In following example we include filter annotation for controller package.
<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In applicationcontext.xml
we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
Use the ref
keyword.
Look at the definitive reference here to understand passing parameters.
To be specific, look at this, to understand the behavior of the code.
EDIT: Sort
works on the same reference (that is passed by value) and hence the values are ordered. However, assigning a new instance to the parameter won't work because parameter is passed by value, unless you put ref
.
Putting ref
lets you change the pointer to the reference to a new instance of List
in your case. Without ref
, you can work on the existing parameter, but can't make it point to something else.
for (int i = 0; i < nodeList.getLength(); i++)
change to
for (int i = 0, len = nodeList.getLength(); i < len; i++)
to be more efficient.
The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.
Why are you grouping by? Do you mean order by?
SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;
You could try this:
Simply place the code in a style tag in the head of the html file
<style>_x000D_
.jumbotron {_x000D_
background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
}_x000D_
</style>
_x000D_
or put it in a separate css file as shown below
.jumbotron {_x000D_
background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
}
_x000D_
use center center to center the image horizontally and vertically. use cover to make the image fill out the jumbotron space and finally no-repeat so that the image is not repeated.
You can tell SQL Server to use Monday as the start of the week using DATEFIRST like this:
SET DATEFIRST 1
Javascript now has a specific built in object called Map, you can call as follows :
var myMap = new Map()
You can update it with .set :
myMap.set("key0","value")
This has the advantage of methods you can use to handle look ups, like the boolean .has
myMap.has("key1"); // evaluates to false
You can use this before calling .get on your Map object to handle looking up non-existent keys
This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?
Inspecting this
within the component, we have this.$options.propsData
. If the prop is present here, the user has explicitly set it; default values aren't shown.
This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.
This happens if you forgot to change your build settings to Simulator
. Unless you want to build to a device, in which case you should see the other answers.
The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double
, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double
.
Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.
I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:
http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6
If you strip out all the hex float support, infinity/nan support, %g
/%f
/%e
variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.
Please read the whole answer before attempting to run with sudo
Try running sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, DON'T DO THIS! If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:
~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.
If you are still having problems you can check the permissions on the file by running ls -l
while in the same directory as the ruby script. You will get something like this:
$ ls -l
total 13
drwxr-xr-x 4 or019268 Administ 12288 Apr 10 18:14 TestWizard
drwxr-xr-x 4 or019268 Administ 4096 Aug 27 12:41 Wizard.Controls
drwxr-xr-x 5 or019268 Administ 8192 Sep 5 00:03 Wizard.UI
-rw-r--r-- 1 or019268 Administ 1375 Sep 5 00:03 readme.txt
You will notice that the readme.txt file says -rw-r--r--
on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute chmod 755 readme.txt
and that permissions portion would become rwxr-xr-x
. I can now execute this file if I want to by running ./readme.txt
(./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).
schluchc alludes to looking at the man page for chmod, do this by running man chmod
. This is the best way to get documentation on a given command, man <command>
CharlesB's answer and helmbert's answer are both helpful, but it took me a while to understand them. Here's another way of putting it:
git show <tag>
to see a tag's details contains no reference to any branches, only the ID of the commit that the tag points to.
6f6b5997506d48fc6267b0b60c3f0261b6afe7a2
)git tag v0.1.0 # tags HEAD of *current* branch
git tag v0.1.0 develop # tags HEAD of 'develop' branch
git describe
to describe the current branch:
git describe [--tags]
describes the current branch in terms of the commits since the most recent [possibly lightweight] tag in this branch's history.git describe
may NOT reflect the most recently created tag overall.Instead of ISNULL()
, use NVL()
.
T-SQL:
SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable
PL/SQL:
SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
You can grep the logs to see the version. Let's say kafka is installed under /usr/local/kafka
, then:
$ grep "Kafka version" /usr/local/kafka/logs/*
/usr/local/kafka/logs/kafkaServer.out: INFO Kafka version : 0.9.0.1 (org.apache.kafka.common.utils.AppInfoParser)
will reveal the version
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
To add margins directly to items (some items allow direct editing of margins), you can do:
LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
((MarginLayoutParams) lp).topMargin = ...;
((MarginLayoutParams) lp).leftMargin = ...;
//... etc
}
else
Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );
...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.
To convert serialize object to String and String to Object
stringToBean(beanToString(new LoginMdp()), LoginMdp.class);
public static String beanToString(Object object) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
StringWriter stringEmp = new StringWriter();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.writeValue(stringEmp, object);
return stringEmp.toString();
}
public static <T> T stringToBean(String content, Class<T> valueType) throws IOException {
return new ObjectMapper().readValue(content, valueType);
}
If M2_HOME
is configured to point to the Maven home directory then:
File -> Settings
Maven
Runner
Insert in the field VM Options
the following string:
Dmaven.multiModuleProjectDirectory=$M2_HOME
Click Apply
and OK
Other answers looked incomplete.
I have tried below in full, and it worked fine.
NOTE:
1. Make a copy of your repository before you try below, to be on safe side.
Details:
1. All development happens in dev branch
2. qa branch is just the same copy of dev
3. Time to time, dev code needs to be moved/overwrite to qa branch
so we need to overwrite qa branch, from dev branch
Part 1:
With below commands, old qa has been updated to newer dev:
git checkout dev
git merge -s ours qa
git checkout qa
git merge dev
git push
Automatic comment for last push gives below:
// Output:
// *<MYNAME> Merge branch 'qa' into dev,*
This comment looks reverse, because above sequence also looks reverse
Part 2:
Below are unexpected, new local commits in dev, the unnecessary ones
so, we need to throw away, and make dev untouched.
git checkout dev
// Output:
// Switched to branch 'dev'
// Your branch is ahead of 'origin/dev' by 15 commits.
// (use "git push" to publish your local commits)
git reset --hard origin/dev
// Now we threw away the unexpected commits
Part 3:
Verify everything is as expected:
git status
// Output:
// *On branch dev
// Your branch is up-to-date with 'origin/dev'.
// nothing to commit, working tree clean*
That's all.
1. old qa is now overwritten by new dev branch code
2. local is clean (remote origin/dev is untouched)
var seconds = 0;
setInterval(function () {
seconds++;
}, 1000);
There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.
Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.
You could also solve this by saving and comparing times.
EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.
simplifily, use:
pip install -r requirement.txt
it can install all listed in requirement file.
Consider the partial map.cshtml
at Partials/Map.cshtml
. This can be called from the Page where the partial is to be rendered, simply by using the <partial>
tag:
<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />
This is one of the easiest methods I encountered (although I am using razor pages, I am sure same is for MVC too)
You can fix the issue by deleting the __MigrationHistory
table which is created automatically in the database and logs any update in the database using code-first migrations. Here, in this case, you manually changed your database while EF assumed you had to do it with the migration tool. Deleting the table means to the EF that there are no updates and no need to do code-first migrations thus it works perfectly fine.
go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.
If you are in a po-up and you want to access the opening window, use window.opener
.
The easiest would be if you could load JQuery in the parent window as well:
window.opener.$("#serverMsg").html
// this uses JQuery in the parent window
or you could use plain old document.getElementById
to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):
element = window.opener.document.getElementById("serverMsg");
element = $(element);
If you are in an iframe or frameset and want to access the parent frame, use window.parent
instead of window.opener
.
According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
zoom in out animation
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
startActivity(i);
finish();
zoom_enter
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="500" />
zoom_exit
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0"
android:fillAfter="true"
android:duration="500" />
Assuming MySQL supports it, you can easily do this with a standard SQL subquery:
select
(count(*) from league_girl l1 where l2.score > l1.score and l1.id <> l2.id) as position,
username,
score
from league_girl l2
order by score;
For large amounts of displayed results, this will be a bit slow and you will want to switch to a self join instead.
After the configure step you probably have a makefile. Inside this makefile look for CFLAGS (or similar). puf -fPIC at the end and run make again. In other words -fPIC is a compiler option that has to be passed to the compiler somewhere.
.NET Core has had a pair of methods to deal with this since version 2.0 :
Example:
"Test".Contains("test", System.StringComparison.CurrentCultureIgnoreCase);
In time, they will probably make their way into the .NET Standard and, from there, into all the other implementations of the Base Class Library.
If for
loops are on short supply, here's what I like to use:
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
Please run the below query, it doesn't requires STUFF and GROUP BY in your case:
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, CAST((
SELECT T.maskdetail+','
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH(''))as varchar(max)) as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.
Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.
I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException
.
Usage:
unchecked(() -> methodThrowingCheckedException())
public class UncheckedExceptions {
/**
* throws {@code exception} as unchecked exception, without wrapping exception.
*
* @return will never return anything, return type is set to {@code exception} only to be able to write <code>throw unchecked(exception)</code>
* @throws T {@code exception} as unchecked exception
*/
@SuppressWarnings("unchecked")
public static <T extends Throwable> T unchecked(Exception exception) throws T {
throw (T) exception;
}
@FunctionalInterface
public interface UncheckedFunction<R> {
R call() throws Exception;
}
/**
* Executes given function,
* catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
*
* @return result of function
* @see #unchecked(Exception)
*/
public static <R> R unchecked(UncheckedFunction<R> function) {
try {
return function.call();
} catch (Exception e) {
throw unchecked(e);
}
}
@FunctionalInterface
public interface UncheckedMethod {
void call() throws Exception;
}
/**
* Executes given method,
* catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
*
* @see #unchecked(Exception)
*/
public static void unchecked(UncheckedMethod method) {
try {
method.call();
} catch (Exception e) {
throw unchecked(e);
}
}
}
You can just put r
in front of the string with your actual path, which denotes a raw string. For example:
data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
You can get posted form data from request.form
and query string data from request.args
.
myvar = request.form["myvar"]
myvar = request.args["myvar"]
Maybe something like this
ps -eo pid,pcpu,comm
And if you like to parse and maybe only look at some processes.
#!/bin/sh
ps -eo pid,pcpu,comm | awk '{if ($2 > 4) print }' >> ~/ps_eo_test.txt
And in swift, you don't need to import "QuartzCore/QuartzCore.h"
Just use:
button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor
or
button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor
execCommand('SaveAs', false, filename);
functionalityEdit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.
Now this code is an rare antique zero day collectible.
// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
var dlg = false;
with(document){
ir=createElement('iframe');
ir.id='ifr';
ir.location='about.blank';
ir.style.display='none';
body.appendChild(ir);
with(getElementById('ifr').contentWindow.document){
open("text/plain", "replace");
charset = "utf-8";
write(content);
close();
document.charset = "utf-8";
dlg = execCommand('SaveAs', false, filename);
}
body.removeChild(ir);
}
return dlg;
}
Invoke the function like this:
msg = "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");
How about this: Spawning the next generation of hackers by Nat Torkington.
I know this is an old question and the answers provided work fine ... but this is a bit shorter and doesn't require any additional libraries ( i.e. JSON ):
function arraysAreEqual(ary1,ary2){
return (ary1.join('') == ary2.join(''));
}
I think you should use prop(), if you are using jQuery 1.6 onwards.
To check it you should do:
$('#test').prop('checked', true);
to uncheck it:
$('#test').prop('checked', false);
Title_Authors is a look up two things join at a time project results and continue chaining
DataClasses1DataContext db = new DataClasses1DataContext();
var queryresults = from a in db.Authors
join ba in db.Title_Authors
on a.Au_ID equals ba.Au_ID into idAuthor
from c in idAuthor
join t in db.Titles
on c.ISBN equals t.ISBN
select new { Author = a.Author1,Title= t.Title1 };
foreach (var item in queryresults)
{
MessageBox.Show(item.Author);
MessageBox.Show(item.Title);
return;
}
When you use Apache with mod_php apache is enforced in prefork
mode, and not worker
. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).
So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :
StartServers 20
MinSpareServers 5
MaxSpareServers 10
MaxClients 1024
MaxRequestsPerChild 0
This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.
See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.
Now you set 1024
MaxClients
. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.
So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:
<IfModule prefork.c>
StartServers 12
MinSpareServers 12
MaxSpareServers 12
MaxClients 12
MaxRequestsPerChild 300
</IfModule>
That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300
means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).ListenBacklog
queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe
And yes, that means you cannot handle more than 12 parallel requests.
If you want to handle more requests:
If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?
And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.
Update: About internal dummy connections (if it's your problem, but maybe not).
Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.
If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
Update:
Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.
Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l
or apache2 -l
on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:
<IfModule worker.c>
StartServers 3
MaxClients 500
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:
<IfModule worker.c>
StartServers 2
MaxClients 250
MinSpareThreads 50
MaxSpareThreads 150
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
We had the problem of different background colors for our cutted elements. And we only wanted upper right und bottom left corner.
body {_x000D_
background-color: rgba(0,0,0,0.3)_x000D_
_x000D_
}_x000D_
_x000D_
.box {_x000D_
position: relative;_x000D_
display: block;_x000D_
background: blue;_x000D_
text-align: center;_x000D_
color: white;_x000D_
padding: 15px;_x000D_
margin: 50px;_x000D_
}_x000D_
_x000D_
.box:before,_x000D_
.box:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
left: 0; _x000D_
right: 0;_x000D_
bottom: 100%;_x000D_
border-bottom: 15px solid blue;_x000D_
border-left: 15px solid transparent;_x000D_
border-right: 15px solid transparent;_x000D_
}_x000D_
_x000D_
.box:before{_x000D_
border-left: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after{_x000D_
border-right: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
bottom: auto;_x000D_
top: 100%;_x000D_
border-bottom: none;_x000D_
border-top: 15px solid blue;_x000D_
}_x000D_
_x000D_
_x000D_
/* Active box */_x000D_
.box.active{_x000D_
background: white;_x000D_
color: black;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.active:before,_x000D_
.active:after {_x000D_
border-bottom: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:before{_x000D_
border-left: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after{_x000D_
border-right: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after {_x000D_
border-bottom: none;_x000D_
border-top: 15px solid white;_x000D_
}
_x000D_
<div class="box">_x000D_
Some text goes here. Some text goes here. Some text goes here. Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>_x000D_
</div>_x000D_
<div class="box">_x000D_
Some text goes here._x000D_
</div>_x000D_
<div class="box active">_x000D_
Some text goes here._x000D_
<span class="border-bottom"></span>_x000D_
</div>_x000D_
<div class="box">_x000D_
Some text goes here._x000D_
</div>
_x000D_
Just use padding top and bottom, it will automatically center the content vertically.
You need to call the Configure
function of the XmlConfigurator
log4net.Config.XmlConfigurator.Configure();
Either call before your first loggin call or in your Global.asax like this:
protected void Application_Start(Object sender, EventArgs e) {
log4net.Config.XmlConfigurator.Configure();
}
(Explanation in more details can be found in an archived Microsoft KB article.)
Three things to know:
%1
, %2
, ...Two percent signs with any characters in between them are interpreted as a variable:
echo %myvar%
%%f
Why's that?
For example, if we execute your (simplified) command line
FOR /f %f in ('dir /b .') DO somecommand %f
in a batch file, rule 2 would try to interpret
%f in ('dir /b .') DO somecommand %
as a variable. In order to prevent that, you have to apply rule 3 and escape the %
with an second %
:
FOR /f %%f in ('dir /b .') DO somecommand %%f
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
Look at rsync
based Windows tool NASBackup. It will be a bonus if you are acquainted with rsync commands.
If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:
/**
* The interface defines all abstract methods and extends the concrete base class
*/
interface IAnimal extends Animal {
speak() : void;
}
/**
* The abstract base class only defines concrete methods & properties.
*/
class Animal {
private _impl : IAnimal;
public name : string;
/**
* Here comes the clever part: by letting the constructor take an
* implementation of IAnimal as argument Animal cannot be instantiated
* without a valid implementation of the abstract methods.
*/
constructor(impl : IAnimal, name : string) {
this.name = name;
this._impl = impl;
// The `impl` object can be used to delegate functionality to the
// implementation class.
console.log(this.name + " is born!");
this._impl.speak();
}
}
class Dog extends Animal implements IAnimal {
constructor(name : string) {
// The child class simply passes itself to Animal
super(this, name);
}
public speak() {
console.log("bark");
}
}
var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"
Since the Animal
class requires an implementation of IAnimal
it's impossible to construct an object of type Animal
without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal
, not Animal
. E.g.:
//This works
function letTheIAnimalSpeak(animal: IAnimal) {
console.log(animal.name + " says:");
animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
console.log(animal.name + " says:");
animal.speak();
}
The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.
The following creates a generic function, taking an array of any size and of any type by reference:
template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
// do stuff
}
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" />
control doesn't handle that.
If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change
event then strip the filename portion and save the path somewhere--but that's about as good as it gets.
Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.