In addition to the other responses:
Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).
Examples of those risks, in real life:
Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.
Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).
Backend RS applications can be outsourced to more or less trustworthy third-parties.
The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.
Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.
https://raw.github.com/fabric/fabric/master/fabric/colors.py
"""
.. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
print(green("This text is green!"))
Because these functions simply return modified strings, you can nest them::
from fabric.colors import red, green
print(red("This sentence is red, except for " + \
green("these words, which are green") + "."))
If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""
def _wrap_with(code):
def inner(text, bold=False):
c = code
if bold:
c = "1;%s" % c
return "\033[%sm%s\033[0m" % (c, text)
return inner
red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')
if you cloned your local will automatically consist,
remote URL where it gets cloned.
you can check it using git remote -v
if you want to made change in it,
git remote set-url origin https://github.io/my_repo.git
here,
origin - your branch
if you want to overwrite existing branch you can still use it.. it will override your existing ... it will do,
git remote remove url
and
git remote add origin url
for you...
When I was a little kid, I had a keen interest in computers (MSX back then), and consequently programming (all there was, was a variant of Basic). I lost that after I grew up, but I got back to it when I learned that Counter-Strike was just a mod made by some fans by modifying Half-Life code. That made me really interested in programming all over again!
It's not 10 lines of code, but if you show people the source code for some game, and then modify that and make it do something different, and demonstrate it to them live, it's reaaaaally gonna blow them away. Wow, this actually is not dark magic! You can do it!
Now a days, there are quite a few games you can do this with. I think the source code for all the Quake series (atleast I through III) is released. I know for a fact that you can create mods for Half-Life and Half-Life2, I'm sure other games like Unreal and FarCry also offer a similar ability.
Some simple things that could spark grate motivation:
The modification itself shouldn't take too many lines of code, but the fact that it works is just amazing.
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw
always interrupt the execution flow of the current method. a try
/catch
block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
In my case i must exclude compiling sources by gradle and set libs path
android {
...
sourceSets {
...
main.jni.srcDirs = []
main.jniLibs.srcDirs = ['libs']
}
....
If a profiler is not applicable in your setup, you may try to identify the thread following steps in this post.
Basically, there are three steps:
top -H
and get PID of the thread with highest CPU.I wanted to use the C++11 answer, but I could not because GCC 4.9 does not support std::put_time.
std::put_time implementation status in GCC?
I ended up using some C++11 to slightly improve the non-C++11 answer. For those that can't use GCC 5, but would still like some C++11 in their date/time format:
std::array<char, 64> buffer;
buffer.fill(0);
time_t rawtime;
time(&rawtime);
const auto timeinfo = localtime(&rawtime);
strftime(buffer.data(), sizeof(buffer), "%d-%m-%Y %H-%M-%S", timeinfo);
std::string timeStr(buffer.data());
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
the delete query only allows for modifiers after the DELETE 'command' to tell the database what/how do handle things.
see this page
filepath.Abs("./")
Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.
As stated in the comment, this returns the directory which is currently active.
I think since we don't have $rootScope kind of thing in angular 2 as in angular 1.x. We can use angular 2 shared service/class while in ngOnDestroy pass data to service and after routing take the data from the service in ngOnInit function:
Here I am using DataService to share hero object:
import { Hero } from './hero';
export class DataService {
public hero: Hero;
}
Pass object from first page component:
ngOnDestroy() {
this.dataService.hero = this.hero;
}
Take object from second page component:
ngOnInit() {
this.hero = this.dataService.hero;
}
Here is an example: plunker
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Sometimes a soft delete mechanism is used where a date is recorded to indicate the deleted date. In this case an UPDATE
statement may be used to update this field based on duplicate entries.
UPDATE MY_TABLE
SET DELETED = getDate()
WHERE TABLE_ID IN (
SELECT x.TABLE_ID
FROM MY_TABLE x
JOIN (SELECT min(TABLE_ID) id, COL_1, COL_2, COL_3
FROM MY_TABLE d
GROUP BY d.COL_1, d.COL_2, d.COL_3
HAVING count(*) > 1) AS d ON d.COL_1 = x.COL_1
AND d.COL_2 = x.COL_2
AND d.COL_3 = x.COL_3
AND d.TABLE_ID <> x.TABLE_ID
/*WHERE x.COL_4 <> 'D' -- Additional filter*/)
This method has served me well for fairly moderate tables containing ~30 million rows with high and low amounts of duplications.
The m_
prefix is often used for member variables - I think its main advantage is that it helps create a clear distinction between a public property and the private member variable backing it:
int m_something
public int Something => this.m_something;
It can help to have a consistent naming convention for backing variables, and the m_
prefix is one way of doing that - one that works in case-insensitive languages.
How useful this is depends on the languages and the tools that you're using. Modern IDEs with strong refactor tools and intellisense have less need for conventions like this, and it's certainly not the only way of doing this, but it's worth being aware of the practice in any case.
You need to give the same style of the fixed element and its parent element. One of these examples is created with max widths and in the other example with paddings.
* {_x000D_
box-sizing: border-box_x000D_
}_x000D_
body {_x000D_
margin: 0;_x000D_
}_x000D_
.container {_x000D_
max-width: 500px;_x000D_
height: 100px;_x000D_
width: 100%;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
background-color: lightgray;_x000D_
}_x000D_
.content {_x000D_
max-width: 500px;_x000D_
width: 100%;_x000D_
position: fixed;_x000D_
}_x000D_
h2 {_x000D_
border: 1px dotted black;_x000D_
padding: 10px;_x000D_
}_x000D_
.container-2 {_x000D_
height: 100px;_x000D_
padding-left: 32px;_x000D_
padding-right: 32px;_x000D_
margin-top: 10px;_x000D_
background-color: lightgray;_x000D_
}_x000D_
.content-2 {_x000D_
width: 100%;_x000D_
position: fixed;_x000D_
left: 0;_x000D_
padding-left: 32px;_x000D_
padding-right: 32px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="content">_x000D_
<h2>container with max widths</h2>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container-2">_x000D_
<div class="content-2">_x000D_
<div>_x000D_
<h2>container with paddings</h2>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
You can use this easiest method.
<form action="validator.php" method="post" id="form1">_x000D_
<input type="text" name="user">_x000D_
<input type="password" name="password">_x000D_
<input type="submit" value="submit" form="form1">_x000D_
</form>_x000D_
_x000D_
<br />_x000D_
_x000D_
<form action="validator.php" method="post" id="form2">_x000D_
<input type="text" name="user">_x000D_
<input type="password" name="password">_x000D_
<input type="submit" value="submit" form="form2">_x000D_
</form>
_x000D_
I tried many things from internet. Only below method worked for me. If every answer in this question don't work, try below steps in below order. Note :
package-lock
fileC:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm
" and
"C:\Users\ YOUR LOGIN NAME \AppData\Roaming\npm-cache
"AppData
and delete them too.npm cache clean --force
npm cache verify
npm install --force
= CONCATENATE("X",A1)
in one cell other than A say D You can see the changes made to the repective cells.
I wrote shell script below (named start.sh
).
Because my package.json
has prestart
option.
So I want to run npm start
.
#!/bin/bash
cd /path/to/project
npm start
Then, start start.sh
by pm2.
pm2 start start.sh --name appNameYouLike
React Native has updated the WebView component to allow for direct html rendering. Here's an example that works for me
var htmlCode = "<b>I am rendered in a <i>WebView</i></b>";
<WebView
ref={'webview'}
automaticallyAdjustContentInsets={false}
style={styles.webView}
html={htmlCode} />
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
Before clear space (trim)
Then replace with RegEx .replace("/\xEF\xBB\xBF/", "")
I'm working on Javascript, I did with JavaScript.
When your script is run by passing it as a command to the Python interpreter,
python myscript.py
all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main()
function that gets run automatically - the main()
function is implicitly all the code at the top level.
In this case, the top-level code is an if
block. __name__
is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py
above), then __name__
instead is set to the string "__main__"
. Thus, you can test whether your script is being run directly or being imported by something else by testing
if __name__ == "__main__":
...
If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if
clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
Now, if you invoke the interpreter as
python one.py
The output will be
top-level in one.py
one.py is being run directly
If you run two.py
instead:
python two.py
You get
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
Thus, when module one
gets loaded, its __name__
equals "one"
instead of "__main__"
.
Something like this will do the trick. Don't know about performance, so do make some tests.
select
id, name, city
from
[stuff] s
where
1 < (select count(*) from [stuff] i where i.city = s.city and i.name = s.name)
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
In Chrome, window.onload is different from <body onload="">
, whereas they are the same in both Firefox(version 35.0) and IE (version 11).
You could explore that by the following snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--import css here-->
<!--import js scripts here-->
<script language="javascript">
function bodyOnloadHandler() {
console.log("body onload");
}
window.onload = function(e) {
console.log("window loaded");
};
</script>
</head>
<body onload="bodyOnloadHandler()">
Page contents go here.
</body>
</html>
And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()
" in the consoles of IE & FF, you will see:
"function onload(event) { bodyOnloadHandler() }"
which means that the assignment "window.onload = function(e)..." is overwritten.
/^[a-zA-Z]*$/
Change the *
to +
if you don't want to allow empty matches.
Character classes ([...]
), Anchors (^
and $
), Repetition (+
, *
)
The /
are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
div hover background color change
Try like this:
.class_name:hover{
background-color:#FF0000;
}
As Sahil Chhabra suggested you can use @JsonFormat
with proper shape
on your variable.
In case you would like to apply it on every BigDecimal
field you have in your Dto's
you can override default format for given class.
@Configuration
public class JacksonObjectMapperConfiguration {
@Autowired
public void customize(ObjectMapper objectMapper) {
objectMapper
.configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
}
}
1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell
. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view.
But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question
2)NSIndexPath
is essentially two things-
Because your table might be divided to many sections and each with its own rows, this NSIndexPath
will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.
It is called if you implement the UITableViewDataSource
protocol in your view controller. A simpler way would be to add a UITableViewController
class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell
object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).
As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.
Does not solve the problem of network going down between checking and running your code but is fairly reliable
public static bool IsAvailableNetworkActive()
{
// only recognizes changes related to Internet adapters
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
// however, this will include all adapters -- filter by opstatus and activity
NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
return (from face in interfaces
where face.OperationalStatus == OperationalStatus.Up
where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
}
return false;
}
$(function(){
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});
This code from http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768 worked for me perfectly.
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
You want to use:
Collections.<String>emptyList();
If you look at the source for what emptyList does you see that it actually just does a
return (List<T>)EMPTY_LIST;
You can use the following command c:\path of you tomcat directory\bin>catalina run
I had this error when trying to SSH into my Raspberry pi from my MBP via bash terminal. My RPI was connected to the network via wifi/wlan0 and this IP had been changed upon restart by my routers DHCP.
Check IP being used to login via SSH is correct. Re-check IP of device being SSH'd into (in my case the RPI), which can be checked using hostname -I
Confirm/amend SSH login credentials on "guest" device (in my case the MBP) and it worked fine in my attempt.
Simple way to load more items on scroll up/down event in android GridView
grid.setOnScrollListener(new AbsListView.OnScrollListener() {
private int mLastFirstVisibleItem;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
Log.d("state",String.valueOf(scrollState));
if(scrollState == 0)
Log.i("a", "scrolling stopped...");
if (view.getId() == grid.getId()) {
final int currentFirstVisibleItem = grid.getLastVisiblePosition();
mLastFirstVisibleItem = grid.getFirstVisiblePosition();
if (currentFirstVisibleItem > mLastFirstVisibleItem) {
mIsScrollingUp = false;
if(!next.contains("null")){
//Call api to get products from server
}
Log.i("a", "scrolling down...");
} else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
mIsScrollingUp = true;
Log.i("a", "scrolling up...");
}
mLastFirstVisibleItem = currentFirstVisibleItem;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
Log.d("on scroll","");
}
});
if you want to display date along with time when you export to Excel then you can use this
xlWorkSheet.Cells(nRow, 3).NumberFormat = "dd/mm/yy h:mm AM/PM"
The underscore is the wildcard in a LIKE
query for one arbitrary character.
Hence LIKE %_%
means "give me all records with at least one arbitrary character in this column".
You have to escape the wildcard character, in sql-server with []
around:
SELECT m.*
FROM Manager m
WHERE m.managerid LIKE '[_]%'
AND m.managername LIKE '%[_]%'
See: LIKE (Transact-SQL)
If none of the options in the select have a selected
attribute, the first option will be the one selected.
In order to select a default option that is not the first, add a selected
attribute to that option:
<option selected="selected">Select a language</option>
You can read the HTML 4.01 spec regarding defaults in select element.
I suggest reading a good HTML book if you need to learn HTML basics like this - I recommend Head First HTML.
Peg the pattern to find "\\.dbf"
at the end of the string using the $
character:
list.files(pattern = "\\.dbf$")
A set
is an unordered data structure, so it does not preserve the insertion order.
This depends on your requirements. If you have an normal list, and want to remove some set of elements while preserving the order of the list, you can do this with a list comprehension:
>>> a = [1, 2, 20, 6, 210]
>>> b = set([6, 20, 1])
>>> [x for x in a if x not in b]
[2, 210]
If you need a data structure that supports both fast membership tests and preservation of insertion order, you can use the keys of a Python dictionary, which starting from Python 3.7 is guaranteed to preserve the insertion order:
>>> a = dict.fromkeys([1, 2, 20, 6, 210])
>>> b = dict.fromkeys([6, 20, 1])
>>> dict.fromkeys(x for x in a if x not in b)
{2: None, 210: None}
b
doesn't really need to be ordered here – you could use a set
as well. Note that a.keys() - b.keys()
returns the set difference as a set
, so it won't preserve the insertion order.
In older versions of Python, you can use collections.OrderedDict
instead:
>>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210])
>>> b = collections.OrderedDict.fromkeys([6, 20, 1])
>>> collections.OrderedDict.fromkeys(x for x in a if x not in b)
OrderedDict([(2, None), (210, None)])
It was mentioned above that the mod_xsendfile method does not allow for non-ASCII characters in filenames.
For this reason, I have a patch available for mod_xsendfile that will allow any file to be sent, as long as the name is url encoded, and the additional header:
X-SendFile-Encoding: url
Is sent as well.
public class MyActivity extends Activity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int CONTACTS_LOADER_ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(CONTACTS_LOADER_ID,
null,
this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
if (id == CONTACTS_LOADER_ID) {
return contactsLoader();
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//The framework will take care of closing the
// old cursor once we return.
List<String> contacts = contactsFromCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
}
private Loader<Cursor> contactsLoader() {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts
String[] projection = { // The columns to return for each row
ContactsContract.Contacts.DISPLAY_NAME
} ;
String selection = null; //Selection criteria
String[] selectionArgs = {}; //Selection criteria
String sortOrder = null; //The sort order for the returned rows
return new CursorLoader(
getApplicationContext(),
contactsUri,
projection,
selection,
selectionArgs,
sortOrder);
}
private List<String> contactsFromCursor(Cursor cursor) {
List<String> contacts = new ArrayList<String>();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contacts.add(name);
} while (cursor.moveToNext());
}
return contacts;
}
}
and do not forget
<uses-permission android:name="android.permission.READ_CONTACTS" />
You should notice that this
depends on how function is invoked
ie: when a function is called as a method of an object, its this
is set to the object the method is called on.
this
is accessible in JSX context as your component object, so you can call your desired method inline as this
method.
If you just pass reference to function/method, it seems that react will invoke it as independent function.
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
You can do something similar to this:
// Get the parent to attatch the element into
var parent = document.getElementsByTagName("ul")[0];
// Create element with random id
var element = document.createElement("li");
element.id = "li-"+Math.floor(Math.random()*9999);
// Add event listener
element.addEventListener("click", EVENT_FN);
// Add to parent
parent.appendChild(element);
The first way is the older standard. The second method was introduced in SQL-92, http://en.wikipedia.org/wiki/SQL. The complete standard can be viewed at http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt .
It took many years before database companies adopted the SQL-92 standard.
So the reason why the second method is preferred, it is the SQL standard according the ANSI and ISO standards committee.
For SBT use below mergeStrategy in build.sbt
mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => {
case PathList("META-INF", "services", "org.apache.hadoop.fs.FileSystem") => MergeStrategy.filterDistinctLines
case s => old(s)
}
}
Or, even cleaner:
when(mockFoo.someMethod()).thenReturn(obj1, obj2);
You can use both. The css style will override the size
attribute in browsers that support CSS and make the field the correct width, and for those that don't, it will fall back to the specified number of characters.
Edit: I should have mentioned that the size
attribute isn't a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.
However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.
The snippet below demonstrates both approaches.
@font-face {_x000D_
font-family: 'Diplomata';_x000D_
font-style: normal;_x000D_
font-weight: 400;_x000D_
src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');_x000D_
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
@font-face {_x000D_
font-family: 'Open Sans Condensed';_x000D_
font-style: normal;_x000D_
font-weight: 300;_x000D_
src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');_x000D_
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
p {_x000D_
margin: 0 0 10px 0;_x000D_
}_x000D_
input {_x000D_
font-size: 20px;_x000D_
}_x000D_
.narrow-font {_x000D_
font-family: 'Open Sans Condensed', sans-serif;_x000D_
}_x000D_
.wide-font {_x000D_
font-family: 'Diplomata', cursive;_x000D_
}_x000D_
.set-width {_x000D_
width: 220px;_x000D_
}
_x000D_
<p>_x000D_
<input type="text" size="10" class="narrow-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
<input type="text" size="10" class="wide-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
<input type="text" size="10" class="narrow-font set-width" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
<input type="text" size="10" class="wide-font set-width" value="0123456789" />_x000D_
</p>
_x000D_
Do you have a "shared object" (usually a shared library on AIX), a UNIX shared library, or a Windows DLL? These are all different things, and your question conflates them all :-(
dump -Tv /path/to/foo.o
.readelf -Ws /path/to/libfoo.so
, or (if you have GNU nm) nm -D /path/to/libfoo.so
.dumpbin /EXPORTS foo.dll
.On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
We need to use Angular Js built in function $apply to acsess scope variables or functions outside the controller function.
This can be done in two ways :
|*| Method 1 : Using Id :
<div id="nameNgsDivUid" ng-app="">
<a onclick="actNgsFnc()"> Activate Angular Scope</a><br><br>
{{ nameNgsVar }}
</div>
<script type="text/javascript">
var nameNgsDivVar = document.getElementById('nameNgsDivUid')
function actNgsFnc()
{
var scopeNgsVar = angular.element(nameNgsDivVar).scope();
scopeNgsVar.$apply(function()
{
scopeNgsVar.nameNgsVar = "Tst Txt";
})
}
</script>
|*| Method 2 : Using init of ng-controller :
<div ng-app="nameNgsApp" ng-controller="nameNgsCtl">
<a onclick="actNgsFnc()"> Activate Angular Scope</a><br><br>
{{ nameNgsVar }}
</div>
<script type="text/javascript">
var scopeNgsVar;
var nameNgsAppVar=angular.module("nameNgsApp",[])
nameNgsAppVar.controller("nameNgsCtl",function($scope)
{
scopeNgsVar=$scope;
})
function actNgsFnc()
{
scopeNgsVar.$apply(function()
{
scopeNgsVar.nameNgsVar = "Tst Txt";
})
}
</script>
When the color of text is dark, in Safari and Chrome, I have better result with the text-stroke css property.
-webkit-text-stroke: 0.5px #000;
You'll want to use the formatting macros from inttypes.h.
See this question: Cross platform format string for variables of type size_t?
Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...
In your code $this->uri->segment(3)
refers to the pagination offset
which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;
, $this->uri->segment(3)
i.e segment 3 refers to the offset. The first segment is the controller
, second is the method
, there after comes the parameters
sent to the controllers as segments
.
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--
you must chmod and chown the new folder
chown -R redis and chmod ...
If you are only looking for images and multiple selection.
Look @ once https://stackoverflow.com/a/15029515/1136023
It's helpful for future.I personally feel great by using MultipleImagePick.
This works for me in Django 1.8
def clean(self):
if self.cleaned_data['name'] != self.initial['name']:
# Do something
You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL
but also PERL5OPT=-Mutf8
.
https://golang.org/ref/spec#For_range
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.
As an example:
for index, element := range someSlice {
// index is the index where we are
// element is the element from someSlice for where we are
}
If you don't care about the index, you can use _
:
for _, element := range someSlice {
// element is the element from someSlice for where we are
}
The underscore, _
, is the blank identifier, an anonymous placeholder.
The usual way
The usual way to create what you're asking for, is to simply do the following:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "The status update text");
startActivity(Intent.createChooser(intent, "Dialog title text"));
This works without any issues for me.
The alternative way (maybe)
The potential problem with doing this, is that you're also allowing the message to be sent via e-mail, SMS, etc. The following code is something I'm using in an application, that allows the user to send me an e-mail using Gmail. I'm guessing you could try to change it to make it work with Facebook only.
I'm not sure how it responds to any errors or exceptions (I'm guessing that would occur if Facebook is not installed), so you might have to test it a bit.
try {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String[] recipients = new String[]{"e-mail address"};
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "E-mail subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "E-mail text");
emailIntent.setType("plain/text"); // This is incorrect MIME, but Gmail is one of the only apps that responds to it - this might need to be replaced with text/plain for Facebook
final PackageManager pm = getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") ||
info.activityInfo.name.toLowerCase().contains("gmail")) best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
startActivity(emailIntent);
} catch (Exception e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
Put a file named log4j.xml
into your classpath. Contents are e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %t %c{1}:%L - %m%n"/>
</layout>
</appender>
<root>
<level value="debug"/>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>
You can set FileAppender dynamically
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"logname."+new Date().toLocaleString(),false);
logger.addAppender(appender);
This is exactly what you need. See it in action here 8FydL/445
Example's Code below:
$(".dropdown img.flag").addClass("flagvisibility");_x000D_
$(".dropdown dt a").click(function() {_x000D_
$(".dropdown dd ul").toggle();_x000D_
});_x000D_
_x000D_
$(".dropdown dd ul li a").click(function() {_x000D_
var text = $(this).html();_x000D_
$(".dropdown dt a span").html(text);_x000D_
$(".dropdown dd ul").hide();_x000D_
$("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
});_x000D_
_x000D_
function getSelectedValue(id) {_x000D_
return $("#" + id).find("dt a span.value").html();_x000D_
}_x000D_
_x000D_
$(document).bind('click', function(e) {_x000D_
var $clicked = $(e.target);_x000D_
if (! $clicked.parents().hasClass("dropdown"))_x000D_
$(".dropdown dd ul").hide();_x000D_
});_x000D_
_x000D_
$(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
.desc { color:#6b6b6b;}_x000D_
.desc a {color:#0092dd;}_x000D_
_x000D_
.dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
.dropdown dd { position:relative; }_x000D_
.dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
.dropdown a:hover { color:#5d4617;}_x000D_
.dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
.dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
border:1px solid #d4ca9a; width:150px;}_x000D_
.dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
.dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
.dropdown span.value { display:none;}_x000D_
.dropdown dd ul li a { padding:5px; display:block;}_x000D_
.dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
_x000D_
.dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
.flagvisibility { display:none;}
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
<dl id="sample" class="dropdown">_x000D_
<dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
<dd>_x000D_
<ul>_x000D_
<li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
<li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
_x000D_
</ul>_x000D_
</dd>_x000D_
</dl>_x000D_
<span id="result"></span>
_x000D_
change the div to display block
.topbar{
display:block;
width:100%;
height:70px;
background-color:#475;
overflow:scroll;
}
i made a jsfiddle example here please check
It happened to me simply because of broken permissions. My user did not have read nor write access to that file. Fixing permissions fixed the problem
The following works without flattening the folder structure:
gulp.src(['input/folder/**/*']).pipe(gulp.dest('output/folder'));
The '**/*'
is the important part. That expression is a glob which is a powerful file selection tool. For example, for copying only .js files use: 'input/folder/**/*.js'
WordPad will open any text file no matter the size. However, it has limited capabilities as compared to a text editor.
$('#myDiv').hide();
hide function is used to edit content and show function is used to show again.
For more please click on this link.
This is the best way, because if user not back more than two seconds then reset backpressed value.
declare one global variable.
private boolean backPressToExit = false;
Override
onBackPressed
Method.
@Override
public void onBackPressed() {
if (backPressToExit) {
super.onBackPressed();
return;
}
this.backPressToExit = true;
Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backPressToExit = false;
}
}, 2000);
}
SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group
That works to get the max date..join it back to your data to get the other columns:
Select group,max_date,checks
from table t
inner join
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date
Inner join functions as the filter to get the max record only.
FYI, your column names are horrid, don't use reserved words for columns (group, date, table).
This works for me in PowerShell:
docker run --rm -v ${PWD}:/data alpine ls /data
Try this tool Javascript Obfuscator
I used it on my HTML5 game not only it reduced it size from 950KB to 150 but also made the source code unreadable closure compilers and minifiers are reversable I personally dont know how to reverse this obfuscation.
I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary
NSArray *array = mutableArray;
This [mutableArray copy]
antipattern is all over sample code. Stop doing so for throwaway mutable arrays that are transient and get deallocated at the end of the current scope.
There is no way the runtime could optimize out the wasteful copying of a mutable array that is just about to go out of scope, decrefed to 0 and deallocated for good.
Follow the steps below:
1) Select your VM Instance. Go to Settings->Storage
2) Under the storage tree select the default image or "Empty"
(which ever is present)
3) Under the attributes frame, click on the CD image and select "Choose a virtual CD/DVD disk file
"
4) Browse and select the image file(iso or what ever format) from the system
5) Select OK.
Abishek's solution is correct. But the highlighted area in 2nd image could be misleading.
This code segment for your Model
function getCount($tblName){
$query = $this->db->get($tblName);
$rowCount = $query->num_rows();
return $rowCount;
}
This is for controlr
public function index() {
$data['employeeCount']= $this->CMS_model->getCount("employee");
$this->load->view("hrdept/main",$data);
}
This is for view
<div class="count">
<?php echo $employeeCount; ?>
</div>
This code is used in my project and is working properly.
In modern browsers, there are two types of notifications:
The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.
Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost://
or HTTPS.
// request permission on page load_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
if (!Notification) {_x000D_
alert('Desktop notifications not available in your browser. Try Chromium.');_x000D_
return;_x000D_
}_x000D_
_x000D_
if (Notification.permission !== 'granted')_x000D_
Notification.requestPermission();_x000D_
});_x000D_
_x000D_
_x000D_
function notifyMe() {_x000D_
if (Notification.permission !== 'granted')_x000D_
Notification.requestPermission();_x000D_
else {_x000D_
var notification = new Notification('Notification title', {_x000D_
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',_x000D_
body: 'Hey there! You\'ve been notified!',_x000D_
});_x000D_
notification.onclick = function() {_x000D_
window.open('http://stackoverflow.com/a/13328397/1269037');_x000D_
};_x000D_
}_x000D_
}
_x000D_
<button onclick="notifyMe()">Notify me!</button>
_x000D_
We're using the W3C Notifications API. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.
W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.
Note that Chrome doesn't honor the notification icon on Linux, due to this bug.
Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.
Now the latest standard is at https://notifications.spec.whatwg.org/.
As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.
See also notify.js for a helper library.
If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:
build.gradle
, change compileSdkVersion
to 23
and buildToolsVersion
to 24.0.0
gradle build
It allows you to queue up animations... for example, instead of this
$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);
Which fades the element and makes the width 100 px at the same time. Using the queue allows you to stage the animations. So one finishes after the other.
$("#show").click(function () {
var n = $("div").queue("fx");
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
Example from http://docs.jquery.com/Effects/queue
I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...
The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf
file is below...
# Virtual Hosts
#
# Required modules: mod_log_config
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
##ServerName dummy-host.example.com
##ServerAlias www.dummy-host.example.com
##ErrorLog "logs/dummy-host.example.com-error.log"
##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
##ServerName dummy-host2.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
</Directory>
</VirtualHost>
I then updated my C:\windows\System32\drivers\etc\hosts
file like this...
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 dev.middleweek.co.uk
127.0.0.1 localhost
Restart your machine for good measure, open the XAMPP Control Panel and start Apache.
Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk
Hope that helps someone!
And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf
to include "Options Indexes" like this...
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
Options Indexes
</Directory>
</VirtualHost>
Cheers, Nick
I had to reinstall pdAdmin to resolve this issue
brew cask reinstall pgadmin4
You have to update the php.ini config file with in your host provider's server, trust me on this, more than likely there is nothing wrong with your code. It took me almost a month and a half to realize that most hosting servers are not up to date on php.ini files, eg. php 5.5 or later, I believe.
You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com
somewhere in the config.
@Ed courtenay, @James, I have one stupid question. How to keep user away from this file?(File containing expiry date). If the user has installation rights, then obviously user has access to view files also. Changing the extension of file wont help. So, how to keep this file safe and away from users hands?
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
I verify XPath and CSS selectors using WebSync Chrome extension.
It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.
https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac
I combined the template format used by John Myczek and Tri Q's algorithm above to create a findChild Algorithm that can be used on any parent. Keep in mind that recursively searching a tree downwards could be a lengthy process. I've only spot-checked this on a WPF application, please comment on any errors you might find and I'll correct my code.
WPF Snoop is a useful tool in looking at the visual tree - I'd strongly recommend using it while testing or using this algorithm to check your work.
There is a small error in Tri Q's Algorithm. After the child is found, if childrenCount is > 1 and we iterate again we can overwrite the properly found child. Therefore I added a if (foundChild != null) break;
into my code to deal with this condition.
/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found,
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
Call it like this:
TextBox foundTextBox =
UIHelper.FindChild<TextBox>(Application.Current.MainWindow, "myTextBoxName");
Note Application.Current.MainWindow
can be any parent window.
You could use the query:
select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION, DATETIME_PRECISION,
IS_NULLABLE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='TableName'
to get all the metadata you require except for the Pk information.
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
I had a similar problem on one of my Linux machines. Generating fresh certificates and exporting an environment variable pointing to the certificates directory fixed it for me:
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
If the above solution doesn't work, check to see if you have $(LibraryPath) in Properties->VC++ Directories->Library Directories. If you are missing it, try adding it.
See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/>
button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )
btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs
Assuming that you are using nvm
and multiple versions of node installed, here is the solution:
npm install -g react-native-cli
in node v6.9.5
. node v6.9.5
as default by running nvm alias default 6.9.5
react-native run-ios
The problem is, you have multiple versions of node installed via nvm
and to install react-native-cli
you have switched or installed latest version of node, which is not marked as default node to point in nvm
yet. When you run react-native run-ios
this opens up another new terminal window in which default nvm
is not pointed to the node version where you have installed react-native-cli
. Just follow the above setup, I hope that should help.
DateFormat.format
only works on Date
values.
You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:
// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);
String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);
EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
basically, look for everything at the beginning except _
, and then the _2
.
+1 to @Ananda_Mahto for suggesting grepl
instead of grep
.
I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.
The HTTP 1.1 RFC explicitly states:
Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferred with a secure protocol.
Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.
This style is for full reset for tables - cellpadding, cellspacing and borders.
I had this style in my reset.css file:
table{
border:0; /* Replace border */
border-spacing: 0px; /* Replace cellspacing */
border-collapse: collapse; /* Patch for Internet Explorer 6 and Internet Explorer 7 */
}
table td{
padding: 0px; /* Replace cellpadding */
}
You should simply apply the following transformation to your input data array.
input_data = input_data.reshape((-1, image_side1, image_side2, channels))
Bonus info: border-radius
has no effect on tables with border-collapse: collapse;
and border set on td
's. And it doesn't matter if border-radius
is set on table
, tr
or td
—it's ignored.
The easiest solution I found was to simply put that in your fragment :
androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(getActivity(),
R.id.nav_host_fragment);
navController.navigate(R.id.action_position_to_destination);
}
});
Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.
On my CentOS 6 I have two openssl.cnf :
/openvpn/easy-rsa/
/pki/tls/
The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.
From the documentation:
The BuildAction property indicates what Visual Studio does with a file when a build is executed. BuildAction can have one of several values:
None - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Compile - The file is compiled into the build output. This setting is used for code files.
Content - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.
Embedded Resource - This file is embedded in the main project build output as a DLL or executable. It is typically used for resource files.
Here's a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.
<div>
<input type="checkbox" id="checkboxID" name="checkboxName" value="whatever" />
<label for="checkboxID"> </label>
</div>
Style the label
with what you want the checkbox to look like
#checkboxID
{
position: absolute fixed;
margin-right: 2000px;
right: 100%;
}
#checkboxID + label
{
/* unchecked state */
}
#checkboxID:checked + label
{
/* checked state */
}
For javascript, you'll be able to add classes to the label to show the state. Also, it would be wise to use the following function:
$('label[for]').live('click', function(e){
$('#' + $(this).attr('for') ).click();
return false;
});
EDIT to modify #checkboxID
styles
SynchronizedMap
and ConcurrentHashMap
are both thread safe class and can be used in multithreaded application, the main difference between them is regarding how they achieve thread safety.
SynchronizedMap
acquires lock on the entire Map instance , while ConcurrentHashMap
divides the Map instance into multiple segments and locking is done on those.
Update:
Read the Docs for your version of Django. e.g.
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#admin-overriding-templates
Original answer from 2011:
I had the same issue about a year and a half ago and I found a nice template loader on djangosnippets.org that makes this easy. It allows you to extend a template in a specific app, giving you the ability to create your own admin/index.html that extends the admin/index.html template from the admin app. Like this:
{% extends "admin:admin/index.html" %}
{% block sidebar %}
{{block.super}}
<div>
<h1>Extra links</h1>
<a href="/admin/extra/">My extra link</a>
</div>
{% endblock %}
I've given a full example on how to use this template loader in a blog post on my website.
It seems to me that those people who never learned Lisp or Scheme as an undergraduate are now discovering it. As with a lot of things in this field there is a tendency to hype and create high expectations...
It will pass.
Functional programming is great. However, it will not take over the world. C, C++, Java, C#, etc will still be around.
What will come of this I think is more cross-language ability - for example implementing things in a functional language and then giving access to that stuff in other languages.
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
In recent Visual Studio Code versions you can find settings here:
Menu File → Preference → Settings → Text Editor → Files → (scroll down a bit) Trim Trailing Whitespace
This is for trimming whitespace when saving a file.
Or you can search "Trim Trailing Whitespace" in the top search bar.
From Microsoft MSDN recommendations:
Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.
So we have already standard recommended sizes of:
If we would like to support high DPI settings, the complete list will include the following sizes as well:
EDIT: it was fixed in EF version 6.1.1. and this answer is no more actual
For SQL Server and EF4-6, Count() performs about two times faster than Any().
When you run Table.Any(), it will generate something like(alert: don't hurt the brain trying to understand it)
SELECT
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [Table] AS [Extent1]
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT
1 AS [C1]
FROM [Table] AS [Extent2]
)) THEN cast(0 as bit) END AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
that requires 2 scans of rows with your condition.
I don't like to write Count() > 0
because it hides my intention. I prefer to use custom predicate for this:
public static class QueryExtensions
{
public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
return source.Count(predicate) > 0;
}
}
Assuming you are on Linux, check if php-fpm is running by searching through the process list:
ps aux | grep php-fpm
If running over IP (as opposed to over Unix socket) then you can also check for the port:
netstat -an | grep :9000
Or using nmap:
nmap localhost -p 9000
Lastly, I've read that you can request the status, but in my experience this has proven unreliable:
/etc/init.d/php5-fpm status
The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new
can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.
To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.
A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.
As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.
Getting the friends like @nfvs describes is a good way. It outputs a multi-dimensional array with all friends with attributes id and name (ordered by id). You can see the friends photos like this:
foreach ($friends as $key=>$value) {
echo count($value) . ' Friends';
echo '<hr />';
echo '<ul id="friends">';
foreach ($value as $fkey=>$fvalue) {
echo '<li><img src="https://graph.facebook.com/' . $fvalue->id . '/picture" title="' . $fvalue->name . '"/></li>';
}
echo '</ul>';
}
Use jline3:
Example:
Terminal terminal = TerminalBuilder.builder()
.jna(true)
.system(true)
.build();
// raw mode means we get keypresses rather than line buffered input
terminal.enterRawMode();
reader = terminal .reader();
...
int read = reader.read();
....
reader.close();
terminal.close();
You can just write your chars as Strings and use the equals method.
For Example:
String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";
if (firstChar.equalsIgnoreCase(secondChar) ||
(firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
System.out.println(firstChar + " is the same as " + secondChar);
} else {
System.out.println(firstChar + " is different than " + secondChar);
}
You need to use some JavaScript stuff to show your map. OpenLayers is the number one choice for this.
There is an example at http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example and something more advanced at
http://wiki.openstreetmap.org/wiki/OpenLayers_Marker
and
http://wiki.openstreetmap.org/wiki/Openlayers_POI_layer_example
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Beside accepted answer, you need to hold a reference of listener and remove when you don't need it. Otherwise you will get a null pointer exception for your ScrollView and memory leak (mentioned in comments of accepted answer).
You can implement OnScrollChangedListener in your activity/fragment.
MyFragment : ViewTreeObserver.OnScrollChangedListener
Add it to scrollView when your view is ready.
scrollView.viewTreeObserver.addOnScrollChangedListener(this)
Remove listener when no longer need (ie. onPause())
scrollView.viewTreeObserver.removeOnScrollChangedListener(this)
You can use this:
return Content(HttpStatusCode.BadRequest, "Any object");
http://docs.python.org/library/configparser.html
Python's standard library might be helpful in this case.
Your second example will reset the exception's stack trace. The first most accurately preserves the origins of the exception. Also you've unwrapped the original type which is key in knowing what actually went wrong... If the second is required for functionality - e.g. To add extended info or re-wrap with special type such as a custom 'HandleableException' then just be sure that the InnerException property is set too!
First create a blank database of the same name. Then go for the restore option
Under Options on the left pane don't forget to select
That's it
You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.
So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.
As required in Question::
var string1= "foo/bar/test.html";
if(string1.contains("/"))
{
var string_parts = string1.split("/");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]
var string1= "Hello how are =you";
if(string1.contains("="))
{
var string_parts = string1.split("=");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
For the html code:
test.html
<button class="dismiss" onclick="alert('hello')">
<string for="exit">Dismiss</string>
</button>
the below python code worked for me. You can just try it.
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()
I had a more specifc error message that stated to remove 'Office 16 Click-to-Run Extensibility Component'
I fixed it by following the steps in https://www.tecklyfe.com/fix-for-microsoft-office-setup-error-please-uninstall-all-32-bit-office-programs-office-15-click-to-run-extensibility-component/
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
{{ wpis.entry.lastChangeDate|date:"SHORT_DATETIME_FORMAT" }}
Once should avoid emulating classical OO and use prototypical OO instead. A nice utility library for prototypical OO is traits.
Rather then overwriting methods and setting up inheritance chains (one should always favour object composition over object inheritance) you should be bundling re-usable functions into traits and creating objects with those.
var modifyA = {
modify: function() {
this.x = 300;
this.y = 400;
}
};
var modifyB = {
modify: function() {
this.x = 3000;
this.y = 4000;
}
};
C = function(trait) {
var o = Object.create(Object.prototype, Trait(trait));
o.modify();
console.log("sum : " + (o.x + o.y));
return o;
}
//C(modifyA);
C(modifyB);
If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run setup.py develop
to semi-install the working tree in your current Python installation.
use <meta http-equiv="X-Frame-Options" content="allow">
in the one to show in the iframe to allow it.
I figured I would throw in my implementation since I believe it covers all of the cases that have been touched on by the others and does so in a concise way that is still readable.
public static string Truncate(this string value, int maxLength)
{
if (!string.IsNullOrEmpty(value) && value.Length > maxLength)
{
return value.Substring(0, maxLength);
}
return value;
}
This solution mainly builds upon the Ray's solution and opens up the method for use as an extension method by using the this keyword just as LBushkin does in his solution.
String strLong = Long.toString(longNumber);
Simple and works fine :-)
In windows for me it kept saying "id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.
This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135
This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")
In addition to Kassim's answer:
As Peter says, they won't be in Maven Central
Either use maven-android-sdk-deployer to deploy the libraries to your local repository
Or from Android SDK Manager download the Android Support Repository (in Extras) and an M2 repo of the support libraries will be downloaded to your Android SDK directory
I also had to update the "Local Maven repository for Support Libraries" in Android SDK Manager.
If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from forms.ModelForm
, and then inherit from it
class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'someClass'
class WhateverForm(BaseForm):
class Meta:
model = SomeModel
This helped me to add the 'form-control'
class to all of the fields on all of the forms of my application automatically, without adding replication of code.
I found this worked best for my usecase:
<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>
The division operator is /
rather than \
.
Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:
"\\ 1.5 = "`
or use a raw string
r" \ 1.5 = "
var canvas = document.getElementById("my-canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
_x000D_
context.fillStyle = "blue";_x000D_
context.font = "bold 16px Arial";_x000D_
context.fillText("Zibri", (canvas.width / 2) - 17, (canvas.height / 2) + 8);
_x000D_
#my-canvas {_x000D_
background: #FF0;_x000D_
}
_x000D_
<canvas id="my-canvas" width="200" height="120"></canvas>
_x000D_
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
I had weird situation when i need to print react component which receives big amount of data and paint in on canvas. I've tried all mentioned approaches, non of them worked reliably for me, with requestAnimationFrame inside setTimeout i get empty canvas in 20% of the time, so i did the following:
nRequest = n => range(0,n).reduce(
(acc,val) => () => requestAnimationFrame(acc), () => requestAnimationFrame(this.save)
);
Basically i made a chain of requestAnimationFrame's, not sure is this good idea or not but this works in 100% of the cases for me so far (i'm using 30 as a value for n variable).
We used to run a social website, on a standard LAMP configuration. We had a Live server, Test server, and Development server, as well as the local developers machines. All were managed using GIT.
On each machine, we had the PHP files, but also the MySQL service, and a folder with Images that users would upload. The Live server grew to have some 100K (!) recurrent users, the dump was about 2GB (!), the Image folder was some 50GB (!). By the time that I left, our server was reaching the limit of its CPU, Ram, and most of all, the concurrent net connection limits (We even compiled our own version of network card driver to max out the server 'lol'). We could not (nor should you assume with your website) put 2GB of data and 50GB of images in GIT.
To manage all this under GIT easily, we would ignore the binary folders (the folders containing the Images) by inserting these folder paths into .gitignore. We also had a folder called SQL outside the Apache documentroot path. In that SQL folder, we would put our SQL files from the developers in incremental numberings (001.florianm.sql, 001.johns.sql, 002.florianm.sql, etc). These SQL files were managed by GIT as well. The first sql file would indeed contain a large set of DB schema. We don't add user-data in GIT (eg the records of the users table, or the comments table), but data like configs or topology or other site specific data, was maintained in the sql files (and hence by GIT). Mostly its the developers (who know the code best) that determine what and what is not maintained by GIT with regards to SQL schema and data.
When it got to a release, the administrator logs in onto the dev server, merges the live branch with all developers and needed branches on the dev machine to an update branch, and pushed it to the test server. On the test server, he checks if the updating process for the Live server is still valid, and in quick succession, points all traffic in Apache to a placeholder site, creates a DB dump, points the working directory from 'live' to 'update', executes all new sql files into mysql, and repoints the traffic back to the correct site. When all stakeholders agreed after reviewing the test server, the Administrator did the same thing from Test server to Live server. Afterwards, he merges the live branch on the production server, to the master branch accross all servers, and rebased all live branches. The developers were responsible themselves to rebase their branches, but they generally know what they are doing.
If there were problems on the test server, eg. the merges had too many conflicts, then the code was reverted (pointing the working branch back to 'live') and the sql files were never executed. The moment that the sql files were executed, this was considered as a non-reversible action at the time. If the SQL files were not working properly, then the DB was restored using the Dump (and the developers told off, for providing ill-tested SQL files).
Today, we maintain both a sql-up and sql-down folder, with equivalent filenames, where the developers have to test that both the upgrading sql files, can be equally downgraded. This could ultimately be executed with a bash script, but its a good idea if human eyes kept monitoring the upgrade process.
It's not great, but its manageable. Hope this gives an insight into a real-life, practical, relatively high-availability site. Be it a bit outdated, but still followed.
The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
Enabling a previously-installed Sublime Text package
If you have a subdirectory under Sublime Text 2\Packages
for a package that isn't working, you may need to enable it.
Follow these steps to enable an installed package:
Preferences > Package Control > Enable Package
sort()
was deprecated for DataFrames in favor of either:
sort_values()
to sort by column(s)sort_index()
to sort by the index sort()
was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values()
and sort_index()
. It was removed from Pandas with release 0.20 (2017-05-05).
I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.
I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int)
function.
Google eventually came up with the answer. The syntax for string replacement in batch is this:
set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%
Which produces "replicate me". My script now looks like this:
@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"
Which replaces all instances of "
with \"
, properly escaped for bash.
I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.
<html>
<pre style="background-color:#bcbbbb;">
@echo off
docker login --username=xxxx --password=xxxx
docker pull %1:%2
IF NOT %ERRORLEVEL%==0 (
echo "Specified Version is Not Found "
echo "Available Version for this image is :"
for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" https://hub.docker.com/v2/users/login ^|jq -r .token ') do set TOKEN=%%i
curl -sH "Authorization: JWT %TOKEN%" "https://hub.docker.com/v2/repositories/%1/tags/" | jq .results[].name
)
</pre>
</html>
So in this we can give arguments to out batch file like:
Dockerfile java version7
I found that @Stefan Haustein comes very close to my experience, but not sure 100%. My suggestion is:
setLeft()
/ setRight()
/ setBottom()
/ setTop()
won't work sometimes.setX()
/ setY()
instead. (You might want search more in difference setLeft()
and setX()
)Of course.
Declaring a class abstract only means that you don't allow it to be instantiated on its own.
Declaring a method abstract means that subclasses have to provide an implementation for that method.
The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final
methods but never the other way around.
I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.
To find the owner of a specific table in an Oracle DB, use the following query:
select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';
use
app:backgroundTint="@color/orange" in
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/id_share_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/share"
app:backgroundTint="@color/orange"
app:fabSize="mini"
app:layout_anchorGravity="end|bottom|center" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.
I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!
In jquery to send a user to a different URL you can do it like this:
$("a#thing_to_click").on('click', function(){
window.location = "http://www.google.com/";
});
this way will work too but the above is the newer more correct way to do it these days
$("a#thing_to_click").click(function(e){
e.preventDefault();
window.location = "http://www.google.com/";
});
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilà.
Instead of using input type button
you can use button
and insert the image inside the button content.
<button class="btn btn-default">
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>
The problem with doing this only with CSS is that you cannot set linear-gradient
to the background you must use solid color.
.sign-in-facebook {
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
.sign-in-facebook:hover {
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
body {_x000D_
padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
.sign-in-facebook {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
.sign-in-facebook:hover {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
Pure/vanilla JS solution (working example here)
// All elements with data-company="Microsoft" below "Companies"
let a = document.querySelectorAll("[data-group='Companies'] [data-company='Microsoft']");
// All elements with data-company!="Microsoft" below "Companies"
let b = document.querySelectorAll("[data-group='Companies'] :not([data-company='Microsoft'])");
In querySelectorAll you must use valid CSS selector (currently Level3)
SPEED TEST (2018.06.29) for jQuery and Pure JS: test was performed on MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit). Below screenshot shows results for fastest browser (Safari):
PureJS was faster than jQuery about 12% on Chrome, 21% on Firefox and 25% on Safari. Interestingly speed for Chrome was 18.9M operation per second, Firefox 26M, Safari 160.9M (!).
So winner is PureJS and fastest browser is Safari (more than 8x faster than Chrome!)
Here you can perform test on your machine: https://jsperf.com/js-selectors-x
I had an issue related to this and was reading
"Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\opencv\build\java\x86\opencv_java2413.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform "
and it took me an entire night to figure out.
I solved my problem by copying the dll in C:\opencv\build\java\x64
to my system32 folder. I hope this will be of help to someone.
Try
myString = 'abcabc'
myString.find('a')
This will give you the index!!!
For streaming protocols such as TCP, you can pretty much set your buffer to any size. That said, common values that are powers of 2 such as 4096 or 8192 are recommended.
If there is more data then what your buffer, it will simply be saved in the kernel for your next call to recv
.
Yes, you can keep growing your buffer. You can do a recv into the middle of the buffer starting at offset idx
, you would do:
recv(socket, recv_buffer + idx, recv_buffer_size - idx, 0);
if you use the "global" command, you can repeat what you can do on one online an any number of lines.
:g/<search>/.<your ex command>
example:
:g/foo/.s/bar/baz/g
The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.
:g/.*/
will do on every line
This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.
Inline JavaScript will not be executed. This restriction bans both inline
<script>
blocks and inline event handlers (e.g.<button onclick="...">
).
If this is indeed the problem, Chrome would produce the following error in the console:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.
More information on debugging a popup is available here.
One needs to remove all inline JavaScript. There is a guide in Chrome documentation.
Suppose the original looks like:
<a onclick="handler()">Click this</a> <!-- Bad -->
One needs to remove the onclick
attribute and give the element a unique id:
<a id="click-this">Click this</a> <!-- Fixed -->
And then attach the listener from a script (which must be in a .js
file, suppose popup.js
):
// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-this").addEventListener("click", handler);
});
// The handler also must go in a .js file
function handler() {
/* ... */
}
Note the wrapping in a DOMContentLoaded
event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head>
of the document:
<script src="popup.js"></script>
Alternative if you're using jQuery:
// jQuery
$(document).ready(function() {
$("#click-this").click(handler);
});
Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?
A: Despite what the error says, you cannot enable inline script:
There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes
'unsafe-inline'
will have no effect.
Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:
As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for
<script>
elements for an example.
However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code"
.
int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);
int mat[rows][cols];
printf("enter the matrix:");
for(i = 0; i < rows ; i++)
for(j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);
printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
for(j = 0; j < cols; j++)
{
printf("%d",mat[i][j]);
printf("\t");
}
printf("\n");
}
}
you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.
$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
A C string is defined as a pointer to an array of characters.
If you cannot have pointers, by definition you cannot have strings.
Very late to the party here but in case anyone else stumbles across this page...
You can do it by setting the AutoGeneratingColumn handler in XAML:
<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn" ..etc.. />
And then in code behind do something like this:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(System.DateTime))
(e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MM/yyyy";
}
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
<?php
/**
* Is Array?
* @param mixed $x
* @return bool
*/
function isArray($x) : bool {
return !isAssociative($x);
}
/**
* Is Associative Array?
* @param mixed $x
* @return bool
*/
function isAssociative($x) : bool {
if (!is_array($array)) {
return false;
}
$i = count($array);
while ($i > 0) {
if (!isset($array[--$i])) {
return true;
}
}
return false;
}
<?php
$arr = [ 'foo', 'bar' ];
$obj = [ 'foo' => 'bar' ];
var_dump(isAssociative($arr));
# bool(false)
var_dump(isAssociative($obj));
# bool(true)
var_dump(isArray($obj));
# bool(false)
var_dump(isArray($arr));
# bool(true)
At the end of the last line, you have a new line character, which is not read by >> operator and it is not an end of file. Please, make an experiment and delete the new line (thelast character in file) - you will not get the duplication. To have a flexible code and avoid unwanted effects just apply any solution given by other users.
Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?
That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.
split was updated in coreutils release 8.8 (announced 22 Dec 2010) with the --number option to generate a specific number of files. The option --number=l/n generates n files without splitting lines.
http://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html#split-invocation http://savannah.gnu.org/forum/forum.php?forum_id=6662
For Swift 3, the below code scales the image keeping the aspect ratio. You can read more about the ImageContext in Apple's documentation:
extension UIImage {
class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
To use it, call resizeImage()
method:
UIImage.resizeImage(image: yourImageName, newHeight: yourImageNewHeight)
Please, try this code:
import serial
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
print(port.device)
first of all, you need to import package for serial port communication, so:
import serial
then you create the list of all the serial ports currently available:
ports = serial.tools.list_ports.comports(include_links=False)
and then, walking along whole list, you can for example print port names:
for port in ports :
print(port.device)
This is just an example how to get the list of ports and print their names, but there some other options you can do with this data. Just try print different variants after
port.
background-image:url('image/img2.jpg');
background-repeat:repeat-x;
Use some image for internal image and use this.
Difficult to do this in NPP. Better way is following:
Download cygwin utility, it is simple Linux terminal under windows. It allow to execute any Linux command in Windows. And you have sort -u there.
TLDR; Visual Studio 2019 may simply need a restart.
I encountered this situation using projects based on Microsoft.NET.Sdk project.
<Project Sdk="Microsoft.NET.Sdk">
Specifically:
Project1
: targets .netstandard2.1
Microsoft.Extensions.Logging.Console
via NugetProject2
: targets .netstandard2.1
Project1
via a Project referenceProject2Tests
: targets .netcoreapp3.1
Project2
via a Project referenceAt test execution, I received the error messaging indicating that Microsoft.Extensions.Logging.Console
could not be found, and it was indeed not in the output directory.
I decided to work around the issue by adding Microsoft.Extensions.Logging.Console
to Project2
, only to discover that Visual Studio's Nuget Manager did not list Microsoft.Extensions.Logging.Console
as installed in Project1
, despite it's presence in the Project1.csproj
file.
A simple shut down and restart of Visual Studio resolved the problem without the need to add an extra reference. Perhaps this will save someone 45 minutes of lost productivity :-)
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
Use the TextInputLayout
provided by the Material Components Library:
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Label">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
It happens on different versions of ff. I'm using latest ff version 39 by using selenium-server-standalone-2.41.0.jar and selenium-java-2.41.0.zip which shows same error.
Get the latest server and client jar files here for the compatibility i used server and client versions 2.47.0 and 2.47.1 respectively. And Boom! It worked.
Based from this thread, you need to bookmark chrome://settings/languages
and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.
Use the method that accepts a Comparator
when you want to sort in something other than natural order.
I also ran into this fault when I used open(file_path)
. My reason for this fault was that my file_path
had a special character like "?"
or "<"
.