I had the same issue, and when I checked if Java is installed I realised it's not, so installing Java solved the problem for me.
Check for java:
java -version
If Java is installed in the system, the command will return the java version otherwise it will show a message like this.
The program 'java' can be found in the following packages:
* default-jre
* gcj-5-jre-headless
* openjdk-8-jre-headless
* gcj-4.8-jre-headless
* gcj-4.9-jre-headless
* openjdk-9-jre-headless
To install java use the following command.
sudo apt-get install default-jre
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
After a long struggle, I've switched my node architecture to x86 and it worked like a charm.
"no suitable driver" usually means that the syntax for the connection URL is incorrect.
in
is definitely more pythonic.
In fact has_key()
was removed in Python 3.x.
The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.
So, you need an alternative approach.
1). Take you current query and join the base data back on it
SELECT
cpe.*
FROM
Filteredfmgcms_claimpaymentestimate cpe
INNER JOIN
(yourQuery) AS lookup
ON lookup.MaxData = cpe.createdOn
AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid
2). Use a CTE to do it all in one go...
WITH
sequenced_data AS
(
SELECT
*,
ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
FROM
Filteredfmgcms_claimpaymentestimate
WHERE
createdon < 'reportstartdate'
)
SELECT
*
FROM
sequenced_data
WHERE
sequence_id = 1
NOTE: Using ROW_NUMBER()
will ensure just one record per fmgcms_cpeclaimid
. Even if multiple records are tied with the exact same createdon
value. If you can have ties, and want all records with the same createdon
value, use RANK()
instead.
It should be the same command, except SET instead of EXPORT
I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:
VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"
Running this in my host's terminal worked like a charm for me.
Source: https://forums.virtualbox.org/viewtopic.php?f=8&t=47821
Or you can hack it up.
Items.All(p => { p.IsAwesome = true; return true; });
private void setRowNumber(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.HeaderCell.Value = (row.Index + 1).ToString();
}
}
This worked for me.
I searched for a simple solution and this works well for me:
//input data
view = new Uint8Array(data);
//output string
serialString = ua2text(view);
//convert UTF8 to string
function ua2text(ua) {
s = "";
for (var i = 0; i < ua.length; i++) {
s += String.fromCharCode(ua[i]);
}
return s;
}
Only issue I have is sometimes I get one character at a time. This might be by design with my source of the arraybuffer. I'm using https://github.com/xseignard/cordovarduino to read serial data on an android device.
This was annoying me a while and I didn't like any of the answers given, so I had a look at the source to see how it works.
FractalWrench is on the right path, but it can be used below API 23 and doesn't have to be set on the toolbar it's self.
As others have said you can set a style on the toolbar with
app:theme="@style/ActionBar"
and in that style you can set the title text colour with
<item name="titleTextColor">#00f</item>
for pre API 23 or for 23+
<item name="android:titleTextColor">your colour</item>
Full xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
app:theme="@style/ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"/>
<style name="ActionBar" parent="@style/ThemeOverlay.AppCompat.ActionBar">
<item name="android:titleTextStyle">@style/ActionBarTextStyle</item>
<item name="titleTextColor">your colour</item>
<item name="android:background">#ff9900</item>
</style>
Heres all the attributes that can be set for a toolbar
<declare-styleable name="Toolbar">
<attr name="titleTextAppearance" format="reference" />
<attr name="subtitleTextAppearance" format="reference" />
<attr name="title" />
<attr name="subtitle" />
<attr name="gravity" />
<attr name="titleMargins" format="dimension" />
<attr name="titleMarginStart" format="dimension" />
<attr name="titleMarginEnd" format="dimension" />
<attr name="titleMarginTop" format="dimension" />
<attr name="titleMarginBottom" format="dimension" />
<attr name="contentInsetStart" />
<attr name="contentInsetEnd" />
<attr name="contentInsetLeft" />
<attr name="contentInsetRight" />
<attr name="maxButtonHeight" format="dimension" />
<attr name="navigationButtonStyle" format="reference" />
<attr name="buttonGravity">
<!-- Push object to the top of its container, not changing its size. -->
<flag name="top" value="0x30" />
<!-- Push object to the bottom of its container, not changing its size. -->
<flag name="bottom" value="0x50" />
</attr>
<!-- Icon drawable to use for the collapse button. -->
<attr name="collapseIcon" format="reference" />
<!-- Text to set as the content description for the collapse button. -->
<attr name="collapseContentDescription" format="string" />
<!-- Reference to a theme that should be used to inflate popups
shown by widgets in the toolbar. -->
<attr name="popupTheme" format="reference" />
<!-- Icon drawable to use for the navigation button located at
the start of the toolbar. -->
<attr name="navigationIcon" format="reference" />
<!-- Text to set as the content description for the navigation button
located at the start of the toolbar. -->
<attr name="navigationContentDescription" format="string" />
<!-- Drawable to set as the logo that appears at the starting side of
the Toolbar, just after the navigation button. -->
<attr name="logo" />
<!-- A content description string to describe the appearance of the
associated logo image. -->
<attr name="logoDescription" format="string" />
<!-- A color to apply to the title string. -->
<attr name="titleTextColor" format="color" />
<!-- A color to apply to the subtitle string. -->
<attr name="subtitleTextColor" format="color" />
</declare-styleable>
Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.
With Java 10, you could now use Set#copyOf
to easily convert a List<E>
to an unmodifiable Set<E>
:
Example:
var set = Set.copyOf(list);
Keep in mind that this is an unordered operation, and null
elements are not permitted, as it will throw a NullPointerException
.
If you wish for it to be modifiable, then simply pass it into the constructor a Set
implementation.
I had a similar purpose. I wanted to resolve pressing the "Enter" key on the keyboard (which I wanted to customize) in an AutoCompleteTextView which extends TextView. I tried different solutions from above and they seemed to work. BUT I experienced some problems when I switched the input type on my device (Nexus 4 with AOKP ROM) from SwiftKey 3 (where it worked perfectly) to the standard Android keyboard (where instead of handling my code from the listener, a new line was entered after pressing the "Enter" key. It took me a while to handle this problem, but I don't know if it will work under all circumstances no matter which input type you use.
So here's my solution:
Set the input type attribute of the TextView in the xml to "text":
android:inputType="text"
Customize the label of the "Enter" key on the keyboard:
myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
Set an OnEditorActionListener to the TextView:
myTextView.setOnEditorActionListener(new OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event)
{
boolean handled = false;
if (event.getAction() == KeyEvent.KEYCODE_ENTER)
{
// Handle pressing "Enter" key here
handled = true;
}
return handled;
}
});
I hope this can help others to avoid the problems I had, because they almost drove me nuts.
Simply install the 32-bit version of the program, instead of the 64-bit version.
This is much safer than installing packages that are not intended for the distribution at hand.
I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04.
Google Earth used to employ ia32-libs
under 64-bit Ubuntu 12.04.
Quoting webupd8.org:
The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]
The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.
The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.
sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386
Because your script runs BEFORE the label exists on the page (in the DOM). Either put the script after the label, or wait until the document has fully loaded (use an OnLoad function, such as the jQuery ready()
or http://www.webreference.com/programming/javascript/onloads/)
This won't work:
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
<label id="lbltipAddedComment">test</label>
This will work:
<label id="lbltipAddedComment">test</label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
This example (jsfiddle link) maintains the order (script first, then label) and uses an onLoad:
<label id="lbltipAddedComment">test</label>
<script>
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
});
</script>
Or you can declare a struct type, that contains a character arry(1 string), them create an array of the structs and thus a multi-element array
typedef struct name
{
char name[100]; // 100 character array
}name;
main()
{
name yourString[10]; // 10 strings
printf("Enter something\n:);
scanf("%s",yourString[0].name);
scanf("%s",yourString[1].name);
// maybe put a for loop and a few print ststements to simplify code
// this is just for example
}
One of the advantages of this over any other method is that this allows you to scan directly into the string without having to use strcpy
;
My SQL teacher said that if you specify both a DEFAULT
value and NOT NULL
or NULL
, DEFAULT
should always be expressed before NOT NULL
or NULL
.
Like this:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL
Just Set barButton.customView = UIView()
and see the Trick
You can set the title in action-bar using AndroidManifest.xml
. Add label to the activity
<activity
android:name=".YourActivity"
android:label="Your Title" />
I prefer this way so I don't need to remember any rare parameters.
git merge branch_name
It will then say your branch is ahead by "#
" commits, you can now pop these commits off and put them into the working changes with the following:
git reset @~#
For example if after the merge it is 1 commit ahead, use:
git reset @~1
Note: On Windows, quotes are needed. (As Josh noted in comments) eg:
git reset "@~1"
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
I have done it like:
using (StreamReader sr = File.OpenText(jsonFilePath))
{
var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
}
also, you can do this with async call like: sr.ReadToEndAsync(). using Newtonsoft.Json as reference.
Hope, this helps.
The local names for a function are decided when the function is defined:
>>> x = 1
>>> def inc():
... x += 5
...
>>> inc.__code__.co_varnames
('x',)
In this case, x
exists in the local namespace. Execution of x += 5
requires a pre-existing value for x
(for integers, it's like x = x + 5
), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError
is named as such.
Compare the other version, where x
is not a local variable, so it can be resolved at the global scope instead:
>>> def incg():
... print(x)
...
>>> incg.__code__.co_varnames
()
Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
try {
query = URLEncoder.encode(query, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The su
command does not execute anything, it just raise your privileges.
Try adb shell su -c YOUR_COMMAND
.
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?>
on your site and look for the Server API
entry. This could say something like CGI/FastCGI
or Apache 2.0 Handler
.
If you also look at the command-line version of PHP -- thread safety does not matter.
Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
The CAST() function does not support the "official" data type "INT" in MySQL, it's not in the list of supported types. With MySQL, "SIGNED" (or "UNSIGNED") could be used instead:
CAST(columnName AS SIGNED)
However, this seems to be MySQL-specific (not standardized), so it may not work with other databases. At least this document (Second Informal Review Draft) ISO/IEC 9075:1992, Database does not list "SIGNED"/"UNSIGNED" in section 4.4 Numbers
.
But DECIMAL is both standardized and supported by MySQL, so the following should work for MySQL (tested) and other databases:
CAST(columnName AS DECIMAL(0))
According to the MySQL docs:
If the scale is 0, DECIMAL values contain no decimal point or fractional part.
Strings are a great example of uses of double pointers. The string itself is a pointer, so any time you need to point to a string, you'll need a double pointer.
Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value. Some examples of valid identifiers are:
AvgTemp ,count a4 ,$test ,this_is_ok
Invalid variable names include:
2count, high-temp, Not/ok
You have to convert the response to JSON using Gson.toJson(object)
.
For example:
return Response.status(Status.OK).entity(new Gson().toJson(Student)).build();
At first I used James Lawruk's method. This however changed all the widths of the td
's.
The solution for me was to use white-space: normal
on the columns (which was set to white-space: nowrap
). This way the text will always break. Using word-wrap: break-word
will ensure that everything will break when needed, even halfway through a word.
The CSS will look like this then:
td, th {
white-space: normal; /* Only needed when it's set differntly somewhere else */
word-wrap: break-word;
}
This might not always be the desirable solution, as word-wrap: break-word
might make your words in the table illegible. It will however keep your table the right width.
well check out the eclipse distro easyeclipse at EasyEclipse. it has Visual editor project already added as a plugin, so no hassles of eclipse version compatibility.Plus the eclipse help section has a tutorial on VE.
For GWT 2.x I just discovered that if you use
<set-property name="user.agent" value="ie6"/>
<extend-property values="ie8,gecko1_8" name="user.agent"/>
You can even specify more than one permutation.
Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -
select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;
You can keep track the position of the current selected element:
OnItemClickListener listViewOnItemClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
mSelectedItem = position;
mAdapter.notifyDataSetChanged();
}
};
And override the getView method of your adapter:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = View.inflate(context, R.layout.item_list, null);
if (position == mSelectedItem) {
// set your color
}
return view;
}
For me it did the trick.
well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.
just wrap your text around this class and see the magic :D
<p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
On your backEnd, you should add:
@RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
This might help:
from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date + timedelta(days=5)
print (date2)
Update - the answer below was written before C# 6 came along. In C# 6 you can write:
public class Foo
{
public string Bar { get; set; } = "bar";
}
You can also write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):
public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)
Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.
This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, and allowing for read-only automatically implemented properties to be initialized in a constructor body.
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
$scope.$watch('age + name', function () {
//called when name or age changed
});
Here function will get called when both age and name value get changed.
Here in LoicTheAztec's answer is shown how to retrieve this information.
Only for WooCommerce v3.0+
Basically, you can call
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
This will return an array to the billing order data, including billing and shipping properties. Explore it by var_dump-ing it.
Here's an example:
$order_billing_data = array(
"first_name" => $order_data['billing']['first_name'],
"last_name" => $order_data['billing']['last_name'],
"company" => $order_data['billing']['company'],
"address_1" => $order_data['billing']['address_1'],
"address_2" => $order_data['billing']['address_2'],
"city" => $order_data['billing']['city'],
"state" => $order_data['billing']['state'],
"postcode" => $order_data['billing']['postcode'],
"country" => $order_data['billing']['country'],
"email" => $order_data['billing']['email'],
"phone" => $order_data['billing']['phone'],
);
Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...
let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);
to prove it:
let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);
enjoy!
For negative integer value, SIGNED
is used and for non-negative integer value, UNSIGNED
is used. It always suggested to use UNSIGNED
for id as a PRIMARY KEY.
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
Here is how the standard keyboard behaves for each of these input types.
See this answer for more details.
You can put an image instead, and do it like this:
HTML:
<img src="/images/uploadButton.png" id="upfile1" style="cursor:pointer" />
<input type="file" id="file1" name="file1" style="display:none" />
JQuery:
$("#upfile1").click(function () {
$("#file1").trigger('click');
});
CAVEAT: In IE9 and IE10 if you trigger the onclick in a file input via javascript the form gets flagged as 'dangerous' and cannot be submmited with javascript, no sure if it can be submitted traditionaly.
you can use this for example
$array = json_decode($string,true)
but validate the Json before. You can validate from http://jsonviewer.stack.hu/
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
You can be more precise with CSS background-origin:
background-origin: content-box;
This will make image respect the padding of the box.
Try selecting send and download
instead of send
when you make the request. (the blue button)
https://www.getpostman.com/docs/responses
"For binary response types, you should select Send and download
which will let you save the response to your hard disk. You can then view it using the appropriate viewer."
I faced the same issue and successfully solved it. My use-case is this.
"Post JSON data to the server and receive an excel file. That excel file is created by the server and returned as a response to the client. Download that response as a file with custom name in browser"
$("#my-button").on("click", function(){
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
The above snippet is just doing following
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type. You can use this technique to download any kind of files.
For those who came here looking for "how to get All input of POST" only
class Illuminate\Http\Request
extends from Symfony\Component\HttpFoundation\Request
which has two class variables that store request parameters.
public $query
- for GET parameters
public $request
- for POST parameters
Usage: To get a post data only
$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter
Source here
EDIT
For Laravel >= 5.5, you can simply call $request->post()
or $request->post('my_param')
which internally calls $request->request->all()
or $request->request->get('my_param')
respectively.
Here and easy Example.
<!-- Navigation bar-->
<nav class="navbar navbar-toggleable-md bg-info navbar-inverse">
<div class="container">
<button class="navbar-toggler" data-toggle="collapse" data-target="#mainMenu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainMenu">
<div class="navbar-nav ml-auto " style="width:100%">
<a class="nav-item nav-link active" href="#">Home</a>
<a class="nav-item nav-link" href="#">About</a>
<a class="nav-item nav-link" href="#">Training</a>
<a class="nav-item nav-link" href="#">Contact</a>
</div>
</div>
</div>
</nav>
I totally agree with the solution provided, but I think a little clarification is important I think, might be necessary.
For each process (read also: vshost.exe, yourWinformApplication.exe.svchost, or the name of your application.exe) that will need to add a DWORD with the value provided, in my case I leave 9000 (in decimal) in application name and running smoothly and error-free script.
the most common mistake is to believe that it is necessary to add "contoso.exe" AS IS and think it all work!
For my case, I restarted the server and it worked.
This is my function:
$rootScope.$emit('setTitle', newVal.full_name);
$rootScope.$on('setTitle', function(event, title) {
if (scope.item)
scope.item.name = title;
else
scope.item = {name: title};
});
It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
To improve James' excellent answer:
It's better to put BINARY
in front of the constant instead:
SELECT * FROM `table` WHERE `column` = BINARY 'value'
Putting BINARY
in front of column
will prevent the use of any index on that column.
Try like this
ImageButton imagetrans=(ImageButton)findViewById(R.id.ImagevieID);
imagetrans.setBackgroundColor(Color.TRANSPARENT);
OR
include this in your .xml file in res/layout
android:background="@android:color/transparent
Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.
To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.
With that said, it really isn't too hard to generate PDFs. Just read the spec.
Simple async request:
function get(url, callback) {
var getRequest = new XMLHttpRequest();
getRequest.open("get", url, true);
getRequest.addEventListener("readystatechange", function() {
if (getRequest.readyState === 4 && getRequest.status === 200) {
callback(getRequest.responseText);
}
});
getRequest.send();
}
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
you can define an extension method and use it later.
String.prototype.contains = function(it)
{
return this.indexOf(it) != -1;
};
so that you can use in your page anywhere like:
var str="hello how are you";
str.contains("are");
which returns true.
Refer below post for more extension helper methods. Javascript helper methods
There is an article on getting to the built-in Windows .ZIP file handling with VBscript here:
https://www.aspfree.com/c/a/Windows-Scripting/Compressed-Folders-in-WSH/
(The last code blurb deals with extraction)
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
sqldump to a text file, find/replace, re-import the sqldump.
Dump the database to a text file
mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql
Restore the database after you have made changes to it.
mysql -u root -p[root_password] [database_name] < dumpfilename.sql
This worked perfectly for me (simple text replace):
Go to search -> file
Containing text: old pakage name
File name pattern: *
Scope: workspace
Press Replace
Replace: new package name
Now your project is full of errors.
Click your package in project explorer and press F2 (rename).
Fill in the new package name and check all checkmarks.
Press Preview.
Click OK.
Wait for Eclipse to refresh. If there are still errors, clean all projects in the workspace:
Project -> Clean
I believe you're looking for...
import config.logging_settings # @UnusedImport
Note the double space before the comment to avoid hitting other formatting warnings.
Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport
).
You are correct that the GPL is more restrictive than the MIT license.
You cannot include GPL code in a MIT licensed product. If you distribute a combined work that combines GPL and MIT code (except in some particular situations, e.g. 'mere aggregation'), that distribution must be compliant with the GPL.
You can include MIT licensed code in a GPL product. The whole combined work must be distributed in a way compliant with the GPL. If you have made changes to the MIT parts of the code, you would be required to publish the source for those changes if you distribute an application that contains GPL and MIT code.
If you are the copyright owner of the GPL code, you can of course choose to release that code under the MIT license instead - in that case it's your code and you can publish it under as many licenses as you want.
Late, but to show an easy solution using promises
after their introduction in ES6, it handles asynchronous calls a lot easier:
You set the asynchronous code in a new promise:
var asyncFunct = new Promise(function(resolve, reject) {
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
resolve();
});
});
Note to set resolve()
when async call finishes.
Then you add the code that you want to run after async call finishes inside .then()
of the promise:
asyncFunct.then((result) => {
console.log("Exit");
});
Here is a snippet of it:
$('#link').click(function () {_x000D_
console.log("Enter");_x000D_
var asyncFunct = new Promise(function(resolve, reject) {_x000D_
$('#link').animate({ width: 200 }, 2000, function() {_x000D_
console.log("finished"); _x000D_
resolve();_x000D_
}); _x000D_
});_x000D_
asyncFunct.then((result) => {_x000D_
console.log("Exit"); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="link">Link</a>_x000D_
<span>Moving</span>
_x000D_
or JSFiddle
exponent
is a 1D array. This means that exponent[0]
is a scalar, and exponent[0][i]
is trying to access it as if it were an array.
Did you mean to say:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
or even
L = diag(exponent)
?
I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was
import time
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,1024)
time.sleep(2)
cap.set(15, -8.0)
the time you have to use can be different
This is how you should initialize the NSString
:
Swift 2.X or older
let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)
Swift 3 or newer:
let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)
This doc explains the syntax.
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
class='col-xs-3'
(for example).class="btn-block"
to your buttons. This will provide permanent spacing.
As others mentioned in Bootstrap 3, you can use nest/embed techniques.
However it is becoming more obvious to use pretty awesome feature from Bootstrap 4 now. you simple have the option to use the col-{breakpoint}-auto
classes (e.g. col-md-auto
) to make columns size itself automatically based on the natural width of its content. check this for example
Tested it and it worked for me. The element finding me change as per the document structure that you have.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form method="post" id = "formId" action="action.php" onsubmit="return false;">
<table>
<tr>
<td>
<label class="standard_text">E-mail</label>
</td>
<td><input class="textarea" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><input class="textarea" name="name" id="name" placeholder="E-mail"> </label></td>
<td><input class="textarea" name="myname" id="myname" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
</body>
</html>
var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('formId');
inputs = form.getElementsByTagName("input");
for(var i = 0 ; i < inputs.length;i++) {
inputs[i].addEventListener('keydown', function(e){
if(e.keyCode == 13) {
var currentIndex = findElement(e.target)
if(currentIndex > -1 && currentIndex < inputs.length) {
inputs[currentIndex+1].focus();
}
}
});
}
});
function findElement(element) {
var index = -1;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i] == element) {
return i;
}
}
return index;
}
The below steps apply to Windows.
Run below in an administrative cmd
mongod --remove
This will remove the existing MongoDB service (if any).
mongod --dbpath "C:\data\db" --logpath "C:\Program Files\MongoDB\Server\3.4\bin\mongod.log" --install --serviceName "MongoDB"
Make sure that C:\data\db
folder exists
Open services with:
services.msc
Find MongoDB -> Right click -> Start
The truth value of an empty list is False
whereas for a non-empty list it is True
.
BreedId
in the Dog
table is obviously a foreign key to the corresponding row in the Breed
table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable<Dog>
, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):
public IEnumerable<Dog> GetDogs()
{
using (var db = new DogDataContext(ConnectString))
{
db.LoadOptions.LoadWith<Dog>(i => i.Breed);
return db.Dogs.ToArray();
}
}
It is then trivial to access the breed for each dog:
foreach (var dog in GetDogs())
{
Console.WriteLine("Dog's Name: {0}", dog.Name);
Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);
}
Try replaceAll("\\\\", "")
or replaceAll("\\\\/", "/")
.
The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \
in row.
Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.
I had the same probleme but the response made by Mike A helped me to figure it out: I had a my certificate, an intermediate certificate (Gandi) , an other intermediate (UserTrustRSA) and finally the RootCA certificate (AddTrust).
So first i made a chain file with Gandi+UserTrustRSA+AddTrust and specified it with SSLCertificateChainFile. But it didn't worked.
So i tried MikeA answer by just putting AddTruct cert in a file and specified it with SSLCACertificateFile and removing SSLCertificateChainFile.But it didn't worked.
So finnaly i made a chain file with only Gandi+UserTrustRSA specified by SSLCertificateChainFile and the other file with only the RootCA specified by SSLCACertificateFile and it worked.
# Server Certificate:
SSLCertificateFile /etc/ssl/apache/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/ssl/apache/myserver.key
# Server Certificate Chain:
SSLCertificateChainFile /etc/ssl/apache/Gandi+UserTrustRSA.pem
# Certificate Authority (CA):
SSLCACertificateFile /etc/ssl/apache/AddTrust.pem
Seems logical when you read but hope it helps.
var myVar = $("#start").find('myClass').val();
needs to be
var myVar = $("#start").find('.myClass').val();
Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>
.
If you are using HUE this is fairly simple as well. Simply go to the Hive editor in HUE, execute your hive query, then save the result file locally as XLS or CSV, or you can save the result file to HDFS.
Access the BIOS setting and turn on the virtualization feature. Mine was together with options like cpu fan speeds and stuffs. Then make sure that Hyper-V is turned off in the windows features ON/OFF. Then reinstall the intel HAXM, this should fix this issue.
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME
, and a VARCHAR
to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York
is the highest data fidelity.
A timezone abbreviation such as PST
is the next highest fidelity.
A time offset such as -2:00
is the smallest amount of data in this regard.
Some key points:
TIMESTAMP
because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.INT
field, because there are half-hour and quarter-hour offsets.If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME
has a problem:
'2009-11-10 11:00:00 -0500'
is before '2009-11-10 10:00:00 -0700'
in terms of "instant in time", but they would sort the other way when inserted into a DATETIME
.
You can do your own conversion to UTC. In the above example, you would then have '2009-11-10 16:00:00'
and '2009-11-10 17:00:00'
respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X)
where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)An advantage to the 3-column approach is that it's explicit: with a single DATETIME
column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
America/Juneau
, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.-0700
, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700
during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00
or 13:00
for the user?These things are important to consider when your application has time, dates, or scheduling as core function.
References:
Steps to manually configure DNS:
You can access Network and Sharing center by right clicking on the Network icon on the taskbar.
Now choose adapter settings from the side menu.
This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.
In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.
Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.
Select ‘use the following DNS address’ option. Now fill the following fields as given here.
Preferred DNS server: 208.67.222.222
Alternate DNS server : 208.67.220.220
This is an available Open DNS address. You may also use google DNS server addresses.
After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.
You have to add this DNS server address in the router configuration also (by referring the router manual for more information).
Refer : for above method & alternative
If none of this works, then open command prompt(Run as Administrator) and run these:
ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit
Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).
Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue
public static void main(String[] args) {
int hex = 0x123456;
int r = (hex & 0xFF0000) >> 16;
int g = (hex & 0xFF00) >> 8;
int b = (hex & 0xFF);
}
Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose
.feature_desc {
display: block;
}
.feature_desc:before {
content: "";
display: block;
}
might give you want you want to achieve without the <br/>
element. Though it would help to see your CSS applied to these elements.
NOTE. The example above doesn't work in IE7 though.
if(str.matches(".*\\d.*")){
// contains a number
} else{
// does not contain a number
}
Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.
String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";
System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));
String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
System.out.println("'"+strWithNumber+"' contains digit");
} else{
System.out.println("'"+strWithNumber+"' does not contain a digit");
}
String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}
Output
'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit
import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg
Try this:
Dim regDate as Date = Date.Now()
Dim strDate as String = regDate.ToString("ddMMMyyyy")
strDate will look like so: 07Feb2012
This worked for me, in my case I had a button with a data-id attribute:
$("a").data("item-id");
The server certificate is invalid, either because it is signed by an invalid CA (internal CA, self signed,...), doesn't match the server's name or because it is expired.
Either way, you need to find how to tell to the Python library that you are using that it must not stop at an invalid certificate if you really want to download files from this server.
Here is a one-liner for ignoring the tar exit status if it is 1. There is no need to set +e
as in sandeep's script. If the tar exit status is 0 or 1, this one-liner will return with exit status 0. Otherwise it will return with exit status 1. This is different from sandeep's script where the original exit status value is preserved if it is different from 1.
tar -czf sample.tar.gz dir1 dir2 || [[ $? -eq 1 ]]
This method is recommended
<link rel="icon"
type="image/png"
href="/somewhere/myicon.png" />
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".
On Ubuntu you can simply add the most recent Apt repository and then run:
sudo apt-get install postgresql-client-11
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
This error occurs when the syntax of connection string is not valid.
You can use the connection string as
'jdbc:derby:MyDbTest;create=true'
or
you can use the following command in the command prompt, the command below creates a new database called MyDbTest
succesfully:
connect 'jdbc:derby:MyDbTest;create=true';
string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")
Little correction at Line 3
HTMLParser.HTMLParser.__init__(self)
it should be
HTMLParser.__init__(self)
The following worked for me though
import urllib2
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.recording = 0
self.data = []
def handle_starttag(self, tag, attrs):
if tag == 'required_tag':
for name, value in attrs:
if name == 'somename' and value == 'somevale':
print name, value
print "Encountered the beginning of a %s tag" % tag
self.recording = 1
def handle_endtag(self, tag):
if tag == 'required_tag':
self.recording -=1
print "Encountered the end of a %s tag" % tag
def handle_data(self, data):
if self.recording:
self.data.append(data)
p = MyHTMLParser()
f = urllib2.urlopen('http://www.someurl.com')
html = f.read()
p.feed(html)
print p.data
p.close()
`
The reason DISTINCT
and GROUP BY
work on entire rows is that your query returns entire rows.
To help you understand: Try to write out by hand what the query should return and you will see that it is ambiguous what to put in the non-duplicated columns.
If you literally don't care what is in the other columns, don't return them. Returning a random row for each e-mail address seems a little useless to me.
Just found out a great plugin for this:
http://flexslider.woothemes.com/
Regards
Just wanted to add this little snippet which works beautifully for me.
INSERT INTO your_target_table SELECT * FROM your_rescource_table WHERE id = 18;
And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier
In java-8 you can use streams:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
The sum is 150.
It's in the package java.util.stream
import java.util.stream.*;
Wouldn't you just do:
srand(time(NULL));
int r = ( rand() % 6 ) + 1;
%
is the modulus operator. Essentially it will just divide by 6 and return the remainder... from 0 - 5
Don't call write.close()
in writeToFile()
.
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string extension = ".log";
filePath += @"\Error Log\" + extension;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
beginupd.getTime()
will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date
object
This will give you the option to:
Call CreateWorksheet("New", False, False, False)
Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
activeSheetNumber = Sheets(ActiveSheet.Name).Index
If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
If (preserveOldSheet) Then
MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
Exit Sub
End If
Application.DisplayAlerts = False
Worksheets(sheetName).Delete
End If
If (isLastSheet) Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
Else 'Place sheet after the active sheet.
Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
End If
If (selectActiveSheet) Then
Sheets(activeSheetNumber).Activate
End If
End Sub
transform: scale();
will make original element preserve its size.
I found the best option is to use vw
.
It's working like a charm:
https://jsfiddle.net/tomekmularczyk/6ebv9Lxw/1/
#div1,_x000D_
#div2,_x000D_
#div3 {_x000D_
background:url('//www.google.pl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png') no-repeat;_x000D_
background-size: 50vw; _x000D_
border: 1px solid black;_x000D_
margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
#div1 {_x000D_
background-position: 0 0;_x000D_
width: 12.5vw;_x000D_
height: 13vw;_x000D_
}_x000D_
#div2 {_x000D_
background-position: -13vw -4vw;_x000D_
width: 17.5vw;_x000D_
height: 9vw;_x000D_
transform: scale(1.8);_x000D_
}_x000D_
#div3 {_x000D_
background-position: -30.5vw 0;_x000D_
width: 19.5vw;_x000D_
height: 17vw;_x000D_
}
_x000D_
<div id="div1">_x000D_
</div>_x000D_
<div id="div2">_x000D_
</div>_x000D_
<div id="div3">_x000D_
</div>
_x000D_
Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init
part on the ng-form
element and the use of furryName
. furryName
becomes the variable name that contains the variable value for the input
's name
attribute.
<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
<!-- animal is furry toggle buttons -->
<input id="furryRadio{{$index}}"
type="radio"
name="{{furryName}}"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolTrue"
required
>
<label for="furryRadio{{$index}}">Furry</label>
<input id="hairlessRadio{{$index}}"
name="{{furryName}}"
type="radio"
ng-model="animal.isFurry"
ng-value="radioBoolValues.boolFalse"
required
>
<label for="hairlessRadio{{$index}}">Hairless</label>
<div ng-messages="animalsForm[furryName].$error"
class="form-errors"
ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
<div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
</div>
</ng-form>
</ion-item>
You can recursively revert like this:
svn revert --recursive .
There is no way (without writing a creative script) to remove things that aren't under source control. I think the closest you could do is to iterate over all of the files, use then grep the result of svn list
, and if the grep fails, then delete it.
EDIT: The solution for the creative script is here: Automatically remove Subversion unversioned files
So you could create a script that combines a revert
with whichever answer in the linked question suits you best.
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
It is worth noting that @Marius's second answer could be used as pure Javascript solution.
document.getElementById('elementId').tagName
You have to write this code instead of return View(); :
return RedirectToAction("ActionName", "ControllerName");
You need to do the subselect based on a column name, not *
.
For example, if you had an id
field common to both tables, you could do:
SELECT * FROM Table1 WHERE id NOT IN (SELECT id FROM Table2)
Refer to the MySQL subquery syntax for more examples.
change to
fscanf(myFile, "%1d", &numberArray[i]);
The NavigationBar height varies for some devices, but as well for some orientations. First you have to check if the device has a navbar, then if the device is a tablet or a not-tablet (phone) and finally you have to look at the orientation of the device in order to get the correct height.
public int getNavBarHeight(Context c) {
int result = 0;
boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if(!hasMenuKey && !hasBackKey) {
//The device has a navigation bar
Resources resources = c.getResources();
int orientation = resources.getConfiguration().orientation;
int resourceId;
if (isTablet(c)){
resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
} else {
resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");
}
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
}
return result;
}
private boolean isTablet(Context c) {
return (c.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
The following appears to work:
table td {
vertical-align: middle !important;
}
You can apply to a specific table as well like so:
#some_table td {
vertical-align: middle !important;
}
Just in case you can't / don't use CURLOPT_HEADERFUNCTION
or other solutions;
$nextCheck = function($body) {
return ($body && strpos($body, 'HTTP/') === 0);
};
[$headers, $body] = explode("\r\n\r\n", $result, 2);
if ($nextCheck($body)) {
do {
[$headers, $body] = explode("\r\n\r\n", $body, 2);
} while ($nextCheck($body));
}
We use {SmartAssembly} for .NET protection of an enterprise level distributed application, and it has worked great for us.
That doesn't work because distToPoint
is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p)
. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p)
.
You can convert that time in Unix timestamp by using
select UNIX_TIMESTAMP('2013-11-26 01:24:34')
then convert it in the readable format in whatever format you need
select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");
For in detail you can visit link
(L[n:n+1] or [somedefault])[0]
The most efficient way is by ID.
$("#foo").val(); //by id
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
https://developers.google.com/speed/docs/best-practices/rendering?hl=it#UseEfficientCSSSelectors
You could try something like this:
#!/bin/bash
all_but()
{
target="$(git rev-parse $1)"
echo "$target --not"
git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
while read entry
do
eval "$entry"
test "$ref" != "$target" && echo "$ref"
done
}
git log $(all_but $1)
Or, borrowing from the recipe in the Git User's Manual:
#!/bin/bash
git log $1 --not $( git show-ref --heads | cut -d' ' -f2 | grep -v "^$1" )
if you are using docker you have to do the following steps:
copy the file from hdfs to namenode (hadoop fs -get output/part-r-00000 /out_text). "/out_text" will be stored on the namenode.
copy the file from namenode to local disk by (docker cp namenode:/out_text output.txt)
output.txt will be there on your current working directory
this is works good https://gist.github.com/pablosalgadom/4d75f30517edc6230a67 for root user should edit
$ /etc/profile
but if you non root should put the generate code in the following
$ ~/.bash_profile
$ ~/.bash_login
$ ~/.profile
Using jQuery
$('#note textarea');
or just
$('#textid');
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Years passed and nowadays you can do it natively
(new TextEncoder().encode('foo')).length
Note that it's not supported by IE (you may use a polyfill for that).
You could consider using CDYNE's PAV-I API that validates international addresses. international-address-verification They cover over 240 countries, so it should cover all of the countries that you are looking to validate for.
You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.
More reference for this : listview with checkbox in android
Source code for model
public class Model {
private boolean isSelected;
private String animal;
public String getAnimal() {
return animal;
}
public void setAnimal(String animal) {
this.animal = animal;
}
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
put this in your custom adapter
holder.checkBox.setTag(R.integer.btnplusview, convertView);
holder.checkBox.setTag( position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
TextView tv = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
if(modelArrayList.get(pos).getSelected()){
modelArrayList.get(pos).setSelected(false);
}else {
modelArrayList.get(pos).setSelected(true);
}
}
});
whole code for customAdapter is
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Model> modelArrayList;
public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getCount() {
return modelArrayList.size();
}
@Override
public Object getItem(int position) {
return modelArrayList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.checkBox.setText("Checkbox "+position);
holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
holder.checkBox.setTag(R.integer.btnplusview, convertView);
holder.checkBox.setTag( position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
TextView tv = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
if(modelArrayList.get(pos).getSelected()){
modelArrayList.get(pos).setSelected(false);
}else {
modelArrayList.get(pos).setSelected(true);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView tvAnimal;
}
}
The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:
export class FilterPipe implements PipeTransform {
transform(items: any[], filterBy: string): any {
return items.filter(item => item.id.indexOf(filterBy) !== -1);
}
}
And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:
export class ProductFilterPipe implements PipeTransform {
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
}
And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
Using a ListTile
also works as well, since a list fills the entire width:
ListTile(
title: new RaisedButton(...),
),
Did you even look at the break
keyword? O.o
This is just pseudo-code, but you should be able to see what I mean:
<?php
for(...) {
while(...) {
foreach(...) {
break 3;
}
}
}
If you think about break
being a function like break()
, then it's parameter would be the number of loops to break out of. As we are in the third loop in the code here, we can break out of all three.
Manual: http://php.net/break
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
_x000D_
[edit]
I tried to rewrite your query, but even yours will work once you associate aliases to the aggregate columns in the query that defines 'd'.
I think you are looking for the following:
First one:
select
c.duration,
c.totalbookings,
d.bkdqty
from
(select
month(bookingdate) as duration,
count(*) as totalbookings
from
entbookings
group by month(bookingdate)
) AS c
inner join
(SELECT
duration,
sum(totalitems) 'bkdqty'
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
) AS d
on c.duration = d.duration
Second one:
select
c.duration,
c.totalbookings,
d.bkdqty
from
(select
month(bookingdate) as duration,
count(*) as totalbookings
from
entbookings
group by month(bookingdate)
) AS c
inner join
(select
month(clothdeliverydate) 'clothdeliverydatemonth',
SUM(CONVERT(INT, deliveredqty)) 'bkdqty'
FROM
barcodetable
where
month(clothdeliverydate) is not null
group by month(clothdeliverydate)
) AS d
on c.duration = d.duration
The error is coming as your query is getting formed as
SELECT * FROM Employ where number = parseInt(val);
I dont know which DB you are using but no DB will understand parseInt
.
What you can do is use a variable say temp and store the value of parseInt(val)
in temp variable and make the query as
SELECT * FROM Employ where number = temp;
I have been banging my head against the wall with a similar problem. The only thing that helped is following the steps in this post.
Extending Bhesh Gurung's answer for assigning values, you can add explicit method to set value
public ExitCode setValue( int value){
// A(104), B(203);
switch(value){
case 104: return ExitCode.A;
case 203: return ExitCode.B;
default:
return ExitCode.Unknown //Keep an default or error enum handy
}
}
From calling application
int i = 104;
ExitCode serverExitCode = ExitCode.setValue(i);
//You've valid enum from now
[Unable to comment to his answer, hence posting it separately]
you can just use post
to post your json.
values := map[string]string{"username": username, "password": password}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))
select * from table where id not in (select id from table limit 10)
where id
be the key in your table.
TRIM
all SPACE
's TAB
's and ENTER
's:
DECLARE @Str VARCHAR(MAX) = '
[ Foo ]
'
DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
CHAR(13) + CHAR(10) -- ENTER
+ CHAR(9) -- TAB
+ ' ' -- SPACE
;WITH Split(Chr, Pos) AS (
SELECT
SUBSTRING(@Str, 1, 1) AS Chr
, 1 AS Pos
UNION ALL
SELECT
SUBSTRING(@Str, Pos, 1) AS Chr
, Pos + 1 AS Pos
FROM Split
WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
Pos >= (
SELECT MIN(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
AND Pos <= (
SELECT MAX(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
SELECT '"' + @NewStr + '"'
CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
DECLARE @NewStr VARCHAR(MAX) = NULL
IF (@Str IS NOT NULL) BEGIN
SET @NewStr = ''
DECLARE @WhiteChars VARCHAR(4) =
CHAR(13) + CHAR(10) -- ENTER
+ CHAR(9) -- TAB
+ ' ' -- SPACE
IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN
;WITH Split(Chr, Pos) AS (
SELECT
SUBSTRING(@Str, 1, 1) AS Chr
, 1 AS Pos
UNION ALL
SELECT
SUBSTRING(@Str, Pos, 1) AS Chr
, Pos + 1 AS Pos
FROM Split
WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
Pos >= (
SELECT MIN(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
AND Pos <= (
SELECT MAX(Pos)
FROM Split
WHERE CHARINDEX(Chr, @WhiteChars) = 0
)
END
END
RETURN @NewStr
END
-- Test
DECLARE @Str VARCHAR(MAX) = '
[ Foo ]
'
SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim(' ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'
Result
+-------+----------------+
| Test | Result |
+-------+----------------+
| EMPTY | "" |
| EMTPY | "" |
| NULL | NULL |
| Str | "[ Foo ]" |
+-------+----------------+
You declare
int countlines(char *filename)
to take a char *
argument.
You call it like this
countlines(fp)
passing in a FILE *.
That is why you get that compile error.
You probably should change that second line to
countlines("Test.txt")
since you open the file in countlines
Your current code is attempting to open the file in two different places.
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
Just simply use this because I wanted to use the "useRef" conditions were not an option for me. You can use this suppose when you want to use useRef hook and press the button.
<Button
ref={uploadbtn}
buttonStyle={{ width: 0, height: 0, opacity: 0, display: "none" }}
onPress={pickImage}
/>
I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.
Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.
Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.
This can be another way to do it and validate nulls
DataControlField dataControlField = UsersGrid.Columns.Cast<DataControlField>().SingleOrDefault(x => x.HeaderText == "Email");
if (dataControlField != null)
dataControlField.Visible = false;
Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[]
.
To access arbitrary elements in a vector vec
, you can use the following:
vec.begin() // 1st
vec.begin()+1 // 2nd
// ...
vec.begin()+(i-1) // ith
// ...
vec.begin()+(vec.size()-1) // last
The following is an example of a typical access pattern (earlier versions of C++):
int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
The advantage of using iterator is that you can apply the same pattern with other containers:
sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
sum += *it;
}
For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).
Another option using std::for_each
and lambdas:
sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });
Since C++11 you can use auto
to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):
sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
And, in addition, there is a simpler for-each variant:
sum = 0;
for (auto value : vec) {
sum += value;
}
And finally there is also std::accumulate
where you have to be careful whether you are adding integer or floating point numbers.
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
As you described, you will need to use a different method based on different versions of iOS. If your team is using both Xcode 5 (which doesn't know about any iOS 8 selectors) and Xcode 6, then you will need to use conditional compiling as follows:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// use registerUserNotificationSettings
} else {
// use registerForRemoteNotificationTypes:
}
#else
// use registerForRemoteNotificationTypes:
#endif
If you are only using Xcode 6, you can stick with just this:
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// use registerUserNotificationSettings
} else {
// use registerForRemoteNotificationTypes:
}
The reason is here is that the way you get notification permissions has changed in iOS 8. A UserNotification
is a message shown to the user, whether from remote or from local. You need to get permission to show one. This is described in the WWDC 2014 video "What's New in iOS Notifications"
To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.
Is there any downside of leveraging mousedown
listener to modify the href
attribute with a new URL location and then let the browser figures out where it should redirect to?
It's working fine so far for me. Would like to know what the limitations are with this approach?
// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';
a.onmousedown = () => {
a.href = '/lol';
};
document.body.appendChild(a);
}
You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2())
.
SELECT b FROM foo;
-- (BLOB)
SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000
This is handy because you this is the same format used for inserting into BLOB columns:
CREATE GLOBAL TEMPORARY TABLE foo (
b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');
DESC foo;
-- Name Null Type
-- ---- ---- ----
-- B BLOB
However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR
for a more complicated approach that will allow you to see substrings of the BLOB.
// if you need to check if all items' MyProperty doesn't have null
if (list.All(x => x.MyProperty != null))
// do something
// or if you need to check if at least one items' property has doesn't have null
if (list.Any(x => x.MyProperty != null))
// do something
But you always have to check for null
Try
$(document).ready(
instead of
$('document').ready(
or you can use a shorthand form
$(function(){
});
The correct syntax is to tell Rsync to use a custom SSH command (adding -p 2222), which creates a secure tunnel to remote side using SSH, then connects via localhost:873
rsync -rvz --progress --remove-sent-files -e "ssh -p 2222" ./dir user@host/path
Rsync runs as a daemon on TCP port 873, which is not secure.
From Rsync man:
Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
Which misleads people to try this:
rsync -rvz --progress --remove-sent-files ./dir user@host:2222/path
However, that is instructing it to connect to Rsync daemon on port 2222, which is not there.
Installing freetype:
sudo apt update && sudo apt install freetype2-demos
It's because you have a recursive function inside of rotate. It's calling itself again:
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
Take that out and it won't keep on running recursively.
I would also suggest just using this function instead:
function rotate($el, degrees) {
$el.css({
'-webkit-transform' : 'rotate('+degrees+'deg)',
'-moz-transform' : 'rotate('+degrees+'deg)',
'-ms-transform' : 'rotate('+degrees+'deg)',
'-o-transform' : 'rotate('+degrees+'deg)',
'transform' : 'rotate('+degrees+'deg)',
'zoom' : 1
});
}
It's much cleaner and will work for the most amount of browsers.
Under "Settings -> Editor -> General -> Auto Import"
there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.
You may also need to enable the World Wide Web Service inbound firewall rule.
On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules
Find World Wide Web Services (HTTP Traffic-In)
in the list and select to enable the rule. Change is pretty much immediate.
We are using display: grid;
and its properties.
#box {_x000D_
display: grid;_x000D_
width: 100px;_x000D_
grid-gap: 5px;_x000D_
/* Space between items */_x000D_
grid-template-columns: 1fr 1fr 1fr 1fr;_x000D_
/* Decide the number of columns and size */_x000D_
}_x000D_
_x000D_
.item {_x000D_
background: gray;_x000D_
width: 100%;_x000D_
/* width is not necessary only added this to understand that width works as 100% to the grid template allocated space **DEFAULT WIDTH WILL BE 100%** */_x000D_
height: 50px;_x000D_
}
_x000D_
<div id='box'>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
</div>
_x000D_
The Downside of this method is in Mobile Opera Mini will not be supported and in PC this works only after IE10.
Note for complete browser compatability including IE11 please use Autoprefixer
Don't think of it as an old solution, it's still one of the best if you only want single row of elements and it will work with all the browsers.
This method is used by CSS sibling combination, so you can manipulate it many other ways also, but if your combination is wrong it may cause issues also.
.item+.item{
margin-left: 5px;
}
The below code will do the trick. In this method, there is no need to give margin: 0 -5px;
to the #box
wrapper.
A working sample for you:
#box {_x000D_
display: flex;_x000D_
width: 100px;_x000D_
}_x000D_
.item {_x000D_
background: gray;_x000D_
width: 22px;_x000D_
height: 50px;_x000D_
}_x000D_
.item+.item{_x000D_
margin-left: 5px;_x000D_
}
_x000D_
<div id='box'>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
<div class='item'></div>_x000D_
</div>
_x000D_
You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly
<div className="col-6">_x000D_
<a download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
</div>
_x000D_
another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
<img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
I was hitting the same issue. Added mysql service port number(3307), resolved the issue.
conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/?" + "user=root&password=password");
Background image is not supported in Outlook. You have to use an image and position it behind the text using position relative or absolute.
$('div#someDiv').css('height', '');
kue is the only message queue you would ever need
Why are you representing them as textareas? This is my favorite:
http://alexgorbatchev.com/wiki/SyntaxHighlighter
But if you are using a CMS, there's probably a better plugin. For example, wordpress has an evolved version:
http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/
Here's another extremely detailed walkthrough that also shows you the entire process, including what values to put in the connection dialogue after the JDBC driver is installed: http://rpbouman.blogspot.com/2007/01/oracle-sql-developer-11-supports-mysql.html
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
I had this same issue. You just need to go to your
C:\Python27\Scripts
and add it to environment variables. After path setting just run pip.exe file on C:\Python27\Scripts and then try pip in cmd. But if nothing happens try running all pip applications like pip2.7 and pip2.exe. And pip will work like a charm.
Add items:
arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Retrieve items:
productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;
Use TablePlus application: Right-Click on the table name from the right panel Choose Import... > From CSV Choose CSV file Review column matching and hit Import All done!
Base on Leo's answer, add
If you want max unit to Mega, change to $units = explode(' ', ' K M');
function formatUnit($value, $precision = 2) {
$units = explode(' ', ' K M G T P E Z Y');
if ($value < 0) {
return '-' . formatUnit(abs($value));
}
if ($value < 1) {
return $value . $units[0];
}
$power = min(
floor(log($value, 1024)),
count($units) - 1
);
return round($value / pow(1024, $power), $precision) . $units[$power];
}
Check this out. Just use float and get rid of relative.
#icons{float:left;}
Documented couple of design issues with this in a comment above. Short story, in Oracle, you need to limit the results manually when you have large tables and/or tables with same column names (and you don't want to explicit type them all out and rename them all). Easy solution is to figure out your breakpoint and limit that in your query. Or you could also do this in the inner query if you don't have the conflicting column names constraint. E.g.
WHERE m_api_log.created_date BETWEEN TO_DATE('10/23/2015 05:00', 'MM/DD/YYYY HH24:MI')
AND TO_DATE('10/30/2015 23:59', 'MM/DD/YYYY HH24:MI')
will cut down the results substantially. Then you can ORDER BY or even do the outer query to limit rows.
Also, I think TOAD has a feature to limit rows; but, not sure that does limiting within the actual query on Oracle. Not sure.
There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...
change: function (e) {
var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}
My solution for this problem is an extension method WithIndex()
,
Use it like
var list = new List<int> { 1, 2, 3, 4, 5, 6 };
var odd = list.WithIndex().Where(i => (i.Item & 1) == 1);
CollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index));
CollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item));
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
The formula for this is very simple, so try this expression,
int num = (int) rand() % (max - min) + min;
//Where rand() returns a random number between 0.0 and 1.0
Use:
$intValue = 1;
$string = sprintf('%d', $intValue);
Or it could be:
$string = (string)$intValue;
Or:
settype(&$intValue, 'string');
You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.
Based only on your style you would have:
<a href="home.com" id="logo"></a>
I'd also like to add that if using the three.js editor don't forget to set the background colour to clear as well in the index.html.
background-color:#00000000
File.Create
returns a FileStream
object that you can call Close()
on.
Another possibility: When you created the user, you may have accidentally been use
ing a database other than admin
, or other than the one you wanted. You need to set --authenticationDatabase
to the database that the user was actually created under.
mongodb
seems to put you in the test
database by default when you open the shell, so you'd need to write --authenticationDatabase test
rather than --authenticationDatabase admin
if you accidentally were use
ing test
when you ran db.createUser(...)
.
Assuming you have access to the machine that's running the mongodb instance, y could disable authorization in /etc/mongod.conf
(comment out authorization
which is nested under security), and then restart your server, and then run:
mongo
show users
And you might get something like this:
{
"_id" : "test.myusername",
"user" : "myusername",
"db" : "test",
"roles" : [
{
"role" : "dbOwner",
"db" : "mydatabasename"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Notice that the db
value equals test
. That's because when I created the user, I didn't first run use admin
or use desiredDatabaseName
. So you can delete the user with db.dropUser("myusername")
and then create another user under your desired database like so:
use desiredDatabaseName
db.createUser(...)
Hopefully that helps someone who was in my position as a noob with this stuff.
ANDROD IMPLEMENTATION A complete method to request data/string response from web service requesting authorization with username and password
public static String getData(String uri, String userName, String userPassword) {
BufferedReader reader = null;
byte[] loginBytes = (userName + ":" + userPassword).getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", loginBuilder.toString());
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null){
sb.append(line);
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In my case the Exception occurred because all google play service extensions are not with same version as follows
compile 'com.google.android.gms:play-services-plus:9.8.0'
compile 'com.google.android.gms:play-services-appinvite:9.8.0'
compile 'com.google.android.gms:play-services-analytics:8.3.0'
It worked when I changed this to
compile 'com.google.android.gms:play-services-plus:9.8.0'
compile 'com.google.android.gms:play-services-appinvite:9.8.0'
compile 'com.google.android.gms:play-services-analytics:9.8.0'