div hover background color change
Try like this:
.class_name:hover{
background-color:#FF0000;
}
The various directive functions are executed from within two other angular functions called $compile
(where the directive's compile
is executed) and an internal function called nodeLinkFn
(where the directive's controller
, preLink
and postLink
are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:
To demonstrate the these steps, let's use the following HTML markup:
<div ng-repeat="i in [0,1,2]">
<my-element>
<div>Inner content</div>
</my-element>
</div>
With the following directive:
myApp.directive( 'myElement', function() {
return {
restrict: 'EA',
transclude: true,
template: '<div>{{label}}<div ng-transclude></div></div>'
}
});
The compile
API looks like so:
compile: function compile( tElement, tAttributes ) { ... }
Often the parameters are prefixed with t
to signify the elements and attributes provided are those of the source template, rather than that of the instance.
Prior to the call to compile
transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile
function will look like so:
<my-element>
<div>
"{{label}}"
<div ng-transclude></div>
</div>
</my-element>
Notice that the transcluded content is not re-inserted at this point.
Following the call to the directive's .compile
, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).
In our case, three instances of the source template above will be created (by ng-repeat
). Thus, the following sequence will execute three times, once per instance.
The controller
API involves:
controller: function( $scope, $element, $attrs, $transclude ) { ... }
Entering the link phase, the link function returned via $compile
is now provided with a scope.
First, the link function create a child scope (scope: true
) or an isolated scope (scope: {...}
) if requested.
The controller is then executed, provided with the scope of the instance element.
The pre-link
API looks like so:
function preLink( scope, element, attributes, controller ) { ... }
Virtually nothing happens between the call to the directive's .controller
and the .preLink
function. Angular still provide recommendation as to how each should be used.
Following the .preLink
call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).
The post-link
API is similar to that of the pre-link
function:
function postLink( scope, element, attributes, controller ) { ... }
Perhaps worth noticing that once a directive's .postLink
function is called, the link process of all its children elements has completed, including all the children's .postLink
functions.
This means that by the time .postLink
is called, the children are 'live' are ready. This includes:
The template at this stage will thus look like so:
<my-element>
<div class="ng-binding">
"{{label}}"
<div ng-transclude>
<div class="ng-scope">Inner content</div>
</div>
</div>
</my-element>
Use sorted function, like this:
map(lambda x: sorted(x)[1],lst)
You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.
e.g.
filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines
and
filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines
If you mean by newline the newline character it is \n and \r is the carrier return character, but if you mean by newline the line ending then it depends on the operating system: DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n")
Sync folder remove with the files or only a file.
I am not much of a giver nor a contributor but I couldn't find a good solution of this problem and I had to find my way... so I hope you'll like it :)
Works perfect for me with any number of nested directories and sub directories. Caution for the scope of 'this' when recursing the function, your implementation may be different. In my case this function stays into the return of another function that's why I am calling it with this.
const fs = require('fs');
deleteFileOrDir(path, pathTemp = false){
if (fs.existsSync(path)) {
if (fs.lstatSync(path).isDirectory()) {
var files = fs.readdirSync(path);
if (!files.length) return fs.rmdirSync(path);
for (var file in files) {
var currentPath = path + "/" + files[file];
if (!fs.existsSync(currentPath)) continue;
if (fs.lstatSync(currentPath).isFile()) {
fs.unlinkSync(currentPath);
continue;
}
if (fs.lstatSync(currentPath).isDirectory() && !fs.readdirSync(currentPath).length) {
fs.rmdirSync(currentPath);
} else {
this.deleteFileOrDir(currentPath, path);
}
}
this.deleteFileOrDir(path);
} else {
fs.unlinkSync(path);
}
}
if (pathTemp) this.deleteFileOrDir(pathTemp);
}
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
This is a very c# type of code:
var bks: Book[] = new Book[2];
In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:
var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
Now to explain what new Book[2];
would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:
Book[2] = function (){alert("hey");}
var foo = new Book[2]
and you should see hey. Try it
There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy
support. Usage: SUPER(<instance>).<method>(<args>)
, for example, assuming two classes A
and B extends A
with method m
: SUPER(new B).m()
.
function SUPER(instance) {
return new Proxy(instance, {
get(target, prop) {
return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
}
});
}
State resides within a component where as props are passed from parent to child. Props are generally immutable.
class Parent extends React.Component {
constructor() {
super();
this.state = {
name : "John",
}
}
render() {
return (
<Child name={this.state.name}>
)
}
}
class Child extends React.Component {
constructor() {
super();
}
render() {
return(
{this.props.name}
)
}
}
In the above code, we have a parent class(Parent) which has name as its state which is passed to the child component(Child class) as a prop and the child component renders it using {this.props.name}
Use %03d
in the format specifier for the integer. The 0
means that the number will be zero-filled if it is less than three (in this case) digits.
See the Formatter
docs for other modifiers.
There is a smart way to disable inspect element in your website. Just add the following snippet inside script tag :
$(document).bind("contextmenu",function(e) {
e.preventDefault();
});
Please check out this blog
The function key F12 which directly take inspect element from browser, we can also disable it, by using the following code:
$(document).keydown(function(e){
if(e.which === 123){
return false;
}
});
Look at the HttpServletResponse#sendRedirect(String location)
method.
Use it as:
response.sendRedirect(request.getContextPath() + "/welcome.jsp")
Alternatively, look at HttpServletResponse#setHeader(String name, String value)
method.
The redirection is set by adding the location header:
response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
json.dumps()
converts a dictionary to str
object, not a json(dict)
object! So you have to load your str
into a dict
to use it by using json.loads()
method
See json.dumps()
as a save method and json.loads()
as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#55000000"
android:paddingBottom="15dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:textColor="@android:color/white" />
</FrameLayout>
and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:
int width= context.getResources().getDisplayMetrics().widthPixels;
com.squareup.picasso.Picasso
.with(context)
.load("some url")
.centerCrop().resize(width/2,width/2)
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(item.drawableId);
now you dont need CustomImageView Class anymore.
P.S i recommend to use ImageView in place of Type Int in class Item.
hope this help..
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON)
there too.
Try adding a Reference to System.Configuration
, you get some of the configuration namespace by referencing the System namespace, adding the reference to System.Configuration should allow you to access ConfigurationManager
.
Check this solution which will able to find same character string too, let me know if something missing or not right.
function indexes(source, find) {_x000D_
if (!source) {_x000D_
return [];_x000D_
}_x000D_
if (!find) {_x000D_
return source.split('').map(function(_, i) { return i; });_x000D_
}_x000D_
source = source.toLowerCase();_x000D_
find = find.toLowerCase();_x000D_
var result = [];_x000D_
var i = 0;_x000D_
while(i < source.length) {_x000D_
if (source.substring(i, i + find.length) == find)_x000D_
result.push(i++);_x000D_
else_x000D_
i++_x000D_
}_x000D_
return result;_x000D_
}_x000D_
console.log(indexes('aaaaaaaa', 'aaaaaa'))_x000D_
console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))_x000D_
console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))_x000D_
console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
_x000D_
This isn't a direct answer to the question (loading images >2048), but a possible solution for anyone experiencing the error.
In my case, the image was smaller than 2048 in both dimensions (1280x727 to be exact) and the issue was specifically experienced on a Galaxy Nexus. The image was in the drawable
folder and none of the qualified folders. Android assumes drawables without a density qualifier are mdpi and scales them up or down for other densities, in this case scaled up 2x for xhdpi. Moving the culprit image to drawable-nodpi
to prevent scaling solved the problem.
Displaying an image from MySql Db.
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
I had the same problem - and I have read all these answers, but unfortunately none of them worked for me. Eventually I tried removing this line
%\usepackage[latin1]{inputenc}
and all errors disappeared.
.remove()
should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.
This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:
$("#myModal").on("hidden.bs.modal", function () {
// put your default event here
});
You can also use this script to figure out more info:
EXEC sp_server_info
The result will be something like that:
attribute_id | attribute_name | attribute_value
-------------|-----------------------|-----------------------------------
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 2012 - 11.0.6020.0
10 | OWNER_TERM | owner
11 | TABLE_TERM | table
12 | MAX_OWNER_NAME_LENGTH | 128
13 | TABLE_LENGTH | 128
14 | MAX_QUAL_LENGTH | 128
15 | COLUMN_LENGTH | 128
16 | IDENTIFIER_CASE | MIXED
? ? ?
? ? ?
? ? ?
You can loop over each row of the DataTable
and check the value.
I'm a big fan of using a foreach loop when using IEnumerable
s. Makes it very simple and clean to look at or process each row
DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
if (dr["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
}
Alternatively you can use a PrimaryKey
for your DataTable
. This helps in various ways, but you often need to define one before you can use it.
An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx
DataTable workTable = new DataTable("Customers");
// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.
Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx
DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
Finally, you can use the Select() method to find data within a DataTable
also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.
String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);
foreach (DataRow dr in drFound)
{
// do you deed. Each record here was already found to match your criteria
}
In my case this problem persisted when I created and saved the svg using Photoshop. What helped, was opening the file using Illustrator and exporting the svg afterwards.
On API >= 11, you can use:
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setDisplayZoomControls(false);
As per the SDK:
public void setDisplayZoomControls (boolean enabled)
Since: API Level 11
Sets whether the on screen zoom buttons are used. A combination of built in zoom controls enabled and on screen zoom controls disabled allows for pinch to zoom to work without the on screen controls
Mongo dump and restore with uri to local
mongodump --uri "mongodb://USERNAME:PASSWORD@IP_OR_URL:PORT/DB_NAME" --collection COLLECTION_NAME -o LOCAL_URL
Omitting --collection COLLECTION_NAME will dump entire DB.
There are several details you need to 'match up' with for a particular CRC implementation - even using the same polynomial there can be different results because of minor differences in how data bits are handled, using a particular initial value for the CRC (sometimes it's zero, sometimes 0xffff), and/or inverting the bits of the CRC. For example, sometimes one implementation will work from the low order bits of the data bytes up, while sometimes they'll work from the high order bits down (as yours currently does).
Also, you need to 'push out' the last bits of the CRC after you've run all the data bits through.
Keep in mind that CRC algorithms were designed to be implemented in hardware, so some of how bit ordering is handled may not make so much sense from a software point of view.
If you want to match the CRC16 with polynomial 0x8005 as shown on the lammertbies.nl CRC calculator page, you need to make the following changes to your CRC function:
So, your function might look like:
#define CRC16 0x8005
uint16_t gen_crc16(const uint8_t *data, uint16_t size)
{
uint16_t out = 0;
int bits_read = 0, bit_flag;
/* Sanity check: */
if(data == NULL)
return 0;
while(size > 0)
{
bit_flag = out >> 15;
/* Get next bit: */
out <<= 1;
out |= (*data >> bits_read) & 1; // item a) work from the least significant bits
/* Increment bit counter: */
bits_read++;
if(bits_read > 7)
{
bits_read = 0;
data++;
size--;
}
/* Cycle check: */
if(bit_flag)
out ^= CRC16;
}
// item b) "push out" the last 16 bits
int i;
for (i = 0; i < 16; ++i) {
bit_flag = out >> 15;
out <<= 1;
if(bit_flag)
out ^= CRC16;
}
// item c) reverse the bits
uint16_t crc = 0;
i = 0x8000;
int j = 0x0001;
for (; i != 0; i >>=1, j <<= 1) {
if (i & out) crc |= j;
}
return crc;
}
That function returns 0xbb3d
for me when I pass in "123456789"
.
>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))
SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
Unlike XML and XHTML, HTML has no knowledge of the self-closing syntax. Browsers that interpret XHTML as HTML don't know that the /
character indicates that the tag should be self-closing; instead they interpret it like an empty attribute and the parser still thinks the tag is 'open'.
Just as <script defer>
is treated as <script defer="defer">
, <script />
is treated as <script /="/">
.
fcntl
, select
, asyncproc
won't help in this case.
A reliable way to read a stream without blocking regardless of operating system is to use Queue.get_nowait()
:
import sys
from subprocess import PIPE, Popen
from threading import Thread
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty # python 2.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
# ... do other things here
# read line without blocking
try: line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
print('no output yet')
else: # got line
# ... do something with line
In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to
Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).
In other words: Whenever the interpreter encounters the sequence <space>
_
<line terminator>
, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.
To break the statement in your question into several lines you could do the following:
U_matrix(i, j, n + 1) = _
k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
(Leading whitespaces are ignored.)
Building off the accepted answer by @dennisg, I accomplished this successfully using jQuery.XDomainRequest.js by MoonScript.
The following code worked correctly in Chrome, Firefox and IE10, but failed in IE9. I simply included the script and it now automagically works in IE9. (And probably 8, but I haven't tested it.)
var displayTweets = function () {
$.ajax({
cache: false,
type: 'GET',
crossDomain: true,
url: Site.config().apiRoot + '/Api/GetTwitterFeed',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
for (var tweet in data) {
displayTweet(data[tweet]);
}
}
});
};
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
byte[] conv = new byte[4];
conv[3] = (byte) input & 0xff;
input >>= 8;
conv[2] = (byte) input & 0xff;
input >>= 8;
conv[1] = (byte) input & 0xff;
input >>= 8;
conv[0] = (byte) input;
If you want to do this only once, then do it because The framework will call initState()
method exactly once for each State object it creates.
@override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => executeAfterBuildComplete(context));
}
If you want to do this again and again like on back or navigate to a next screen and etc..., then do it because didChangeDependencies()
Called when a dependency of this State object changes.
For example, if the previous call to build
referenced an InheritedWidget
that later changed, the framework would call this method to notify this object about the change.
This method is also called immediately after initState
. It is safe to call BuildContext.dependOnInheritedWidgetOfExactType
from this method.
@override
void didChangeDependencies() {
super.didChangeDependencies();
WidgetsBinding.instance
.addPostFrameCallback((_) => executeAfterBuildComplete(context));
}
This is the your Callback function
executeAfterBuildComplete([BuildContext context]){
print("Build Process Complete");
}
Use this:
return this.RedirectToAction<AccountController>(m => m.LogIn());
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything.
You need to declare and initialize the x
and y
members.
Explicitly:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly:
export class Pixel {
constructor(public x: number, public y: number) {}
}
Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:
I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker
when you add your marker simply set the icon-property:
GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.
ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..
Debugging inside IPython
Cell Example:
%%debug
...: for n in range(4):
...: n>2
IPython inside debugging
pytest ... --pdbcls=IPython.terminal.debugger:TerminalPdb --pdb
breakpoint()
, python -m ipdb
, etc.I agree with the OP that many things MATLAB does nicely Python still does not have and really should since just about everything in the language favors development speed over production speed. Maybe someday I will contribute more than trivial bug fixes to CPython.
https://github.com/ipython/ipython/commit/f042f3fea7560afcb518a1940daa46a72fbcfa68
See also Is it possible to run commands in IPython with debugging?
Since PHP 5.5, you can use array_column
:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map
with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function
instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
Since this seems to be the number one google hit on base64 encoding and iphone, I felt like sharing my experience with the code snippet above.
It works, but it is extremely slow. A benchmark on a random image (0.4 mb) took 37 seconds on native iphone. The main reason is probably all the OOP magic - single char NSStrings etc, which are only autoreleased after the encoding is done.
Another suggestion posted here (ab)uses the openssl library, which feels like overkill as well.
The code below takes 70 ms - that's a 500 times speedup. This only does base64 encoding (decoding will follow as soon as I encounter it)
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length];
if (lentext < 1) return @"";
char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure
if ( !outbuf ) return nil;
const unsigned char *raw = [data bytes];
int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);
for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}
if ( do_now < lentext )
{
char tmpbuf[2] = {0,0};
int left = lentext%3;
for ( int i=0; i < left; i++ )
{
tmpbuf[i] = raw[do_now+i];
}
raw = tmpbuf;
outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}
NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);
return ret;
}
I left out the line-cutting since I didn't need it, but it's trivial to add.
For those who are interested in optimizing: the goal is to minimize what happens in the main loop. Therefore all logic to deal with the last 3 bytes is treated outside the loop.
Also, try to work on data in-place, without additional copying to/from buffers. And reduce any arithmetic to the bare minimum.
Observe that the bits that are put together to look up an entry in the table, would not overlap when they were to be orred together without shifting. A major improvement could therefore be to use 4 separate 256 byte lookup tables and eliminate the shifts, like this:
outbuf[outp++] = base64EncodingTable1[(raw[inp] & 0xFC)];
outbuf[outp++] = base64EncodingTable2[(raw[inp] & 0x03) | (raw[inp+1] & 0xF0)];
outbuf[outp++] = base64EncodingTable3[(raw[inp+1] & 0x0F) | (raw[inp+2] & 0xC0)];
outbuf[outp++] = base64EncodingTable4[raw[inp+2] & 0x3F];
Of course you could take it a whole lot further, but that's beyond the scope here.
In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.
public ActionResult VolunteersAdd()
{
VolunteerModel model = new VolunteerModel(); //to set the default values
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VolunteersAdd(VolunteerModel model)
{
return View(model);
}
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
I had a problem like this where Intellisense didn't seem to recognise the existence of one project (lots of "can't find this type", "this namespace doesn't exist", etc. errors).
Removing and re-adding the project reference in all the referencing projects would fix the issue, but the underlying cause could be fixed by editing the .proj file of the problem project.
Near the top of the "missing" project' .csproj file is an element:
<ProjectGuid>{GUID}</ProjectGuid>
and in all of the referencing projects .csproj files were project references:
<ProjectReference Include="..\OffendingProject\OffendingProject.csproj">
<Project>{ANOTHER-GUID}</Project>
<Name>Offending Project</Name>
</ProjectReference>
The referencing GUID didn't match the project's GUID. Replacing {GUID}
above with {ANOTHER-GUID}
fixed the problem without having to go through every referencing project.
Long Press on Power button, then you will have the option for the screenshot.
You could use if(number >= 0)
. The fact that you use int number = input.nextInt();
makes sure that it has to be an Integer.
I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html
To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.
If you are inheriting UITableViewController, you can just init tableView again.
Objective C:
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
Swift:
self.tableView = UITableView(frame: CGRect.zero, style: .grouped)
Installing fiddler was causing me similar problem. Uninstalling fiddler and removing the fiddler proxy from the machine.config (from both Framework and Framework64) solved the problem.
You are writing if(true)
so it will always show "Hello " message.
You should take decision on the basis of value of n
returned.
In case you also want to include your real name in the from-field, you can use the following format
mailx -r "[email protected] (My Name)" -s "My Subject" ...
If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:
mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...
Hope this can save someone an hour of hard work/research!
It is rather messy but you need to do something like the following:
START "do something window" dir
FOR /F "tokens=2" %I in ('TASKLIST /NH /FI "WINDOWTITLE eq do something window"' ) DO SET PID=%I
ECHO %PID%
TASKKILL /PID %PID%
Found this on this page.
(This kind of thing is much easier if you have a UNIX / LINUX system ... or if you run Cygwin or similar on Windows.)
This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});
In addition to the answer, you can't directly use output redirection operators in the set part of for
loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^
):
for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)
Reference: Redirect output of command in for loop of batch script
std
namespace (where features of the C++ Standard Library, such as string
or vector
, are declared).After you write this instruction, if the compiler sees string
it will know that you may be referring to std::string
, and if it sees vector
, it will know that you may be referring to std::vector
. (Provided that you have included in your compilation unit the header files where they are defined, of course.)
If you don't write it, when the compiler sees string
or vector
it will not know what you are refering to. You will need to explicitly tell it std::string
or std::vector
, and if you don't, you will get a compile error.
Follow the steps to store data in Angular - local storage:
Inject 'ngStorage' in your angular.module
eg: angular.module("app", [ 'ngStorage']);
$localStorage
in your app.controller function4.You can use $localStorage
inside your controller
Eg: $localstorage.login= true;
The above will store the localstorage in your browser application
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
in run time, you can use following code
btn.setBackgroundDrawable(null);
<script type="text/javascript">
$(document).ready(function() {
var asdf = $('.capsf').text();
$('.capsf').text(asdf.toLowerCase());
});
</script>
<div style="text-transform: capitalize;" class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>
I solved is by using android:background instead of app:srcCompact.
This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .
I have just installed mongodb 3.4 with homebrew.(brew install mongodb) It looks for /data/db by default.
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
Try this
myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )
Edit: Relevant sources:
Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...
Say I have the following DataFrame
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
You could count a single column by
df.A.count()
#or
df['A'].count()
both evaluate to 5.
The cool thing (or one of many w.r.t. pandas
) is that if you have NA
values, count takes that into consideration.
So if I did
df['A'][1::2] = np.NAN
df.count()
The result would be
A 3
B 5
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow
and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
You need to specify the number of rows which should be deleted. In your case (and I assume that you only want to keep one) this can be done like this:
DELETE FROM your_table WHERE id_users=1 AND id_product=2
LIMIT (SELECT COUNT(*)-1 FROM your_table WHERE id_users=1 AND id_product=2)
Hint text not bold, I try to below code.
When I change inputtype=email
, other edittext is bold. But when I change input type to password
, hint is normal.
I need hint text to be bold, my code is:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="56dp"
app:theme="@style/Widget.Design.TextInputLayout"
>
<EditText
android:id="@+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:textStyle="bold"
android:inputType="textPassword"
android:textColor="@color/White"
style="@style/Base.TextAppearance.AppCompat.Small"
android:drawableLeft="@drawable/ic_password"
android:drawablePadding="10dp"
/>
</android.support.design.widget.TextInputLayout>
Just add "sudo" before npm command. Thats it.
I am fairly new to Javascript. But this is what I understood:
JSON.parse()
returns SyntaxError
exceptions when invalid JSON is provided as its first parameter. So. It would be better to catch that exception as such like as follows:
try {
let sData = `
{
"id": "1",
"name": "UbuntuGod",
}
`;
console.log(JSON.parse(sData));
} catch (objError) {
if (objError instanceof SyntaxError) {
console.error(objError.name);
} else {
console.error(objError.message);
}
}
The reason why I made the words "first parameter" bold is that JSON.parse()
takes a reviver function as its second parameter.
Find the right version of your anaconda
Put it to ~/.zshrc
via command vim ~/.zshrc
export PATH="/User/<your-username>/anaconda2/bin:$PATH"
export PATH="/User/<your-username>/anaconda3/bin:$PATH"
export PATH="/anaconda2/bin:$PATH"
export PATH="/anaconda3/bin:$PATH"
Restart the zsh source ~/.zshrc
In most cases, you shouldn't use a regex for that.
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc
correctly by keeping the whole name.
I know you don't want to obfuscate, but maybe you should check out dotfuscator, it will take your compiled assemblies and obfuscate them for you. I think it can even encrypt them.
No, there is no type called "byte
" in C++. What you want instead is unsigned char
(or, if you need exactly 8 bits, uint8_t
from <cstdint>
, since C++11). Note that char
is not necessarily an accurate alternative, as it means signed char
on some compilers and unsigned char
on others.
You can also use the following command:
pylint --disable=C0321 test.py
My Pylint version is 0.25.1.
Using urllib, you can get this done instantly.
import urllib.request
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(URL, "images/0.jpg")
pom.xml
as -<project>
....
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
...
</build>
...
</project>
It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.
Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
I have resolve the problem as below 1. Get the tag from your branch 2. Write below command
Example: git branch <Hotfix branch> <TAG>
git branch hotfix_4.4.3 v4.4.3
git checkout hotfix_4.4.3
or you can do with other command
git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local
once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command
git push --set-upstream origin hotfix_4.4.3
It looks like you are trying to use (almost) straight up C code here. Go has a few differences.
const
. The term const
has a different meaning in Go, as it does in C. The list should be defined as var
instead.basenameOpts
as opposed to basename_opts
.char
type in Go. You probably want byte
(or rune
if you intend to allow unicode codepoints).var x = foo
.For example:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
An alternative is to declare the list with its type and then use an init
function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init
functions are run when the program is being initialized and are guaranteed to finish before main
is executed. You can have multiple init
functions in a package, or even in the same source file.
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
}
Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.
This occurs if the password for the database is not given.
default="postgres://postgres:[email protected]:5432/DBname"
Place the below lines in your <EditText>
:
android:digits="0123456789"
android:inputType="phone"
You could also use the generic function cbind()
and lm()
without the intercept:
cbind(lm(d$Rate1~-1+d$Name)$coef,lm(d$Rate2~-1+d$Name)$coef)
> [,1] [,2]
>d$NameAira 16.33333 47.00000
>d$NameBen 31.33333 50.33333
>d$NameCat 44.66667 54.00000
Execute chmod 777 -R scripts/
, it worked fine for me ;)
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
If you want to run your command in parallel for each line you can use GNU Parallel
parallel -a <your file> <program>
Each line of your file will be passed to program as an argument. By default parallel
runs as many threads as your CPUs count. But you can specify it with -j
hope it will work
@Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })
Here String.Empty
will be the empty as a default selector.
Maybe this helps someone:
git tag 0.0.1 # creates tag locally
git push origin 0.0.1 # pushes tag to remote
git tag --delete 0.0.1 # deletes tag locally
git push --delete origin 0.0.1 # deletes remote tag
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Starting in NumPy version 1.10, we have the method stack. It can stack arrays of any dimension (all equal):
# List of arrays.
L = [np.random.randn(5,4,2,5,1,2) for i in range(10)]
# Stack them using axis=0.
M = np.stack(L)
M.shape # == (10,5,4,2,5,1,2)
np.all(M == L) # == True
M = np.stack(L, axis=1)
M.shape # == (5,10,4,2,5,1,2)
np.all(M == L) # == False (Don't Panic)
# This are all true
np.all(M[:,0,:] == L[0]) # == True
all(np.all(M[:,i,:] == L[i]) for i in range(10)) # == True
Enjoy,
-------------------------------------------------------------------------------
-- Author name
-- Created date
-- Purpose description of the business/technical purpose
-- using multiple lines as needed
-- Copyright © yyyy, Company Name, All Rights Reserved
-------------------------------------------------------------------------------
-- Modification History
--
-- 01/01/0000 developer full name
-- A comprehensive description of the changes. The description may use as
-- many lines as needed.
-------------------------------------------------------------------------------
Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"
According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:
Model.objects.all().order_by('-id')[:10:1]
Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.
You have to edit httpd.conf
and find this line: Listen 127.0.0.1:80
Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80
I used 192.167.137.1
as my LAN IP of Windows 7. Restart Apache and enjoy sharing.
You can try this one it is short :)
SystemClock.sleep(7000);
It will sleep for 7 sec look at documentation
use curl php library: http://php.net/manual/en/book.curl.php
direct example: CURL_EXEC:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
If you don't need the leading and trailing spaces :
str.Trim().Length
In your case you have a List
of Strings and most of the already proposed solutions (I specially like @guyblank answer) are just fine but!!!, if you have a List
of beans, which is my case, you can use Comparable
interface in your bean like this:
public class UserBean implements Comparable<UserBean> {
private String name;
private String surname;
private Integer phone;
// GETTERS AND SETTERS
public int compareTo(UserBean bean) {
return name.compareToIgnoreCase(bean.name);
}
}
Then you only need to create your ArrayList<UserBean> userBeanArray = new ArrayList<UserBean>();
, fill it and sort it: Collections.sort(userBeanArray);
And you have it done!
Hope to help to community ;-)
I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!
style
.wrapper{background-image:url(silhouette.png);}
.original{opacity:0.7:}
.original:hover{opacity:1}
<div class="wrapper">
<div class="img">
<img src="original.png">
</div>
</div>
I followed all the answers of this question to change a working legacy code using - Statement
( but having SQL Injections ) to a solution using PreparedStatement
with a much slower code because of poor understanding of semantics around Statement.addBatch(String sql)
& PreparedStatement.addBatch()
.
So I am listing my scenario here so others don't make same mistake.
My scenario was
Statement statement = connection.createStatement();
for (Object object : objectList) {
//Create a query which would be different for each object
// Add this query to statement for batch using - statement.addBatch(query);
}
statement.executeBatch();
So in above code , I had thousands of different queries, all added to same statement and this code worked faster because statements not being cached was good & this code executed rarely in the app.
Now to fix SQL Injections, I changed this code to ,
List<PreparedStatement> pStatements = new ArrayList<>();
for (Object object : objectList) {
//Create a query which would be different for each object
PreparedStatement pStatement =connection.prepareStatement(query);
// This query can't be added to batch because its a different query so I used list.
//Set parameter to pStatement using object
pStatements.add(pStatement);
}// Object loop
// In place of statement.executeBatch(); , I had to loop around the list & execute each update separately
for (PreparedStatement ps : pStatements) {
ps.executeUpdate();
}
So you see, I started creating thousands of PreparedStatement
objects & then eventually not able to utilize batching because my scenario demanded that - there are thousands of UPDATE or INSERT queries & all of these queries happen to be different.
Fixing SQL injection was mandatory at no cost of performance degradation and I don't think that it is possible with PreparedStatement
in this scenario.
Also, when you use inbuilt batching facility, you have to worry about closing only one Statement but with this List approach, you need to close statement before reuse , Reusing a PreparedStatement
Yes, it is mainly to anchor your keywords, in particular the location of your page, so whenever URL loads the page with particular anchor name, then it will be pointed to that particular location.
For example, www.something.com/some_page/#computer if it is very lengthy page and you want to show exactly computer then you can anchor.
<p> adfadsf </p>
<p> adfadsf </p>
<p> adfadsf </p>
<a name="computer"></a><p> Computer topics </p>
<p> adfadsf </p>
Now the page will scroll and bring computer-related topics to the top.
getSupportFragmentManager()
used when you are in activity and want to get a fragment but in the fragment you can access
getSupportFragmentManager()
by use another method called getFragmentMangaer()
works the same like getSupportFragmentManager()
and you can use it like you used to:
fragmentTransaction =getFragmentManager().beginTransaction();
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing
The background-image
can also be used to create an underline. This method handles line breaks.
It has to be shifted down via background-position
and repeated horizontally. The line width can be adjusted to some degree using background-size
(the background is limited to the content box of the element).
.underline
{
--color: green;
font-size: 40px;
background-image: linear-gradient(var(--color) 0%, var(--color) 100%);
background-repeat: repeat-x;
background-position: 0 1.05em;
background-size: 2px 5px;
}
_x000D_
<span class="underline">
Underlined<br/>
Text
</span>
_x000D_
var list3 = list1.Where(x => !list2.Any(z => z.Id == x.Id)).ToList();
Note: list3
will contain the items or objects that are not in both lists.
Note: Its ToList()
not toList()
A note about 64bit Windows which seems to trip up a few folks. If your app is running under 64bit Windows, you likely have to set the DWORD under [HKLM\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION] instead.
Same think can be done using lambda function. Here I am reading the data from a xlsx file.
import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df
Output:
cluster Unnamed: 1 date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
Sum two columns into 3rd new one.
df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df
Output:
cluster Unnamed: 1 date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
You are not doing error checking after the call to mysql_query:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
In case mysql_query
fails, it returns false
, a boolean
value. When you pass this to mysql_fetch_array
function (which expects a mysql result object
) we get this error.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
A typical way would be to use stringstream
:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
To add to Timo's answer LINQ can be used like this as well:
items = items.Select(i => {
...
//perform some logic adding / updating.
return i / return new Item();
...
//To remove an item simply have logic to return null.
//Then attach the Where to filter out nulls
return null;
...
}).Where(i => i != null);
Could you try this one:
create or replace
procedure point_triangle
IS
BEGIN
FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P where P.TEAM = 'IND' group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.S);
END LOOP;
END;
How about this? I frequently use the CSS Flexible Box Layout to center something.
<div style="display: flex; justify-content: center;">_x000D_
<img src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png" style="width: 40px; height: 40px;" />_x000D_
</div>
_x000D_
Alternately, you can start a program containing the line with one click.
Just select the method stub for it when creating the new Java class, where the code says,
Which method stubs would you like to create?
[check-box] public static void main(String[]args) <---- Select this one.
[check-box] Constructors from superclass
[check-box] Inherited abstract methods
Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.
I had this problem but didn't have a version conflict in my package.json.
My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.
While inserting the data, we have to used character string delimiter (' '
). And, you missed it (' '
) while inserting values which is the reason of your error message. The correction of code is given below:
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
To see the file size of your containers, you can use the --size
argument of docker ps
:
docker ps --size
To complement @tyczj answer:
Generic Adapter Pseido code:
public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{
private List<T> mList;
//default implementation code
public abstract int getLayout();
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(getLayout(), parent, false);
return getCustomHolder(v);
}
public Holders.TextImageHolder getCustomHolder(View v) {
return new Holders.TextImageHolder(v){
@Override
public void onClick(View v) {
onItem(mList.get(this.getAdapterPosition()));
}
};
}
abstract void onItem(T t);
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
onSet(mList.get(position), (K) holder);
}
public abstract void onSet(T item, K holder);
}
ViewHolder:
public class Holders {
public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView text;
public TextImageHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
text.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
}
Adapter usage:
public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {
public CategoriesAdapter(List<Category> list, Context context) {
super(list, context);
}
@Override
void onItem(Category category) {
}
@Override
public int getLayout() {
return R.layout.categories_row;
}
@Override
public void onSet(Category item, Holders.TextImageHolder holder) {
}
}
C99 standard on c >= '0' && c <= '9'
c >= '0' && c <= '9'
(mentioned in another answer) works because C99 N1256 standard draft 5.2.1 "Character sets" says:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
ASCII is not guaranteed however.
simple example of a function parent_by_selector which return a parent or null (no selector matches):
function parent_by_selector(node, selector, stop_selector = 'body') {
var parent = node.parentNode;
while (true) {
if (parent.matches(stop_selector)) break;
if (parent.matches(selector)) break;
parent = parent.parentNode; // get upper parent and check again
}
if (parent.matches(stop_selector)) parent = null; // when parent is a tag 'body' -> parent not found
return parent;
};
If nothing works then add authentication mode="Windows" in your system.web attribute in your Web.Config file. hope it will work for you.
$(document).on('change','#multiid',function(){
// you desired code
});
reference on
You should probably check for errors in /var/log/nginx/error.log
.
In my case I did no add the port for ipv6. You should also do this (in case you are running nginx on a port other than 80):
listen [::]:8000 default_server ipv6only=on;
Do you mean something like this:
s1 = '00000001'
s2 = '11111110'
int(s1,2) ^ int(s2,2)
Remove the if
keyword. It should just be predicate ? true_result : false_result
.
Also ? :
is called ternary operator.
but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
hi how to delete from datagridview
1.make query delete by id
2.type
tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);
Try this
div_x000D_
{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:red;_x000D_
transition: all 1s ease-in-out;_x000D_
-webkit-transition: all 1s ease-in-out;_x000D_
-moz-transition: all 1s ease-in-out;_x000D_
-o-transition: all 1s ease-in-out;_x000D_
-ms-transition: all 1s ease-in-out;_x000D_
position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
transform: translate(3em,0);_x000D_
-webkit-transform: translate(3em,0);_x000D_
-moz-transform: translate(3em,0);_x000D_
-o-transform: translate(3em,0);_x000D_
-ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
If you are splitting a string in Lua, you should try the string.gmatch() or string.sub() methods. Use the string.sub() method if you know the index you wish to split the string at, or use the string.gmatch() if you will parse the string to find the location to split the string at.
Example using string.gmatch() from Lua 5.1 Reference Manual:
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:
f (a,b)
previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.
The above answers may help you but you may also want to know how to use array of function pointers.
void fun1()
{
}
void fun2()
{
}
void fun3()
{
}
void (*func_ptr[3])() = {fun1, fun2, fun3};
main()
{
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;
}
You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.
You can also pass arguments like below if all the above functions are having the same number of arguments of same type.
(*func_ptr[option])(argu1);
Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1
can be called if option=0, fun2
can be called if option=1 and fun3
can be called if option=2.
For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:
print str_replace(
array("search1","search2"),
array("replace1", "replace2"),
"search1 search2"
);
// Output: replace1 replace2
Your can use NumPy's array indexing:
def unison_shuffled_copies(a, b):
assert len(a) == len(b)
p = numpy.random.permutation(len(a))
return a[p], b[p]
This will result in creation of separate unison-shuffled arrays.
After a quick google:
__STDC__
and __STDC_VERSION__
, see here
Try this jsfiddle. This is using jQuery and made from Hashem Qolami's answer. At first, make a regular table then make it scrollable.
const makeScrollableTable = function (tableSelector, tbodyHeight) {
let $table = $(tableSelector);
let $bodyCells = $table.find('tbody tr:first').children();
let $headCells = $table.find('thead tr:first').children();
let headColWidth = 0;
let bodyColWidth = 0;
headColWidth = $headCells.map(function () {
return $(this).outerWidth();
}).get();
bodyColWidth = $bodyCells.map(function () {
return $(this).outerWidth();
}).get();
$table.find('thead tr').children().each(function (i, v) {
$(v).css("width", headColWidth[i]+"px");
$(v).css("min-width", headColWidth[i]+"px");
$(v).css("max-width", headColWidth[i]+"px");
});
$table.find('tbody tr').children().each(function (i, v) {
$(v).css("width", bodyColWidth[i]+"px");
$(v).css("min-width", bodyColWidth[i]+"px");
$(v).css("max-width", bodyColWidth[i]+"px");
});
$table.find('thead').css("display", "block");
$table.find('tbody').css("display", "block");
$table.find('tbody').css("height", tbodyHeight+"px");
$table.find('tbody').css("overflow-y", "auto");
$table.find('tbody').css("overflow-x", "hidden");
};
Then you can use this function as follows:
makeScrollableTable('#test-table', 250);
I've never actually used this, but try view.getClass().getGenericSuperclass()
So is there any other method to achieve this goal?
No. In order to convert an image to a byte array you have to specify an image format - just as you have to specify an encoding when you convert text to a byte array.
If you're worried about compression artefacts, pick a lossless format. If you're worried about CPU resources, pick a format which doesn't bother compressing - just raw ARGB pixels, for example. But of course that will lead to a larger byte array.
Note that if you pick a format which does include compression, there's no point in then compressing the byte array afterwards - it's almost certain to have no beneficial effect.
string.find("substring")
will help you. This function returns -1
when there is no substring.
I had such problem. Solution was simple :
P.S. Sorry, for bad grammar.
Modify the maximun memory parameter in eclipse.ini
-Xmx1024m
And restart your computer.
It worked for me :)
FormsModule
should be added at imports array
not declarations array
.
BrowserModule
, FormsModule
, HttpModule
Components
, Pipes
, Directives
refer below change:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
After searching a bit about the method to open the existing sheet in xlxs, i discovered
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
You can now append/write any data to the open worksheet. I hope it helps. Thanks
See if this is what you want to do:
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"
You can follow these steps to remove all the files associated with virtualenv and then reinstall the virtualenv again and using it
cd {python virtualenv folder}
find {broken virtualenv}/ -type l ## to list out all the links
deactivate ## deactivate if virtualenv is active
find {broken virtualenv}/ -type l -delete ## to delete the broken links
virtualenv {broken virtualenv} --python=python3 ## recreate links to OS's python
workon {broken virtualenv} ## activate & workon the fixed virtualenv
pip3 install ... {other packages required for the project}
Here is a version that will handle multiple files drag and dropped from windows. Based on the above works by
Christian Lemer
plang
ScottF
Open Notepad, create a file called XlsToCsv.vbs and paste this in:
'* Usage: Drop .xl* files on me to export each sheet as CSV
'* Global Settings and Variables
Dim gSkip
Set args = Wscript.Arguments
For Each sFilename In args
iErr = ExportExcelFileToCSV(sFilename)
' 0 for normal success
' 404 for file not found
' 10 for file skipped (or user abort if script returns 10)
Next
WScript.Quit(0)
Function ExportExcelFileToCSV(sFilename)
'* Settings
Dim oExcel, oFSO, oExcelFile
Set oExcel = CreateObject("Excel.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
iCSV_Format = 6
'* Set Up
sExtension = oFSO.GetExtensionName(sFilename)
if sExtension = "" then
ExportExcelFileToCSV = 404
Exit Function
end if
sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
if not (sTest = "xl") then
if (PromptForSkip(sFilename,oExcel)) then
ExportExcelFileToCSV = 10
Exit Function
end if
End If
sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")
'* Do Work
Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
For Each oSheet in oExcelFile.Sheets
sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
oExcelFile.Sheets(oSheet.Name).Select
oExcelFile.SaveAs sThisDestination, iCSV_Format
Next
'* Take Down
oExcelFile.Close False
oExcel.Quit
ExportExcelFileToCSV = 0
Exit Function
End Function
Function PromptForSkip(sFilename,oExcel)
if not (VarType(gSkip) = vbEmpty) then
PromptForSkip = gSkip
Exit Function
end if
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sPrompt = vbCRLF & _
"A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
"Do you want to skip this and all other unrecognized files? (Will only prompt this once)" & vbCRLF & _
"" & vbCRLF & _
"Yes - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
"No - Will pass the file to excel regardless of extension" & vbCRLF & _
"Cancel - Abort any further conversions and exit this script" & vbCRLF & _
"" & vbCRLF & _
"The unrecognized file was:" & vbCRLF & _
sFilename & vbCRLF & _
"" & vbCRLF & _
"The path returned by the system was:" & vbCRLF & _
oFSO.GetAbsolutePathName(sFilename) & vbCRLF
sTitle = "Unrecognized File Type Encountered"
sResponse = MsgBox (sPrompt,vbYesNoCancel,sTitle)
Select Case sResponse
Case vbYes
gSkip = True
Case vbNo
gSkip = False
Case vbCancel
oExcel.Quit
WScript.Quit(10) '* 10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
End Select
PromptForSkip = gSkip
Exit Function
End Function
The Interface javax.servlet.http.HttpServletResponse
from the servlet API has all the response codes in the form of int
constants names SC_<description>
. See http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html
This is the easiest way I can figure out:
#!/usr/bin/python3
for i in range(97, 123):
print("{:c}".format(i), end='')
So, 97 to 122 are the ASCII number equivalent to 'a' to and 'z'. Notice the lowercase and the need to put 123, since it will not be included).
In print function make sure to set the {:c}
(character) format, and, in this case, we want it to print it all together not even letting a new line at the end, so end=''
would do the job.
The result is this:
abcdefghijklmnopqrstuvwxyz
In that case you should use ListBox
control instead of dropdown and Set the SelectionMode
property to Multiple
<asp:ListBox runat="server" SelectionMode="Multiple" >
<asp:ListItem Text="test1"></asp:ListItem>
<asp:ListItem Text="test2"></asp:ListItem>
<asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>
More information will be useful.
When I was faced with the same error message all I had to do was to correctly configure the credentials page of the DataSource(I am using Report Builder 3). if you chose the default, the report would work fine in Report Builder but would fail on the Report Server.
You may review more details of this fix here: https://hodentekmsss.blogspot.com/2017/05/fix-for-rserroropeningconnection-in.html
Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.
For array type Please try this one.
List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-"
for a red line, or by explicitely stating the color
argument.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
See also the plot command's documentation.
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
If you want to change this color later on, you can do so by
plt.gca().get_lines()[0].set_color("black")
This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
and if you have more lines you can loop over them as well.
You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point. If result is equal to zero then the number is a whole number.
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
Additionally to IIDan's answer: For some purposes it is necessary to set
label.layer.shouldRasterize = YES
I think this is due to the blend mode that is used to render the shadow. For example I had a dark background and white text on it and wanted to "highlight" the text using a black shadowy glow. It wasn't working until I set this property.
You are comparing two objects for equality. The snippet:
if (obj == this) { return true; }
is a quick test that can be read
"If the object I'm comparing myself to is me, return true"
. You usually see this happen in equals
methods so they can exit early and avoid other costly comparisons.
How about
if value in my_array[:, col_num]:
do_whatever
Edit: I think __contains__
is implemented in such a way that this is the same as @detly's version
You can configure the connect body parser middleware in a configuration block in your main application file:
/** Form Handling */
app.use(express.bodyParser({
uploadDir: '/tmp/uploads',
keepExtensions: true
}))
app.use(express.limit('5mb'));
In my experience, this turned out to be the most efficient
driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')
We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.
EDIT: removed Keys dependency
As ben foster says you can return the Javascripts and it will redirect you to the desired page.
To load page in the current page:
return JavaScript("window.location = 'http://www.google.co.uk'");'
To load page in the new tab:
return JavaScript("window.open('http://www.google.co.uk')");
Wireshark does not do port redirection, but sniffs and interprets a lot of protocols.
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
You can use Path API as follow:
var filenNme = Path.GetFileNameWithoutExtension([File Path]);
More info: Path.GetFileNameWithoutExtension
Using flexbox
#parent_div_1{
display:flex;
flex-wrap: wrap;
}
From linux/typecheck.h:
/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
})
Here you can find explanation which statements from standard and which GNU extensions above code uses.
(Maybe a bit not in scope of the question, since question is not about failure on type mismatch, but anyway, leaving it here).
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
You have two span6 divs within your row so that will take up the whole 12 spans that a row is made up of.
Adding pull-right to the second span6 div isn't going to do anything to it as it's already sitting to the right.
If you mean you want to have the text in the second span6 div aligned to the right then simple add a new class to that div and give it the text-align: right value e.g.
.myclass {
text-align: right;
}
UPDATE:
EricFreese pointed out that in the 2.3 release of Bootstrap (last week) they've added text-align utility classes that you can use:
.text-left
.text-center
.text-right
http://twitter.github.com/bootstrap/base-css.html#typography
Your problem is that you are naming your component class Date
. When you call new Date()
within your class, it won't create an instance of the Date
you expect it to create (which is likely this Date
)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.
If you want to use Date
within your class, try naming your class something different such as Calendar
or DateComponent
.
The reason for this is how JavaScript deals with name scope: Whenever you create a new named entity, if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date
within a class named Date
, the name Date
will refer to that class and not to any object named Date
which existed before the class definition started.
I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze
will show you the library as installed if your current directory contains lib.egg-info
folder. And pip uninstall <lib>
will give you the same error message.
egg-info
folderspip show <lib-name>
to see the details about the location of the library, so you can remove files manually.For a direct scroll:
getListView().setSelection(21);
For a smooth scroll:
getListView().smoothScrollToPosition(21);
Another js alternative:
fontsize = function () {
var fontSize = $("#container").width() * 0.10; // 10% of container width
$("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);
Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:
<div id="container">
<svg width="100%" height="100%" viewBox="0 0 13 15">
<text x="0" y="13">X</text>
</svg>
</div>
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
# 10GB
SIZE="10"
# check the current size
CHECK="`du -hs /media/662499e1-b699-19ad-57b3-acb127aa5a2b/Aufnahmen`"
CHECK=${CHECK%G*}
echo "Current Foldersize: $CHECK GB"
if (( $(echo "$CHECK > $SIZE" |bc -l) )); then
echo "Folder is bigger than $SIZE GB"
else
echo "Folder is smaller than $SIZE GB"
fi
Could you also increase post_max_size
and see if it helps?
Uploading a file through an HTML form makes the upload treated like any other form element content, that's why increasing post_max_size
should be required too.
Update : the final solution involved the command-line:
To export only 1 table you would do
mysqldump -u user_name -p your_password your_database_name your_table_name > dump_file.sql
and to import :
mysql -u your_user -p your_database < dump_file.sql
'drop table your_tabe_name;' can also be added at the top of the import script if it's not already there, to ensure the table gets deleted before the script creates and fill it
Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.
library(plyr)
lapply(df, count)
I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.
For example, if you never want Newtonsoft.Json
to be updated past version 3.x.x
in your project, change the corresponding package
element in your packages.config
file to look like this:
<package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />
Notice the allowedVersions
attribute. This will limit the version of that package to versions between 3.0
(inclusive) and 4.0
(exclusive). Then, when you do an Update-Package
on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x
.
The documentation for this functionality is here.
Example:
You want to see all the items that are (round AND (red OR blue)):
{
"query": {
"bool": {
"must": [
{
"term": {"shape": "round"}
},
{
"bool": {
"should": [
{"term": {"color": "red"}},
{"term": {"color": "blue"}}
]
}
}
]
}
}
}
You can also do more complex versions of OR, for example if you want to match at least 3 out of 5, you can specify 5 options under "should" and set a "minimum_should" of 3.
Thanks to Glen Thompson and Sebastialonso for finding where my nesting wasn't quite right before.
Thanks also to Fatmajk for pointing out that "term" becomes "match" in ElasticSearch 6.
This is speculation, but based on Google's reference to the "risk analysis engine" they use (http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html)
I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.
It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.
In my case, when I created the web form, it was named as WebForm1.aspx and respective names (WebForm1). Letter, I renamed that to something else. I renamed manually at almost all the places, but one place in designer file was still showing it as 'WebForm1'.
I changed that too and got rid of this error.
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
The one with the "Pings" helped me... but may be explained a little better...
For me the solution was to change:
copy $(TargetDir)$(TargetName).* $(SolutionDir)bin
to this:
copy "$(TargetDir)$(TargetName).*" "$(SolutionDir)bin"
Hope it works for you. :-)
if (window.console && 'function' === typeof window.console.log) { window.console.log(o); }
For newest iTunes 12.7 and above can easily install IPA by copy and paste
composer create-project laravel/laravel ProjectName
I had the same error message. In my case I had inadvertently mixed the ES6 export default function myFunc
syntax with const myFunc = require('./myFunc');
.
Using module.exports = myFunc;
instead solved the issue.
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String
or the char
primitive -- you should only be using byte[]
arrays or ByteBuffer
objects. Then, you can use java.nio.charset.Charset
to convert between encodings:
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
In your windows os follow the following steps:
The proper way to sort strings is:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
The previous example of mylist.sort(key=lambda x: x.lower())
will work fine for ASCII-only contexts.
In curl version 7.22.0 on Ubuntu and 7.24.0 on OSX the solution to not show progress but to show errors is to use both -s
(--silent
) and -S
(--show-error
) like so:
curl -sS http://google.com > temp.html
This works for both redirected output > /some/file
, piped output | less
and outputting directly to the terminal for me.
Update: Since curl 7.67.0 there is a new option --no-progress-meter
which does precisely this and nothing else, see clonejo's answer for more details.