Using this solution, you will also be able to put the cursor at the end of newly text.
final TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextField(controller: _controller)),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.text = "Hello";
// this changes cursor position
_controller.selection = TextSelection.fromPosition(TextPosition(offset: _controller.text.length));
setState(() {});
},
),
);
}
You can also declare a focusNode for you textfield and when you are done you can just call the unfocus method on that focusNode and also dispose it
class MyHomePage extends StatefulWidget {
MyHomePageState createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = new TextEditingController();
/// declare focus
final FocusNode _titleFocus = FocusNode();
@override
void dispose() {
_titleFocus.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.send),
onPressed: () {
setState(() {
// send message
// dismiss on screen keyboard here
_titleFocus.unfocus();
_controller.clear();
});
},
),
body: new Container(
alignment: FractionalOffset.center,
padding: new EdgeInsets.all(20.0),
child: new TextFormField(
controller: _controller,
focusNode: _titleFocus,
decoration: new InputDecoration(labelText: 'Example Text'),
),
),
);
}
}
Here is one more way to specify event.target
:
import { Component, EventEmitter, Output } from '@angular/core';_x000D_
_x000D_
@Component({_x000D_
selector: 'text-editor',_x000D_
template: `<textarea (keyup)="emitWordCount($event)"></textarea>`_x000D_
})_x000D_
export class TextEditorComponent {_x000D_
_x000D_
@Output() countUpdate = new EventEmitter<number>();_x000D_
_x000D_
emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there_x000D_
_x000D_
this.countUpdate.emit(_x000D_
// using it directly without `event`_x000D_
(target.value.match(/\S+/g) || []).length);_x000D_
}_x000D_
}
_x000D_
Swift 4.2
let closure = { [weak self] (_ parameter:Int) in
guard let self = self else { return }
self.method(parameter)
}
Starting with xdebug 3 you can use the following command line :
php -r "xdebug_info();"
And it will display useful information about your xdebug installation.
Gathering solutions from multiple places here on StackOverflow, I think the next one sums it up:
If you don't need the keyboard to be shown anywhere on your activity, you can simply use the next flags which are used for dialogs (got from here) :
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
If you don't want it only for a specific EditText, you can use this (got from here) :
public static boolean disableKeyboardForEditText(@NonNull EditText editText) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
return true;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
try {
final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
return false;
}
Or this (taken from here) :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
editText.setShowSoftInputOnFocus(false);
else
editText.setTextIsSelectable(true);
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<table class="table table-bordered">_x000D_
<thead>_x000D_
<tr>_x000D_
<th></th>_x000D_
<th class="text-center">Left</th>_x000D_
<th class="text-center">Center</th>_x000D_
<th class="text-center">Right</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<th>_x000D_
<span>Bootstrap (class="text-left")</span>_x000D_
</th>_x000D_
<td class="text-left">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
<td class="text-center">_x000D_
<input type="checkbox" checked />_x000D_
</td>_x000D_
<td class="text-right">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>_x000D_
<span>HTML attribute (align="left")</span>_x000D_
</th>_x000D_
<td align="left">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
<td align="center">_x000D_
<input type="checkbox" checked />_x000D_
</td>_x000D_
<td align="right">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Converting already utf-8 encoded text by using mb_convert_encoding
is not needed. Just add three characters in front of the original content:
$newContent = chr(239) . chr(187) . chr(191) . $originalContent
For me this resolved the problem of special characters in csv files.
Make subl
available.
Put this in ~/.bash_profile
[[ -s ~/.bashrc ]] && source ~/.bashrc
Put this in ~/.bashrc
export EDITOR=subl
I have found solution by editing code as per following. There is no need to set Binding property first False then True.
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached(
"IsFocused", typeof(bool), typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d != null && d is Control)
{
var _Control = d as Control;
if ((bool)e.NewValue)
{
// To set false value to get focus on control. if we don't set value to False then we have to set all binding
//property to first False then True to set focus on control.
OnLostFocus(_Control, null);
_Control.Focus(); // Don't care about false values.
}
}
}
private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control)
{
(sender as Control).SetValue(IsFocusedProperty, false);
}
}
}
I had the same problem. 2.0 worked fine. after installing up to 3.5 sp1, application gets Access Violation.
installed http://support.microsoft.com/kb/971030 and my problem is solved, even though I am not using LCG.
Obsolete: This answer is correct only for an older version of Notepad++. Converting between tabs/spaces is now built into Notepad++ and the TextFX plugin is no longer available in the Plugin Manager dialog.
Preferences -> Language Menu/Tab Settings
.TextFX -> TextFX Edit -> Leading spaces to tabs or tabs to spaces
.Note: Make sure TextFX Characters plugin is installed (Plugins -> Plugin manager -> Show plugin manager
, Installed
tab). Otherwise, there will be no TextFX menu.
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
SELECT CAST(CAST(@DateField As Date) As DateTime) + CAST(CAST(@TimeField As Time) As DateTime)
if you know for sure the element is unique (such as your case with the ID):
myDiv.parentElement.querySelectorAll("#myDiv > .foo");
For a more "global" solution: (use a matchesSelector shim)
function getDirectChildren(elm, sel){
var ret = [], i = 0, l = elm.childNodes.length;
for (var i; i < l; ++i){
if (elm.childNodes[i].matchesSelector(sel)){
ret.push(elm.childNodes[i]);
}
}
return ret;
}
where elm
is your parent element, and sel
is your selector. Could totally be used as a prototype as well.
Per CSV format specification, I don't think it matters if data is correctly quoted or not, as long as it adheres to specification. Excessive quotes should be handled by the parser, if it's properly implemented. FIELDTERMINATOR
should be comma and ROWTERMINATOR
is line end - this denotes a standard CSV file. Did you try to import your data with these settings?
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
A quick way to list your FKs (Foreign Key references) using the
KEY_COLUMN_USAGE view:
SELECT CONCAT( table_name, '.',
column_name, ' -> ',
referenced_table_name, '.',
referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;
This query does assume that the constraints and all referenced and referencing tables are in the same schema.
Add your own comment.
Source: the official mysql manual.
<table class="blueTable">
<tr>
<td>My name is good</td>
</tr>
</table>
<style>
table.blueTable td,
table.blueTable th {
white-space: nowrap;
/* non-question related further styling */
border: 1px solid #AAAAAA;
padding: 3px 2px;
text-align: left;
}
</style>
This is an example usage of the white space property with value nowrap, the bluetable is the class of the table, below the table are the CSS styles.
Instead of using the referrer, you can implement window.postMessage
to communicate accross iframes/windows across domains.
You post to window.parent, and then parent returns the URL.
This works, but it requires asynchronous communication.
You will have to write a synchronous wrapper around the asynchronous methods, if you need it synchronous.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
// What browsers support the window.postMessage call now?
// IE8 does not allow postMessage across windows/tabs
// FF3+, IE8+, Chrome, Safari(5?), Opera10+
function SendMessage()
{
var win = document.getElementById("ifrmChild").contentWindow;
// http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/
// http://stackoverflow.com/questions/16072902/dom-exception-12-for-window-postmessage
// Specify origin. Should be a domain or a wildcard "*"
if (win == null || !window['postMessage'])
alert("oh crap");
else
win.postMessage("hello", "*");
//alert("lol");
}
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if (false) {
message = 'You ("' + evt.origin + '") are not worthy';
}
else {
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if (ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
//evt.source.postMessage("thanks, got it ;)", event.origin);
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
<br />
<input type="button" value="Test" onclick="SendMessage();" />
</body>
</html>
Child.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
/*
// Opera 9 supports document.postMessage()
// document is wrong
window.addEventListener("message", function (e) {
//document.getElementById("test").textContent = ;
alert(
e.domain + " said: " + e.data
);
}, false);
*/
// https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
// http://ejohn.org/blog/cross-window-messaging/
// http://benalman.com/projects/jquery-postmessage-plugin/
// http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
// .data – A string holding the message passed from the other window.
// .domain (origin?) – The domain name of the window that sent the message.
// .uri – The full URI for the window that sent the message.
// .source – A reference to the window object of the window that sent the message.
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if(false)
{
message = 'You ("' + evt.origin + '") are not worthy';
}
else
{
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
//alert(evt.source.location.href)
var ta = document.getElementById("taRecvMessage");
if(ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
// http://javascript.info/tutorial/cross-window-messaging-with-postmessage
//evt.source.postMessage("thanks, got it", evt.origin);
evt.source.postMessage("thanks, got it", "*");
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body style="background-color: gray;">
<h1>Test</h1>
<textarea id="taRecvMessage" rows="20" cols="20" ></textarea>
</body>
</html>
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
You can use CSS to do the trick:
$("#yourElement").css({ top: '100px' });
Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:
$.get('/service', function(data) {
var obj = data;
/*
"obj" is evaluated at this point if server responded
with "application/json" or similar.
*/
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].Name);
}
});
Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify
:
var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);
But in this case I don't understand why you can't just take the json
variable and refer to it instead of stringifying and parsing.
In my gulp setup, I'm specifying the vendor files first and then specifying the (more general) everything, second. And it successfully puts the vendor js before the other custom stuff.
gulp.src([
// vendor folder first
path.join(folder, '/vendor/**/*.js'),
// custom js after vendor
path.join(folder, '/**/*.js')
])
First subtract the pivot point (cx,cy)
, then rotate it, then add the point again.
Untested:
POINT rotate_point(float cx,float cy,float angle,POINT p)
{
float s = sin(angle);
float c = cos(angle);
// translate point back to origin:
p.x -= cx;
p.y -= cy;
// rotate point
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
// translate point back:
p.x = xnew + cx;
p.y = ynew + cy;
return p;
}
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
The getItem
method in the WebStorage specification, explicitly returns null
if the item does not exist:
... If the given key does not exist in the list associated with the object then this method must return null. ...
So, you can:
if (localStorage.getItem("infiniteScrollEnabled") === null) {
//...
}
See this related question:
Run below commands in Terminal:
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
Try this ...
StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// valid response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
// params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.
func textViewDidChange(_ textView: UITextView) {
tableView.beginUpdates()
if textView.text.contains("\n"){
textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
textView.resignFirstResponder()
}
tableView.endUpdates()
}
if you want remove the message that tells if the destination is a file or folder you just add a slash:
xcopy /s c:\Folder1 d:\Folder2\
In my case the problem was with SDK license acceptance. The problem was solved by downloading proper SDK version and license acceptance via SDK Manager.
based on OP's answer to question:
Please see this link. Its having a different solution, which looks working for the person who asked the question. I'm trying to figure out a solution like this.
Paginated query using sorting on different columns using ROW_NUMBER() OVER () in SQL Server 2005
~Joseph
"method 1" is like the OP's query from the linked question, and "method 2" is like the query from the selected answer. You had to look at the code linked in this answer to see what was really going on, since the code in the selected answer was modified to make it work. Try this:
DECLARE @YourTable table (RowID int not null primary key identity, Value1 int, Value2 int, value3 int)
SET NOCOUNT ON
INSERT INTO @YourTable VALUES (1,1,1)
INSERT INTO @YourTable VALUES (1,1,2)
INSERT INTO @YourTable VALUES (1,1,3)
INSERT INTO @YourTable VALUES (1,2,1)
INSERT INTO @YourTable VALUES (1,2,2)
INSERT INTO @YourTable VALUES (1,2,3)
INSERT INTO @YourTable VALUES (1,3,1)
INSERT INTO @YourTable VALUES (1,3,2)
INSERT INTO @YourTable VALUES (1,3,3)
INSERT INTO @YourTable VALUES (2,1,1)
INSERT INTO @YourTable VALUES (2,1,2)
INSERT INTO @YourTable VALUES (2,1,3)
INSERT INTO @YourTable VALUES (2,2,1)
INSERT INTO @YourTable VALUES (2,2,2)
INSERT INTO @YourTable VALUES (2,2,3)
INSERT INTO @YourTable VALUES (2,3,1)
INSERT INTO @YourTable VALUES (2,3,2)
INSERT INTO @YourTable VALUES (2,3,3)
INSERT INTO @YourTable VALUES (3,1,1)
INSERT INTO @YourTable VALUES (3,1,2)
INSERT INTO @YourTable VALUES (3,1,3)
INSERT INTO @YourTable VALUES (3,2,1)
INSERT INTO @YourTable VALUES (3,2,2)
INSERT INTO @YourTable VALUES (3,2,3)
INSERT INTO @YourTable VALUES (3,3,1)
INSERT INTO @YourTable VALUES (3,3,2)
INSERT INTO @YourTable VALUES (3,3,3)
SET NOCOUNT OFF
DECLARE @PageNumber int
DECLARE @PageSize int
DECLARE @SortBy int
SET @PageNumber=3
SET @PageSize=5
SET @SortBy=1
--SELECT * FROM @YourTable
--Method 1
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,CASE @SortBy
WHEN 1 THEN ROW_NUMBER() OVER (ORDER BY Value1 ASC)
WHEN 2 THEN ROW_NUMBER() OVER (ORDER BY Value2 ASC)
WHEN 3 THEN ROW_NUMBER() OVER (ORDER BY Value3 ASC)
WHEN -1 THEN ROW_NUMBER() OVER (ORDER BY Value1 DESC)
WHEN -2 THEN ROW_NUMBER() OVER (ORDER BY Value2 DESC)
WHEN -3 THEN ROW_NUMBER() OVER (ORDER BY Value3 DESC)
END AS RowNumber
FROM @YourTable
--WHERE
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
ORDER BY RowNumber
--------------------------------------------
--Method 2
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,ROW_NUMBER() OVER
(
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
) RowNumber
FROM @YourTable
--WHERE more conditions here
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE
RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
--AND more conditions here
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
OUTPUT:
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected)
If you don't want to include the full path, you can do
add_executable(main main.cpp)
target_link_libraries(main bingitup)
bingitup
is the same name you'd give a target if you create the static library in a CMake project:
add_library(bingitup STATIC bingitup.cpp)
CMake automatically adds the lib
to the front and the .a
at the end on Linux, and .lib
at the end on Windows.
If the library is external, you might want to add the path to the library using
link_directories(/path/to/libraries/)
Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:
float distance = (float) loc.distanceTo(loc2);
Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?
This is because of using integer indices (ix
selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).
*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:
df.iloc[-3:]
see the docs.
As Wes points out, in this specific case you should just use tail!
This is how i solve it.:
items: [
{ title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
{ title: 'Projects', icon: require('@/assets/icons/sidebar/projects.svg') },
{ title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
],
And on the template part:
<img :src="item.icon" />
My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)
# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)
# tails of the arrows
tails= np.zeros(len(bvecs))
# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('b-vectors on unit sphere')
plt.show()
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
One solution is to style the left border like so:
li { display: inline; }
li + li {
border-left: 1px solid;
margin-left:.5em;
padding-left:.5em;
}
However, this may not give you desirable results if the entire lists wraps, like it does in your example. I.e. it would give something like:
foo | bar | baz
| bob | bill
| judy
Based on the source you can use the 'dataurlnewwindow' parameter for output():
doc.output('dataurlnewwindow');
Source in github: https://github.com/MrRio/jsPDF/blob/master/jspdf.js#L914
All possible cases:
doc.output('save', 'filename.pdf'); //Try to save PDF as a file (not works on ie before 10, and some mobile devices)
doc.output('datauristring'); //returns the data uri string
doc.output('datauri'); //opens the data uri in current window
doc.output('dataurlnewwindow'); //opens the data uri in new window
You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:
$ ls | egrep '.+\..+'
Pass param rot=0
to rotate the xticks:
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()
yields plot:
You could try this if you want to insert all column using SELECT * INTO
table.
SELECT *
INTO Table2
FROM Table1;
commands
also works.
import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result
It works on linux, python 2.7.
If your server is still listening on port 80, check the permission on the DocumentRoot folder and if DirectoryIndex file existed.
One example more :)
double a = 1.00
if(floor(a) == a) {
// a is an integer
} else {
//a is not an integer.
}
In this example, ceil can be used and have the exact same effect.
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep()
, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:
# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php
On my system, I don't even have to put the path to the php installation:
00 * * * * php /home/path/script.php
On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.
With AutoEventWireup
which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
For details see the MSDN article.
You can use this:
<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">
Here, record is the model for current row and status is boolean value.
It's usually the metacharacter .
when not inside a character class.
So use ^.{1,35}$
. However, dot does not include newlines unless the dot-all modifier is applied against it.
You can use ^[\S\s]{1,35}$
without any modifiers, and this includes newlines as well.
@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
@RequestParam(required = false) String parameter1,
@RequestParam(required = false) String parameter2,
BindingResult result, HttpServletRequest request)
throws ParseException {
LONG CODE and SAME LONG CODE with a minor difference
}
if @RequestParam(required = true)
then you must pass parameter1,parameter2
Use BindingResult and request them based on your conditions.
The Other way
@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
two @RequestParam parameters, HttpServletRequest request) throws ParseException {
myMethod();
}
@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
BindingResult result) throws ParseException {
myMethod();
do here your minor difference
}
private returntype myMethod(){
LONG CODE
}
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
You'll have to configure the server to interpret .html
files as .php
files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.
<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
<option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>
In ts
mostrardatos(){
}
Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
I'm re-acquainting myself with Python and needed the same thing. The findall solution may be better, but I came up with this:
tokens = [x.strip() for x in data.split(',')]
This is the simple way:
text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:
Thin 100
Extra Light 200
Light 300
Regular 400
Medium 500
Semi-Bold 600
Bold 700
Extra-Bold 800
Black 900
Note that very few fonts come in all 9 weights.
If you are running the
mvn spring-boot:run
from the command line, make sure you are in the directory that contains the pom.xml file. Otherwise, you will run into the No plugin found for prefix 'spring-boot' in the current project and in the plugin groups error.
You can use the memcpy()
,
void * memcpy ( void * destination, const void * source, size_t num );
memcpy()
copies the values of num
bytes from the location pointed by source
directly to the memory block pointed by destination
.
If the destination
and source
overlap, then you can use memmove()
.
void * memmove ( void * destination, const void * source, size_t num );
memmove()
copies the values of num
bytes from the location pointed by source
to the memory block pointed by destination
. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
Works for every binary, not only java:
file - < $(which java) # heavyly bashic
cat `which java` | file - # universal
Heres a shorter version of Simons answer for Swift 3. Also allows for toggling of the cell's selection
var cellIsSelected: IndexPath?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
cellIsSelected = cellIsSelected == indexPath ? nil : indexPath
tableView.beginUpdates()
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if cellIsSelected == indexPath {
return 250
}
return 65
}
As additional information, to accomplish same thing in SQL Server, you just need to remove the "FROM dual" part of the query.
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
Unfortunately, many of the answers simply indicate how to access the Response’s body as text. By default, the body of the response object is text, not an object as it is passed through a stream.
What you are looking for is the json() function of the Body object property on the Response object. MDN explains it much better than I:
The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
response.json().then(function(data) { console.log(data);});
or using ES6:
response.json().then((data) => { console.log(data) });
Source: https://developer.mozilla.org/en-US/docs/Web/API/Body/json
This function returns a Promise by default, but note that this can be easily converted to an Observable for downstream consumption (stream pun not intended but works great).
Without invoking the json() function, the data, especially when attempting to access the _body property of the Response object, will be returned as text, which is obviously not what you want if you are looking for a deep object (as in an object with properties, or than can’t be simply converted into another objected).
I changed the following dependencies in my project to make it work .
build.gradle (app):
implementation 'com.google.firebase:firebase-core:16.0.1'
to
implementation 'com.google.firebase:firebase-core:16.0.8'
build.gradle (app) :
classpath 'com.google.gms:google-services:4.0.1'
to
classpath 'com.google.gms:google-services:4.2.0'
****Note :
Use the following link for updated use of libraries that have dependencies https://firebase.google.com/docs/android/setup
@@
denotes a class variable, i.e. it can be inherited.
This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle
with the class variable @@number_of_wheels
then if you create a class Car < Vehicle
then it too will have the class variable @@number_of_wheels
While pd.set_option('display.max_columns', None)
sets the number of the maximum columns shown, the option pd.set_option('display.max_colwidth', -1)
sets the maximum width of each single field.
For my purposes I wrote a small helper function to fully print huge data frames without affecting the rest of the code, it also reformats float numbers and sets the virtual display width. You may adopt it for your use cases.
def print_full(x):
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 2000)
pd.set_option('display.float_format', '{:20,.2f}'.format)
pd.set_option('display.max_colwidth', None)
print(x)
pd.reset_option('display.max_rows')
pd.reset_option('display.max_columns')
pd.reset_option('display.width')
pd.reset_option('display.float_format')
pd.reset_option('display.max_colwidth')
It is explained pretty well here: Display a view from another controller in ASP.NET MVC
To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\
,
but after that, if it doesn't find the view, it checks in \Views\Shared
.
ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
To check if a folder exists or not, you can simply use the exists()
method:
// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
w << "Some text\n"
}
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
If you are using the static serve view in development, you have to have DEBUG = True :
Warning
This will only work if DEBUG is True.
That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.
Docs: serving static files in developent
EDIT: You could add some urls just to test your 404 and 500 templates, just use the generic view direct_to_template in your urls.
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
('^404testing/$', direct_to_template, {'template': '404.html'})
)
$('#attached_docs [value="123"]').find ... .remove();
it should do your need however, you cannot duplicate id! remember it
I've found that this works best for me. It overrides as expected.
return <View style={{...styles.local, ...styles.fromProps}} />
C doesn't have a foreach, but macros are frequently used to emulate that:
#define for_each_item(item, list) \
for(T * item = list->head; item != NULL; item = item->next)
And can be used like
for_each_item(i, processes) {
i->wakeup();
}
Iteration over an array is also possible:
#define foreach(item, array) \
for(int keep = 1, \
count = 0,\
size = sizeof (array) / sizeof *(array); \
keep && count != size; \
keep = !keep, count++) \
for(item = (array) + count; keep; keep = !keep)
And can be used like
int values[] = { 1, 2, 3 };
foreach(int *v, values) {
printf("value: %d\n", *v);
}
Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"
Using list comprehensions is a pretty obvious one for me. Not sure about performance, but at least things stay lists.
[x for x in a if x in b]
Or "all the x values that are in A, if the X value is in B".
What worked best for me is
scroll_view.post(new Runnable() {
@Override
public void run() {
// This method works but animates the scrolling
// which looks weird on first load
// scroll_view.fullScroll(View.FOCUS_DOWN);
// This method works even better because there are no animations.
scroll_view.scrollTo(0, scroll_view.getBottom());
}
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
You should try this way. It will definitely work.
(function() {
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function($scope) {
$scope.myText = "Object Push inside ";
$scope.arrayText = [
];
$scope.addText = function() {
$scope.arrayText.push(this.myText);
}
}]);
})();
In your case $scope.arrayText
is an object. You should initialize as a array.
Install GCC in Ubuntu Debian Base
sudo apt-get install build-essential
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
Use win APIs in your main function:
Then write another function which handles win's messages (mentioned in #1). When you receive the message WM_CREATE you have to call CreateWindow(). The class is what control is that window, for example "edit" is a text box and "button" is a.. button :). You have to specify an ID for each control (of your choice but unique among all). CreateWindow() returns a handle to that control, which needs to be memorized. When the user clicks on a control you receive the WM_COMMAND message with the ID of that control. Here you can handle that event. You might find useful SetWindowText() and GetWindowText() which allows you to set/get the text of any control.
You will need only the win32 SDK. You can get it here.
Here is simple steps add this gradle:
dependencies {
compile "com.google.firebase:firebase-messaging:9.0.0"
}
No extra permission are needed in manifest like GCM.
No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver
is added automatically.
Migrate your listener service
A service extending InstanceIDListenerService
is now required only if you want to access the FCM token.
This is needed if you want to
Add Service in manifest
<service
android:name=".MyInstanceIDListenerService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Change MyInstanceIDListenerService
to extend FirebaseInstanceIdService
, and update code to listen for token updates and get the token whenever a new token is generated.
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
...
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is also called
* when the InstanceID token is initially generated, so this is where
* you retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
}
For more information visit
i forgot to add below line to my HTML code after i add problem has resolved.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}
I know this is an old thread but I ended up here with the same issue.
I solved it by comparing the dependencies classpath in the build.gradle script(Project) to the installed version.
The error message was pointing to the following folder
C:\Program Files\Android\android-studio3 preview\gradle\m2repository\com\android\tools\build\gradle
It turned out that the alpha2 version was installed but the classpath was still pointing to alpaha1. A simple change to the classpath ('com.android.tools.build:gradle:3.0.0-alpha2') was all that was needed.
This may not help everyone, but I do hope it help most people out.
Here is an easy way.
Open the connection window, click on the Server name dropdown, and hover over the connection string you want to delete, then press delete.
You can use the include?
method:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.
The following will create an iterator that yields five, and then every item in some_list.
def __iter__(self):
yield 5
yield from some_list
Pre-3.3, yield from
didn't exist, so you would have to do:
def __iter__(self):
yield 5
for x in some_list:
yield x
It looks like you are interesting in performing an operation everything for a given year, if this is indeed the case, I would recommend to use the YEAR() function like this:
SELECT * FROM `table` WHERE YEAR(date_column) = '2012';
The same goes for DAY() and MONTH(). They are also available for MySQL/MariaDB variants and was introduced in SQL Server 2008 (so not for specific 2000).
We had this exact issue while testing our code (delete cached modules so they can be re-required in a fresh state) so we reviewed all the suggestions of people on the various StackOverflow Questions & Answers and put together a simple node.js module (with tests):
As you would expect, works for both published npm packages and locally defined modules. Windows, Mac, Linux, etc.
Usage is pretty simple:
Install the module from npm:
npm install decache --save-dev
// require the decache module:
const decache = require('decache');
// require a module that you wrote"
let mymod = require('./mymodule.js');
// use your module the way you need to:
console.log(mymod.count()); // 0 (the initial state for our counter is zero)
console.log(mymod.incrementRunCount()); // 1
// delete the cached module:
decache('./mymodule.js');
//
mymod = require('./mymodule.js'); // fresh start
console.log(mymod.count()); // 0 (back to initial state ... zero)
If you have any questions or need more examples, please create a GitHub issue: https://github.com/dwyl/decache/issues
In the terminal, I typed:
/usr/local/mysql/bin/mysql -u root -p
I was then prompted to enter the temporary password that was given to me upon completion of the installation.
You can also save as a file: rdd.saveAsTextFile("alicia.txt")
$('tableName').find('tr').length
If you set the date to
DateTime dNewDate = new DateTime();
The value is set to {1/1/0001 12:00:00 AM}
The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:
input -> [1,2,[3,4]]
output -> [1,2,3,4]
The code below gives me the result, but I would like to know if anyone can create a simpler answer:
def get_elements_from_nested_list(l, new_l):
if l is not None:
e = l[0]
if isinstance(e, list):
get_elements_from_nested_list(e, new_l)
else:
new_l.append(e)
if len(l) > 1:
return get_elements_from_nested_list(l[1:], new_l)
else:
return new_l
l = [1,2,[3,4]]
new_l = []
get_elements_from_nested_list(l, new_l)
It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.
For asp core 2.2:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
namespace Project
{
sealed class Program
{
#region Variables
/// <summary>
/// Last loaded configuration
/// </summary>
private static IConfiguration _Configuration;
#endregion
#region Properties
/// <summary>
/// Default application configuration
/// </summary>
internal static IConfiguration Configuration
{
get
{
// None configuration yet?
if (Program._Configuration == null)
{
// Create the builder using a callback class
IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();
// Build everything but do not initialize it
builder.Build();
}
// Current configuration
return Program._Configuration;
}
// Update configuration
set => Program._Configuration = value;
}
#endregion
#region Public
/// <summary>
/// Start the webapp
/// </summary>
public static void Main(string[] args)
{
// Create the builder using the default Startup class
IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
// Build everything and run it
using (IWebHost host = builder.Build())
host.Run();
}
#endregion
#region CallBackConfiguration
/// <summary>
/// Aux class to callback configuration
/// </summary>
private class CallBackConfiguration
{
/// <summary>
/// Callback with configuration
/// </summary>
public CallBackConfiguration(IConfiguration configuration)
{
// Update the last configuration
Program.Configuration = configuration;
}
/// <summary>
/// Do nothing, just for compatibility
/// </summary>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//
}
}
#endregion
}
}
So now on you just use the static Program.Configuration at any other class you need it.
create_function
did not work for me inside a class. I had to use call_user_func
.
<?php
class Dispatcher {
//Added explicit callback declaration.
var $callback;
public function Dispatcher( $callback ){
$this->callback = $callback;
}
public function asynchronous_method(){
//do asynch stuff, like fwrite...then, fire callback.
if ( isset( $this->callback ) ) {
if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
}
}
}
Then, to use:
<?php
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();
function do_callback( $data ){
print 'Data is: ' . $data . "\n";
}
?>
[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.
There are two options:
First
You can also use like is()
$('#dropDownId').is(':disabled');
Second
Using == true
by checking if the attributes value is disabled
. attr()
$('#dropDownId').attr('disabled');
whatever you feel fits better , you can use :)
Cheers!
Here is a simple "CSS only" trick I created and am using to dynamically add a red asterisk on the labels of required form elements without losing browsers' default form validation.
The following code works perfectly on all the browsers and for all the main form elements.
.form-group {
display: flex;
flex-direction: column;
}
label {
order: 1;
text-transform: capitalize;
margin-bottom: 0.3em;
}
input,
select,
textarea {
padding: 0.5em;
order: 2;
}
input:required+label::after,
select:required+label::after,
textarea:required+label::after {
content: " *";
color: #e32;
}
_x000D_
<div class="form-group">
<input class="form-control" name="first_name" id="first_name" type="text" placeholder="First Name" required>
<label class="small mb-1" for="first_name">First Name</label>
</div>
<br>
<div class="form-group">
<input class="form-control" name="last_name" id="last_name" type="text" placeholder="Last Name">
<label class="small mb-1" for="last_name">Last Name</label>
</div>
_x000D_
Important: You must preserve the order of elements that is the input element first and label element second. CSS is gonna handle it and transform it in the traditional way, that is the label first and input second.
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Use like this:
when(
fooDao.getBar(
Matchers.<Bazoo>any()
)
).thenReturn(myFoo);
Before you need to import Mockito.Matchers
Let me add my vote for boost::lexical_cast
#include <boost/lexical_cast.hpp>
int val = boost::lexical_cast<int>(strval) ;
It throws bad_lexical_cast
on error.
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a zipped data and it has to upzip it,this is a example where Type really matters at Bowser.
The error says it all, change:
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
to
final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
Array's include?
method accepts any object, not just a string. This should work:
@suggested_horses = []
@suggested_horses << Horse.first(:offset => rand(Horse.count))
while @suggested_horses.length < 8
horse = Horse.first(:offset => rand(Horse.count))
@suggested_horses << horse unless @suggested_horses.include?(horse)
end
It doesn't matter at all, but class makes it look like T can only be a class, while it can of course be any type. So typename is more accurate. On the other hand, most people use class, so that is probably easier to read generally.
Very simple was to renew your certificate. Go to your developer member centre and go to your Provisioning profile and see what are the certificate Active and InActive and select Inactive certificate and hit Edit button then hit generate button. Now your certificate successful renewal for another 1 year. Thanks
I would do it using a for loop as shown below :
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
Set a property for the current lesson: currentLesson
. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson
value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on.
Each button now can be disabled with [disabled] attribute, if it the currentLesson
is not the same as it's order.
HTML
<button (click)="currentLesson = '1'"
[disabled]="currentLesson !== '1'" class="primair">
Start lesson</button>
<button (click)="currentLesson = '2'"
[disabled]="currentLesson !== '2'" class="primair">
Start lesson</button>
.....//so on
Typescript
currentLesson:string;
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
constructor(){
this.currentLesson=this.classes[0].currentLesson
}
Putting everything in a loop:
HTML
<div *ngFor="let class of classes; let i = index">
<button [disabled]="currentLesson !== i + 1" class="primair">
Start lesson {{i + 1}}</button>
</div>
Typescript
currentLesson:string;
classes = [
{
name: 'Lesson1',
level: 1,
code: 1,
},{
name: 'Lesson2',
level: 1,
code: 2,
},
{
name: 'Lesson3',
level: 2,
code: 3,
}]
IN SQL Server ,
declare @ViewName nvarchar(20)='ViewNameExample'
if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
begin
-- Your SQL Code goes here ...
end
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
In HTML 5 you could also use:
onpageshow
: Script to be run when the window becomes visibleonpagehide
: Script to be run when the window is hiddenSee:
The variables my_list
and "-"
are both objects. Specifically, they're instances of the classes list
and str
, respectively. The join
function belongs to the class str
. Therefore, the syntax "-".join(my_list)
is used because the object "-"
is taking my_list
as an input.
The following code assumes no circular references, and assumes subs
is always an array (and not null in leaf nodes):
function find(haystack, needle) {
if (haystack.label === needle) return haystack;
for (var i = 0; i < haystack.subs.length; i ++) {
var result = find(haystack.subs[i], needle);
if (result) return result;
}
return null;
}
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:
git checkout yourbranch
git rebase -i origin/master
# Edit command names accordingly
pick 1fc6c95 My pull request
squash 6b2481b Hack hack - will be discarded
squash dd1475d Also discarded
git push -f origin yourbranch
...and now the pull request contains only one commit.
Related links about rebasing:
stack
is part of memory. it use for input
and output
of functions
. also it use for remembering function's return.
esp
register is remember the stack address.
stack
and esp
are implemented by hardware. also you can implement it yourself. it will make your program very slow.
example:
nop // esp
= 0012ffc4
push 0 //esp
= 0012ffc0 ,Dword[0012ffc0]=00000000
call proc01 // esp
= 0012ffbc ,Dword[0012ffbc] = eip
, eip
= adrr[proc01]
pop eax
// eax
= Dword[esp
], esp
= esp
+ 4
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");
Use aggregation on name
and get name
with count > 1
:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
To sort the results by most to least duplicates:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$sort": {"count" : -1} },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
To use with another column name than "name", change "$name" to "$column_name"
Java passes by value; there's no out
parameter like in C#.
You can either use return
, or mutate an object passed as a reference (by value).
public class FunctionSample {
static String fReturn() {
return "Hello!";
}
static void fArgNoWorkie(String s) {
s = "What am I doing???"; // Doesn't "work"! Java passes by value!
}
static void fMutate(StringBuilder sb) {
sb.append("Here you go!");
}
public static void main(String[] args) {
String s = null;
s = fReturn();
System.out.println(s); // prints "Hello!"
fArgNoWorkie(s);
System.out.println(s); // prints "Hello!"
StringBuilder sb = new StringBuilder();
fMutate(sb);
s = sb.toString();
System.out.println(s); // prints "Here you go!"
}
}
As for the code that OP needs help with, here's a typical solution of using a special value (usually null
for reference types) to indicate success/failure:
Instead of:
String oPerson= null;
if (CheckAddress("5556", oPerson)) {
print(oPerson); // DOESN'T "WORK"! Java passes by value; String is immutable!
}
private boolean CheckAddress(String iAddress, String oPerson) {
// on search succeeded:
oPerson = something; // DOESN'T "WORK"!
return true;
:
// on search failed:
return false;
}
Use a String
return type instead, with null
to indicate failure.
String person = checkAddress("5556");
if (person != null) {
print(person);
}
private String checkAddress(String address) {
// on search succeeded:
return something;
:
// on search failed:
return null;
}
This is how java.io.BufferedReader.readLine()
works, for example: it returns instanceof String
(perhaps an empty string!), until it returns null
to indicate end of "search".
This is not limited to a reference type return value, of course. The key is that there has to be some special value(s) that is never a valid value, and you use that value for special purposes.
Another classic example is String.indexOf
: it returns -1
to indicate search failure.
Note: because Java doesn't have a concept of "input" and "output" parameters, using the
i-
ando-
prefix (e.g.iAddress
,oPerson
) is unnecessary and unidiomatic.
If you need to return several values, usually they're related in some way (e.g. x
and y
coordinates of a single Point
). The best solution would be to encapsulate these values together. People have used an Object[]
or a List<Object>
, or a generic Pair<T1,T2>
, but really, your own type would be best.
For this problem, I recommend an immutable SearchResult
type like this to encapsulate the boolean
and String
search results:
public class SearchResult {
public final String name;
public final boolean isFound;
public SearchResult(String name, boolean isFound) {
this.name = name;
this.isFound = isFound;
}
}
Then in your search function, you do the following:
private SearchResult checkAddress(String address) {
// on address search succeed
return new SearchResult(foundName, true);
:
// on address search failed
return new SearchResult(null, false);
}
And then you use it like this:
SearchResult sr = checkAddress("5556");
if (sr.isFound) {
String name = sr.name;
//...
}
If you want, you can (and probably should) make the final
immutable fields non-public
, and use public
getters instead.
Technically, you can use StackTrace, but this is very slow and will not give you the answers you expect a lot of the time. This is because during release builds optimizations can occur that will remove certain method calls. Hence you can't be sure in release whether stacktrace is "correct" or not.
Really, there isn't any foolproof or fast way of doing this in C#. You should really be asking yourself why you need this and how you can architect your application, so you can do what you want without knowing which method called it.
Change your crontab command to
* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)
The (...)
starts a sub-shell that your crond executes as a single command. The || exit 1
causes your cronjob to fail in case that the directory is unavailable.
Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.
I had this problems when I was running my application using docker containers.
The solution was put the name of the MySQL service container I was using in docker_compose.yml
on DB_HOST. In my case, it was db
:
DB_HOST=db
Hope it helps.
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
I just changed @Jotne's answer for "for loop".
for i in `seq 11 20`; do host myserver-$i | awk -v i="$i" '{print "myserver-"i" " $4}'; done
Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified his example to do this here: http://jsfiddle.net/QLfMU/116/
I think I wrote an elegant solution to this problem by using namespaces. In my case, the inner class does not need to know his parent class (like the static inner class in Java). As an example I made a class called 'User' and a subclass called 'Type', used as a reference for the user types (ADMIN, OTHERS) in my example. Regards.
User.php (User class file)
<?php
namespace
{
class User
{
private $type;
public function getType(){ return $this->type;}
public function setType($type){ $this->type = $type;}
}
}
namespace User
{
class Type
{
const ADMIN = 0;
const OTHERS = 1;
}
}
?>
Using.php (An example of how to call the 'subclass')
<?php
require_once("User.php");
//calling a subclass reference:
echo "Value of user type Admin: ".User\Type::ADMIN;
?>
Use a ByteArrayOutputStream
. Here is the process:
InputStream
to read dataByteArrayOutputStream
.InputStream
into the OutputStream
byte[]
from the ByteArrayOutputStream
using the toByteArray()
methodIn theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
Usually, best is to see a character in his context.
Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others.
This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases.
By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard.
var i = 0
do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++
while (i<136690)
window.stop()
// From https://codepen.io/Nico_KraZhtest/pen/mWzXqy
_x000D_
The same snippet as a bookmarklet:
javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}();
To generate that list from php:
for ($x = 0; $x < 136690; $x++) {
echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8');
}
To generate that list into the console, using php:
php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}'
Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/
Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters.
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Hey, did you notice the plain html <details>
element has a drop down arrow? This is sometimes all what we need.
<details>
<summary>Morning</summary>
<p>Hello world!</p>
</details>
<details>
<summary>Evening</summary>
<p>How sweat?</p>
</details>
_x000D_
Shift+F5 quickly clears the cache.
Use the method Int.Parse()
instead. It will work.
If you are using Visual Studio Community 2015 and trying to Install GLUT you should place the header file glut.h
in
C:\Program Files (x86)\Windows Kits\8.1\Include\um\gl
Simple Steps:
-Open Eclipse.
You can use site https://regex101.com/ for building your own specific pattern for some country:
For example, Poland:
-pattern = xxxxxxxxx OR xxx-xxx-xxx OR xxx xxx xxx
-regexp ="^\d{9}|^\d{3}-\d{3}-\d{3}|^\d{3}\s\d{3}\s\d{3}"
The problem is not that Bar and Bah have to copy 387 constructors, the problem is that Foo has 387 constructors. Foo clearly does too many things - refactor quick! Also, unless you have a really good reason to have values set in the constructor (which, if you provide a parameterless constructor, you probably don't), I'd recommend using property getting/setting.
Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/
If you want set custom exception handling behavior for a specific controller, you can do so by overriding the controllers OnActionExecuted
method.
Remember to set the ExceptionHandled
property to true to disable default exception handling behavior.
Here is a sample from an api I'm writing, where I want to catch specific types of exceptions and return a json formatted result:
private static readonly Type[] API_CATCH_EXCEPTIONS = new Type[]
{
typeof(InvalidOperationException),
typeof(ValidationException)
};
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
if (context.Exception != null)
{
var exType = context.Exception.GetType();
if (API_CATCH_EXCEPTIONS.Any(type => exType == type || exType.IsSubclassOf(type)))
{
context.Result = Problem(detail: context.Exception.Message);
context.ExceptionHandled = true;
}
}
}
/* The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it. */
var jq = $.noConflict();
(function($){
$('document').ready(function(){
$('button').click(function(){
alert($('.para').text());
})
})
})(jq);
Live view example on codepen that is easy to understand: http://codepen.io/kaushik/pen/QGjeJQ
hosts
file you wish to add to docker container;1.2.3.4 abc.tv
5.6.7.8 domain.xyz
1.3.5.7 odd.org
2.4.6.8 even.net
hosts
file into the container by adding the following line in the Dockerfile
COPY hosts /etc/hosts_extra
ENTRYPOINT
or CMD
or CRON
job then incorporate the following command line into it or at least run this inside the running container: cat /etc/hosts_extra >> etc/hosts;
Dockerfile
because the modification will be lost:RUN cat /etc/hosts_extra >> etc/hosts;
In Oracle we can use below.
SELECT * FROM TABLE_A WHERE ASCIISTR(COLUMN_A) <> COLUMN_A;
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
As stated in this answer not all browsers support the standard way. It is not a good idea to use for robust user experience. And if you use it, you cannot ask too much.
Instead use time-picker libraries. For example: TimePicker.js is a zero dependency and lightweight library. Use it like:
var timepicker = new TimePicker('time', {_x000D_
lang: 'en',_x000D_
theme: 'dark'_x000D_
});_x000D_
timepicker.on('change', function(evt) {_x000D_
_x000D_
var value = (evt.hour || '00') + ':' + (evt.minute || '00');_x000D_
evt.element.value = value;_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div>_x000D_
<input type="text" id="time" placeholder="Time">_x000D_
</div>
_x000D_
This post will explore various approaches of fetching MIME Type across various programming languages with their CONS in one-line description as header. So, use them accordingly and the one which works for you.
For eg. the code below is especially helpful when user may supply either of .xls, .xlsx or .xlsm and you don't want to write code testing extension and supplying MIME-type for each of them. Let the system do this job.
>>> pip install python-magic
>>> import magic
>>> magic.from_file("Employee.pdf", mime=True)
'application/pdf'
>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'
Source: Baeldung's blog on File MIME Types in Java
@Test
public void get_JAVA7_mimetype() {
Path path = new File("Employee.xlsx").toPath();
String mimeType = Files.probeContentType(path);
assertEquals(mimeType, "application/vnd.ms-excel");
}
It will use FileTypeDetector implementations to probe the MIME type and invokes the probeContentType of each implementation to resolve the type. Hence, if the file is known to the implementations then the content type is returned. However, if that doesn’t happen, a system-default file type detector is invoked.
@Test
public void getMIMEType_from_Extension(){
File file = new File("Employee.xlsx");
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
assertEquals(mimeType, "application/vnd.ms-excel");
}
@Test
public void getMIMEType_UsingGetFileNameMap(){
File file = new File("Employee.xlsx");
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(file.getName());
assertEquals(mimeType, "image/png");
}
It returns the matrix of MIME types used by all instances of URLConnection which then is used to resolve the input file type. However, this matrix of MIME types is very limited when it comes to URLConnection.
By default, the class uses content-types.properties file in JRE_HOME/lib. We can, however, extend it, by specifying a user-specific table using the content.types.user.table property:
System.setProperty("content.types.user.table","<path-to-file>");
Source: FileReader API & Medium's article on using Magic Numbers in JavaScript to get Mime Types
Final result looks something like this when one use javaScript to fetch the MimeType based on filestream. Open the embedded jsFiddle to see and understand this approach.
Bonus: It's accessible for most of the MIME Types and also you can add custom Mime Types in the getMimetype function. Also, it has FULL SUPPORT for MS Office Files Mime Types.
The steps to calculate mime type for a file in this example would be:
Browser Support (Above 95% overall and Close to 100% in all modern browsers):
const uploads = []_x000D_
_x000D_
const fileSelector = document.getElementById('file-selector')_x000D_
fileSelector.addEventListener('change', (event) => {_x000D_
console.time('FileOpen')_x000D_
const file = event.target.files[0]_x000D_
_x000D_
const filereader = new FileReader()_x000D_
_x000D_
filereader.onloadend = function(evt) {_x000D_
if (evt.target.readyState === FileReader.DONE) {_x000D_
const uint = new Uint8Array(evt.target.result)_x000D_
let bytes = []_x000D_
uint.forEach((byte) => {_x000D_
bytes.push(byte.toString(16))_x000D_
})_x000D_
const hex = bytes.join('').toUpperCase()_x000D_
_x000D_
uploads.push({_x000D_
filename: file.name,_x000D_
filetype: file.type ? file.type : 'Unknown/Extension missing',_x000D_
binaryFileType: getMimetype(hex),_x000D_
hex: hex_x000D_
})_x000D_
render()_x000D_
}_x000D_
_x000D_
console.timeEnd('FileOpen')_x000D_
}_x000D_
_x000D_
_x000D_
const blob = file.slice(0, 4);_x000D_
filereader.readAsArrayBuffer(blob);_x000D_
})_x000D_
_x000D_
const render = () => {_x000D_
const container = document.getElementById('files')_x000D_
_x000D_
const uploadedFiles = uploads.map((file) => {_x000D_
return `<div class=result><hr />_x000D_
<span class=filename>Filename: <strong>${file.filename}</strong></span><br>_x000D_
<span class=fileObject>File Object (Mime Type):<strong> ${file.filetype}</strong></span><br>_x000D_
<span class=binaryObject>Binary (Mime Type):<strong> ${file.binaryFileType}</strong></span><br>_x000D_
<span class=HexCode>Hex Code (Magic Number):<strong> <em>${file.hex}</strong></span></em>_x000D_
</div>`_x000D_
})_x000D_
_x000D_
container.innerHTML = uploadedFiles.join('')_x000D_
}_x000D_
_x000D_
const getMimetype = (signature) => {_x000D_
switch (signature) {_x000D_
case '89504E47':_x000D_
return 'image/png'_x000D_
case '47494638':_x000D_
return 'image/gif'_x000D_
case '25504446':_x000D_
return 'application/pdf'_x000D_
case 'FFD8FFDB':_x000D_
case 'FFD8FFE0':_x000D_
case 'FFD8FFE1':_x000D_
return 'image/jpeg'_x000D_
case '504B0304':_x000D_
return 'application/zip'_x000D_
case '504B34':_x000D_
return 'application/vnd.ms-excel.sheet.macroEnabled.12'_x000D_
default:_x000D_
return 'Unknown filetype'_x000D_
}_x000D_
}
_x000D_
.result {_x000D_
font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;_x000D_
line-height: 20px;_x000D_
font-size: 14px;_x000D_
margin: 10px 0;_x000D_
}_x000D_
_x000D_
.filename {_x000D_
color: #333;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
.fileObject {_x000D_
color: #a53;_x000D_
}_x000D_
_x000D_
.binaryObject {_x000D_
color: #63f;_x000D_
}_x000D_
_x000D_
.HexCode {_x000D_
color: #262;_x000D_
}_x000D_
_x000D_
em {_x000D_
padding: 2px 4px;_x000D_
background-color: #efefef;_x000D_
font-style: normal;_x000D_
}_x000D_
_x000D_
input[type=file] {_x000D_
background-color: #4CAF50;_x000D_
border: none;_x000D_
color: white;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
margin: 4px 2px;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<body>_x000D_
_x000D_
<input type="file" id="file-selector">_x000D_
_x000D_
<div id="files"></div>
_x000D_
Set the parent div to position: relative
, then the inner div to...
position: absolute;
bottom: 0;
...and there you go :)
You can set ref for child components then in parent can call via $refs:
Add ref to child component:
<my-component ref="childref"></my-component>
Add click event to parent:
<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
var vm = new Vue({_x000D_
el: '#app',_x000D_
components: {_x000D_
'my-component': { _x000D_
template: '#my-template',_x000D_
data: function() {_x000D_
return {_x000D_
count: 1,_x000D_
};_x000D_
},_x000D_
methods: {_x000D_
increaseCount: function() {_x000D_
this.count++;_x000D_
}_x000D_
}_x000D_
},_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="app">_x000D_
_x000D_
<my-component ref="childref"></my-component>_x000D_
<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>_x000D_
</div>_x000D_
_x000D_
<template id="my-template">_x000D_
<div style="border: 1px solid; padding: 2px;" ref="childref">_x000D_
<p>A counter: {{ count }}</p>_x000D_
<button @click="increaseCount">Internal Button</button>_x000D_
</div>_x000D_
</template>
_x000D_
To initialize your shell run the below code
source ~/anaconda3/etc/profile.d/conda.sh
conda activate Your_env
It's Worked for me, I got the solution from the below link
https://www.codegrepper.com/code-[“CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.][1]examples/shell/CommandNotFoundError%3A+Your+shell+has+not+been+properly+configured+to+use+%27conda+activate%27.+To+initialize+your+shell%2C+run
For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring
property is set to true, the sub-widget (actually, the entire subtree) is not clickable.
IgnorePointer(
ignoring: true, // or false
child: RaisedButton(
onPressed: _logInWithFacebook,
child: Text("Facebook sign-in"),
),
),
Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().
Thanks to cryo for improved version that I based my tested code below:
#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim()
#I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed.
from array import array
from struct import pack
from sys import byteorder
import copy
import pyaudio
import wave
THRESHOLD = 500 # audio levels not normalised.
CHUNK_SIZE = 1024
SILENT_CHUNKS = 3 * 44100 / 1024 # about 3sec
FORMAT = pyaudio.paInt16
FRAME_MAX_VALUE = 2 ** 15 - 1
NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20)
RATE = 44100
CHANNELS = 1
TRIM_APPEND = RATE / 4
def is_silent(data_chunk):
"""Returns 'True' if below the 'silent' threshold"""
return max(data_chunk) < THRESHOLD
def normalize(data_all):
"""Amplify the volume out to max -1dB"""
# MAXIMUM = 16384
normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE)
/ max(abs(i) for i in data_all))
r = array('h')
for i in data_all:
r.append(int(i * normalize_factor))
return r
def trim(data_all):
_from = 0
_to = len(data_all) - 1
for i, b in enumerate(data_all):
if abs(b) > THRESHOLD:
_from = max(0, i - TRIM_APPEND)
break
for i, b in enumerate(reversed(data_all)):
if abs(b) > THRESHOLD:
_to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND)
break
return copy.deepcopy(data_all[_from:(_to + 1)])
def record():
"""Record a word or words from the microphone and
return the data as an array of signed shorts."""
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE)
silent_chunks = 0
audio_started = False
data_all = array('h')
while True:
# little endian, signed short
data_chunk = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
data_chunk.byteswap()
data_all.extend(data_chunk)
silent = is_silent(data_chunk)
if audio_started:
if silent:
silent_chunks += 1
if silent_chunks > SILENT_CHUNKS:
break
else:
silent_chunks = 0
elif not silent:
audio_started = True
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
data_all = trim(data_all) # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function)
data_all = normalize(data_all)
return sample_width, data_all
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h' * len(data)), *data)
wave_file = wave.open(path, 'wb')
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(sample_width)
wave_file.setframerate(RATE)
wave_file.writeframes(data)
wave_file.close()
if __name__ == '__main__':
print("Wait in silence to begin recording; wait in silence to terminate")
record_to_file('demo.wav')
print("done - result written to demo.wav")
This is the correct way:
To execute code that will only be available to the index page, we could use this syntax:
$(document).on('pageinit', "#index", function() {
...
});
jQuery has an AjaxSetup()
function that allows you to register global ajax handlers such as beforeSend
and complete
for all ajax calls as well as allow you to access the xhr
object to do the progress that you are looking for
A good workaround in some cases may be to move the variables and code to another function:
def print_data(data):
print data
def main():
data = [4, 5, 6]
print_data(data)
main()
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
If you just want the bug fix to be integrated into the branch, git cherry-pick
the relevant commit(s).
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
This is the simplest way I found for doing this:
byte[] byteArray = ...
InputStream is = new BufferedInputStream(new ByteArrayInputStream(byteArray));
String mimeType = URLConnection.guessContentTypeFromStream(is);
If you want to pick value of first item then you should do like this-
var item0 = _config.GetSection("MyArray:0");
If you want to pick value of entire array then you should do like this-
IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();
Ideally, you should consider using options pattern suggested by official documentation. This will give you more benefits.
CSS to detect screen orientation:
@media screen and (orientation:portrait) { … }
@media screen and (orientation:landscape) { … }
The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation
Check Following Things
To get parameters from URL with ngRoute
. It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.
The solution for the question:
// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
// configure the routing rules here
$routeProvider.when('/backend/:type/:id', {
controller: 'PagesCtrl'
});
// enable HTML5mode to disable hashbang urls
$locationProvider.html5Mode(true);
})
.controller('PagesCtrl', function ($routeParams) {
console.log($routeParams.id, $routeParams.type);
});
If you don't enable the $locationProvider.html5Mode(true);
. Urls will use hashbang(/#/
).
More information about routing can be found on official angular $route API documentation.
Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.
NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.
Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.
final class MyClass {
public static function someMethod1() {
MyClass::init();
// whatever
}
public static function someMethod2() {
MyClass::init();
// whatever
}
private static $didInit = false;
private static function init() {
if (!self::$didInit) {
self::$didInit = true;
// one-time init code.
}
}
// private, so can't create an instance.
private function __construct() {
// Nothing to do - there are no instances.
}
}
The advantage of this approach, is that you get to call with the straightforward static function syntax:
MyClass::someMethod1();
Contrast it to the calls required by the accepted answer:
MyClass::getInstance->someMethod1();
As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.
If you are NOT using PHP 7.4's opcode.cache
, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache
.
If you ARE using opcode.cache
, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init();
at start of every public method. NOTE: If you want public properties, code them as a get
/ set
pair of methods, so that you have a place to add that init
call.
(Private members do NOT need that init
call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)
Here's a demo. Even works in IE7:
http://james.padolsey.com/demos/grayscale/
and
http://james.padolsey.com/javascript/grayscaling-in-non-ie-browsers/
The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.
In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and Object.Equals
and Object.ReferenceEquals
(or whatever it's called).
Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.
Haven't check in Excel, but this works in Libreoffice4:
The whole thing of address rewriting comes during consecutive
(a1) cut
(a2) paste
You need to interrupt the consecutiveness by putting something in-between:
(b1) cut
(b2) select some empty cells (more than 1) and drag(move) them
(b3) paste
Step (b2) is where the cell that is about to update itself stops the tracking. Quick and simple.
For a single result:
if (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
For multiple results:
while (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
Best option would be
Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:
<asp:CompareValidator
id="dateValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="txtDatecompleted"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
Not mentioned yet on this thread: since C++11, the member initializer list can use list-initialization (aka. "uniform initialization", "braced initialization"):
Foo(int num): bar{num} {}
which has the same semantics as list-initialization in other contexts.
What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
What worked for me in Android Studio (0.8.1):
These changes via the UI make the equivalent changes represented in other answers but is a better way to proceed because on close, all appropriate files (current and future) will be updated automatically (which is helpful when confronted by the many places where issues can occur).
NB: It is very important to review the Event Log and note that Android Studio provides helpful messages on alternative ways to resolve such issues.
Using REGEX you can remove the spaces in a string.
The following namespace is mandatory.
using System.Text.RegularExpressions;
Syntax:
Regex.Replace(text, @"\s", "")
public class TimeDelay{
public static void main(String args[]) {
try {
while (true) {
System.out.println(new String("Hello world"));
Thread.sleep(3 * 1000); // every 3 seconds
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I finally fixed this using the Google's camera app. It gets the phone's orientation by using a sensor and then sets the EXIF tag appropriately. The JPEG which comes out of the camera is not oriented automatically.
Also, the camera preview works properly only in the landscape mode. If you need your activity layout to be oriented in portrait, you will have to do it manually using the value from the orientation sensor.
You can use in this way using bootstrap css. Just remove the active class if already assinged to any row and reassign to the current row.
$(".table tr").each(function () {
$(this).attr("class", "");
});
$(this).attr("class", "active");
byte[] bytes = System.IO.File.ReadAllBytes(filename);
That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.
In script is usefull something like this:
if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi
it prevents before re-create "bad" looped symlink after re-run script
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
I had the same problem. Open the cmd and type:
python -m pip install pylint
I got a nice solution inspired by Apple's Table View Animations and Gestures. I deleted unnecessary parts from Apple's sample and translated it into swift.
I know the answer is quite long, but all the code is necessary. Fortunately, you can just copy and paste most of the code and just need to do a bit modification on step 1 and 3
1.create SectionHeaderView.swift
and SectionHeaderView.xib
import UIKit
protocol SectionHeaderViewDelegate {
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionOpened: Int)
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionClosed: Int)
}
class SectionHeaderView: UITableViewHeaderFooterView {
var section: Int?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var disclosureButton: UIButton!
@IBAction func toggleOpen() {
self.toggleOpenWithUserAction(true)
}
var delegate: SectionHeaderViewDelegate?
func toggleOpenWithUserAction(userAction: Bool) {
self.disclosureButton.selected = !self.disclosureButton.selected
if userAction {
if self.disclosureButton.selected {
self.delegate?.sectionHeaderView(self, sectionClosed: self.section!)
} else {
self.delegate?.sectionHeaderView(self, sectionOpened: self.section!)
}
}
}
override func awakeFromNib() {
var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "toggleOpen")
self.addGestureRecognizer(tapGesture)
// change the button image here, you can also set image via IB.
self.disclosureButton.setImage(UIImage(named: "arrow_up"), forState: UIControlState.Selected)
self.disclosureButton.setImage(UIImage(named: "arrow_down"), forState: UIControlState.Normal)
}
}
the SectionHeaderView.xib
(the view with gray background) should look something like this in a tableview(you can customize it according to your needs, of course):
note:
a) the toggleOpen
action should be linked to disclosureButton
b) the disclosureButton
and toggleOpen
action are not necessary. You can delete these 2 things if you don't need the button.
2.create SectionInfo.swift
import UIKit
class SectionInfo: NSObject {
var open: Bool = true
var itemsInSection: NSMutableArray = []
var sectionTitle: String?
init(itemsInSection: NSMutableArray, sectionTitle: String) {
self.itemsInSection = itemsInSection
self.sectionTitle = sectionTitle
}
}
3.in your tableview
import UIKit
class TableViewController: UITableViewController, SectionHeaderViewDelegate {
let SectionHeaderViewIdentifier = "SectionHeaderViewIdentifier"
var sectionInfoArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
let sectionHeaderNib: UINib = UINib(nibName: "SectionHeaderView", bundle: nil)
self.tableView.registerNib(sectionHeaderNib, forHeaderFooterViewReuseIdentifier: SectionHeaderViewIdentifier)
// you can change section height based on your needs
self.tableView.sectionHeaderHeight = 30
// You should set up your SectionInfo here
var firstSection: SectionInfo = SectionInfo(itemsInSection: ["1"], sectionTitle: "firstSection")
var secondSection: SectionInfo = SectionInfo(itemsInSection: ["2"], sectionTitle: "secondSection"))
sectionInfoArray.addObjectsFromArray([firstSection, secondSection])
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionInfoArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.sectionInfoArray.count > 0 {
var sectionInfo: SectionInfo = sectionInfoArray[section] as! SectionInfo
if sectionInfo.open {
return sectionInfo.open ? sectionInfo.itemsInSection.count : 0
}
}
return 0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionHeaderView: SectionHeaderView! = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderViewIdentifier) as! SectionHeaderView
var sectionInfo: SectionInfo = sectionInfoArray[section] as! SectionInfo
sectionHeaderView.titleLabel.text = sectionInfo.sectionTitle
sectionHeaderView.section = section
sectionHeaderView.delegate = self
let backGroundView = UIView()
// you can customize the background color of the header here
backGroundView.backgroundColor = UIColor(red:0.89, green:0.89, blue:0.89, alpha:1)
sectionHeaderView.backgroundView = backGroundView
return sectionHeaderView
}
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionOpened: Int) {
var sectionInfo: SectionInfo = sectionInfoArray[sectionOpened] as! SectionInfo
var countOfRowsToInsert = sectionInfo.itemsInSection.count
sectionInfo.open = true
var indexPathToInsert: NSMutableArray = NSMutableArray()
for i in 0..<countOfRowsToInsert {
indexPathToInsert.addObject(NSIndexPath(forRow: i, inSection: sectionOpened))
}
self.tableView.insertRowsAtIndexPaths(indexPathToInsert as [AnyObject], withRowAnimation: .Top)
}
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionClosed: Int) {
var sectionInfo: SectionInfo = sectionInfoArray[sectionClosed] as! SectionInfo
var countOfRowsToDelete = sectionInfo.itemsInSection.count
sectionInfo.open = false
if countOfRowsToDelete > 0 {
var indexPathToDelete: NSMutableArray = NSMutableArray()
for i in 0..<countOfRowsToDelete {
indexPathToDelete.addObject(NSIndexPath(forRow: i, inSection: sectionClosed))
}
self.tableView.deleteRowsAtIndexPaths(indexPathToDelete as [AnyObject], withRowAnimation: .Top)
}
}
}
This tutorial worked for me, resolving my issues with /usr/local/bin permission issues and php-cli (which composer requires, and may aliased differently on shared hosting).
First run these commands to download and install composer:
cd ~
mkdir bin
mkdir bin/composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar bin/composer
Determine the location of your php-cli (needed later on):
which php-cli
(If the above fails, use which php
)
It should return the path, such as /usr/bin/php-cli, /usr/php/54/usr/bin/php-cli, etc.
edit ~/.bashrc and make sure this line is at the top, adding it if it is not:
[ -z "$PS1" ] && return
and then add this alias to the bottom (using the php-cli path that you determined earlier):
alias composer="/usr/bin/php-cli ~/bin/composer/composer.phar"
Finish with these commands:
source ~/.bashrc
composer --version
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
The problem is where you are executing:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.
Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.
FormData method .entries
and the for of
expression is not supported in IE11 and Safari.
Here is a simplier version to support Safari, Chrome, Firefox and Edge
function formDataToJSON(formElement) {
var formData = new FormData(formElement),
convertedJSON = {};
formData.forEach(function(value, key) {
convertedJSON[key] = value;
});
return convertedJSON;
}
Warning: this answer doesn't work in IE11.
FormData doesn't have a forEach
method in IE11.
I'm still searching for a final solution to support all major browsers.
I have write down some code for other question which is similar to this one, but that question got duplicated so i can't answer there so i am just putting my code here if someone looking for same requirement.
It's not fully working code, you need to make some minor changes to get it worked.
Here is the code:
I've used @Graeme idea of using spannable text.
String colorfulText = "colorfulText";
Spannable span = new SpannableString(colorfulText);
for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);
Random Color Method:
private int getRandomColor(){
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
try to change this in your dispatcher-servlet.xml
<!-- Your View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views" />
<property name="order" value="1" />
</bean>
<!-- UrlBasedViewResolver to Handle Redirects & Forward -->
<bean id="urlViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order" value="2" />
</bean>
What happens is clearly explained here http://projects.nigelsim.org/wiki/RedirectWithSpringWebMvc
try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load
Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.
Also you can use some slaves as bridge to participate with more devices.
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
While your site is live, the php.ini
file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
Just change the port to 8081
and following virtual host will work:
<VirtualHost *:8081>
ServerName comm-app.local
DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
SetEnv APPLICATION_ENV "development"
<Directory "C:/xampp/htdocs/CommunicationApp/public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';' Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion: You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
In Management Studio, open the Object Explorer.
Views
Script view as > Create To > New query window
and you're done!
If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:
SELECT
m.definition
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'
I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji
That is the independent code from jQuery
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
else if (event.detail) delta = -(event.detail)/3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(sentido) {
var inicial = document.body.scrollTop;
var time = 1000;
var distance = 200;
animate({
delay: 0,
duration: time,
delta: function(p) {return p;},
step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
}});}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = (timePassed / opts.duration);
if (progress > 1) {progress = 1;}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
This might be more clear:
from datetime import date, timedelta
start_date = date(2019, 1, 1)
end_date = date(2020, 1, 1)
delta = timedelta(days=1)
while start_date <= end_date:
print (start_date.strftime("%Y-%m-%d"))
start_date += delta
I had exactly the same error. My network is an internal one of a company. I downloaded neon-eclipse for java developpers. These steps worked for me:
1- I downloaded a VPN client on my PC to be totally blinded from the network. Shellfire I used. Use free account and connect to Shellserver.
2- Inside the windows firewall, I added incoming rule for Eclipse. Navigate to where eclipse exe is found.
3- Perform Maven Update project.
Then the project was able to fetch from the maven repository.
hope it helps.
You could use Directory.GetCurrentDirectory
:
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");
Which will look for the file fileName.txt
in the current directory of the application.
Here's what I don't like about git:
First of all, I think the distributed idea flies in the face of reality. Everybody who's actually using git is doing so in a centralised way, even Linus Torvalds. If the kernel was managed in a distributed way, that would mean I couldn't actually download the "official" kernel sources - there wouldn't be one - I'd have to decide whether I want Linus' version, or Joe's version, or Bill's version. That would obviously be ridiculous, and that's why there is an official definition which Linus controls using a centralised workflow.
If you accept that you want a centralised definition of your stuff, then it becomes clear that the server and client roles are completely different, so the dogma that the client and server softwares should be the same becomes purely limiting. The dogma that the client and server data should be the same becomes patently ridiculous, especially in a codebase that's got fifteen years of history that nobody cares about but everybody would have to clone.
What we actually want to do with all that old stuff is bung it in a cupboard and forget that it's there, just like any normal VCS does. The fact that git hauls it all back and forth over the network every day is very dangerous, because it nags you to prune it. That pruning involves a lot of tedious decisions and it can go wrong. So people will probably keep a whole series of snapshot repos from various points in history, but wasn't that what source control was for in the first place? This problem didn't exist until somebody invented the distributed model.
Git actively encourages people to rewrite history, and the above is probably one reason for that. Every normal VCS makes rewriting history impossible for all but the admins, and makes sure the admins have no reason to consider it. Correct me if I'm wrong, but as far as I know, git provides no way to grant normal users write access but ban them from rewriting history. That means any developer with a grudge (or who was still struggling with the learning curve) could trash the whole codebase. How do we tighten that one? Well, either you make regular backups of the entire history, i.e. you keep history squared, or you ban write access to all except some poor sod who would receive all the diffs by email and merge them by hand.
Let's take an example of a well-funded, large project and see how git is working for them: Android. I once decided to have a play with the android system itself. I found out that I was supposed to use a bunch of scripts called repo to get at their git. Some of repo runs on the client and some on the server, but both, by their very existence, are illustrating the fact that git is incomplete in either capacity. What happened is that I was unable to pull the sources for about a week and then gave up altogether. I would have had to pull a truly vast amount of data from several different repositories, but the server was completely overloaded with people like me. Repo was timing out and was unable to resume from where it had timed out. If git is so distributable, you'd have thought that they'd have done some kind of peer-to-peer thing to relieve the load on that one server. Git is distributable, but it's not a server. Git+repo is a server, but repo is not distributable cos it's just an ad-hoc collection of hacks.
A similar illustration of git's inadequacy is gitolite (and its ancestor which apparently didn't work out so well.) Gitolite describes its job as easing the deployment of a git server. Again, the very existence of this thing proves that git is not a server, any more than it is a client. What's more, it never will be, because if it grew into either it would be betraying it's founding principles.
Even if you did believe in the distributed thing, git would still be a mess. What, for instance, is a branch? They say that you implicitly make a branch every time you clone a repository, but that can't be the same thing as a branch in a single repository. So that's at least two different things being referred to as branches. But then, you can also rewind in a repo and just start editing. Is that like the second type of branch, or something different again? Maybe it depends what type of repo you've got - oh yes - apparently the repo is not a very clear concept either. There are normal ones and bare ones. You can't push to a normal one because the bare part might get out of sync with its source tree. But you can't cvsimport to a bare one cos they didn't think of that. So you have to cvsimport to a normal one, clone that to a bare one which developers hit, and cvsexport that to a cvs working copy which still has to be checked into cvs. Who can be bothered? Where did all these complications come from? From the distributed idea itself. I ditched gitolite in the end because it was imposing even more of these restrictions on me.
Git says that branching should be light, but many companies already have a serious rogue branch problem so I'd have thought that branching should be a momentous decision with strict policing. This is where perforce really shines...
In perforce you rarely need branches because you can juggle changesets in a very agile way. For instance, the usual workflow is that you sync to the last known good version on mainline, then write your feature. Whenever you attempt to modify a file, the diff of that file gets added to your "default changeset". When you attempt to check in the changeset, it automatically tries to merge the news from mainline into your changeset (effectively rebasing it) and then commits. This workflow is enforced without you even needing to understand it. Mainline thus collects a history of changes which you can quite easily cherry pick your way through later. For instance, suppose you want to revert an old one, say, the one before the one before last. You sync to the moment before the offending change, mark the affected files as part of the changeset, sync to the moment after and merge with "always mine". (There was something very interesting there: syncing doesn't mean having the same thing - if a file is editable (i.e. in an active changeset) it won't be clobbered by the sync but marked as due for resolving.) Now you have a changelist that undoes the offending one. Merge in the subsequent news and you have a changelist that you can plop on top of mainline to have the desired effect. At no point did we rewrite any history.
Now, supposing half way through this process, somebody runs up to you and tells you to drop everything and fix some bug. You just give your default changelist a name (a number actually) then "suspend" it, fix the bug in the now empty default changelist, commit it, and resume the named changelist. It's typical to have several changelists suspended at a time where you try different things out. It's easy and private. You get what you really want from a branch regime without the temptation to procrastinate or chicken out of merging to mainline.
I suppose it would be theoretically possible to do something similar in git, but git makes practically anything possible rather than asserting a workflow we approve of. The centralised model is a bunch of valid simplifications relative to the distributed model which is an invalid generalisation. It's so overgeneralised that it basically expects you to implement source control on top of it, as repo does.
The other thing is replication. In git, anything is possible so you have to figure it out for yourself. In perforce, you get an effectively stateless cache. The only configuration it needs to know is where the master is, and the clients can point at either the master or the cache at their discretion. That's a five minute job and it can't go wrong.
You've also got triggers and customisable forms for asserting code reviews, bugzilla references etc, and of course, you have branches for when you actually need them. It's not clearcase, but it's close, and it's dead easy to set up and maintain.
All in all, I think that if you know you're going to work in a centralised way, which everybody does, you might as well use a tool that was designed with that in mind. Git is overrated because of Linus' fearsome wit together with peoples' tendency to follow each other around like sheep, but its main raison d'etre doesn't actually stand up to common sense, and by following it, git ties its own hands with the two huge dogmas that (a) the software and (b) the data have to be the same at both client and server, and that will always make it complicated and lame at the centralised job.
I often need to do this when upgrading machines, moving from box to box. In addition to moving /var/lib/mysql to a better location, I often need to restore old DB tables from an old MySQL installation. In order to do this...
I got this same error and managed to fix it by closing Skype and running XAMP as Administrator, works perfectly now. So right click THE XAMP icon and click run as admin.
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 NotReady 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Here is a NotReady on the node of 192.168.1.157
. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.
kubectl describe node 192.168.1.157
Partial Result:
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
OutOfDisk Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
Ready Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
There is a OutOfDisk on my node, then Kubelet stopped posting node status.
So, I must free some disk space, using the command of df
on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name
under the role of su
I can remove the useless images.
Login in 192.168.1.157
by using ssh, like ssh [email protected]
, and switch to the 'su' by sudo su
;
/etc/init.d/kubelet restart
Result:
stop: Unknown instance:
kubelet start/running, process 59261
On the master:
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 Ready 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Ok, that node works fine.
Here is a reference: Kubernetes
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader
for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable
as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;
By checking other answers, I used object-fit in CSS:
video {
object-fit: fill;
}
From MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit):
The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.
Value: fill
The replaced content is sized to fill the element’s content box: the object’s concrete object size is the element’s used width and height.
I will suppose your JPanel contains JTextField, for the sake of the demo.
Those components provides JTextComponent#setMargin()
method which seems to be what you're looking for.
If you're looking for an empty border of any size around your text, well, use EmptyBorder