As seen in this Angular example, there is a way to disable a button until the whole form is valid:
<button type="submit" [disabled]="!ngForm.valid">Submit</button>
Unicode string literals (string literals prefixed by u
) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.
If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'
. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n
to your string literal. So when you print the 'hello\nworld'
string, the words will be printed on separate lines. That's very handy!
On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:
'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'
In such situations you can just prefix the string literal with the r
character like this: r'hello\nworld'
and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.
Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.
From the lexical definition of a string literal:
string ::= "'" stringitem* "'"
stringitem ::= stringchar | escapeseq
stringchar ::= <any source character except "\" or newline or the quote>
escapeseq ::= "\" <any source character>
It is clear that string literals (raw or not) containing a bare quote character: 'hello'world'
or ending with a backslash: 'hello world\'
are not valid.
Static classes in languages like C# exist because there are no other top-level constructs to group data and functions. In JavaScript, however, they do and so it is much more natural to just declare an object like you did. To more closely mimick the class syntax, you can declare methods like so:
const myStaticClass = {
property: 10,
method() {
}
}
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
In Xcode 7 you can have multiple storyBoards. It will be better if you can keep the Login flow in a separate storyboard.
This can be done using SELECT VIEWCONTROLLER > Editor > Refactor to Storyboard
And here is the Swift version for setting a view as the RootViewContoller-
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = newRootViewController
let rootViewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController")
array_values()
will do pretty much what you want:
$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar
Readonly is an attribute as defined in html, so treat it like one.
You need to have something like readonly="readonly" in the object you are working with if you want it not to be editable. And if you want it to be editable again you won't have something like readonly='' (this is not standard if I understood correctly). You really need to remove the attribute as a whole.
As such, while using jquery adding it and removing it is what makes sense.
Set something readonly:
$("#someId").attr('readonly', 'readonly');
Remove readonly:
$("#someId").removeAttr('readonly');
This was the only alternative that really worked for me. Hope it helps!
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
strace -tfp PID will monitor the PID process's system calls, thus we can debug/monitor our process/program status.
I just made marc_s "presentation ready":
SELECT
c.name 'Column Name',
t.name 'Data type',
IIF(t.name = 'nvarchar', c.max_length / 2, c.max_length) 'Max Length',
c.precision 'Precision',
c.scale 'Scale',
IIF(c.is_nullable = 0, 'No', 'Yes') 'Nullable',
IIF(ISNULL(i.is_primary_key, 0) = 0, 'No', 'Yes') 'Primary Key'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('YourTableName')
The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global
flag needs to be provided.
In order to uninstall the globally linked foo
package, the following command can be used (using sudo
if necessary, depending on your setup and permissions)
sudo npm rm --global foo
This will uninstall the package.
To check whether a package is installed, the npm ls
command can be used:
npm ls --global foo
Here's a mmap example:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/*
* pvtmMmapAlloc - creates a memory mapped file area.
* The return value is a page-aligned memory value, or NULL if there is a failure.
* Here's the list of arguments:
* @mmapFileName - the name of the memory mapped file
* @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
* @create - determines whether or not the area should be created.
*/
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)
{
void * retv = NULL;
if (create)
{
mode_t origMask = umask(0);
int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);
umask(origMask);
if (mmapFd < 0)
{
perror("open mmapFd failed");
return NULL;
}
if ((ftruncate(mmapFd, size) == 0))
{
int result = lseek(mmapFd, size - 1, SEEK_SET);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
/* Something needs to be written at the end of the file to
* have the file actually have the new size.
* Just writing an empty string at the current file position will do.
* Note:
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - An empty string is actually a single '\0' character, so a zero-byte
* will be written at the last byte of the file.
*/
result = write(mmapFd, "", 1);
if (result != 1)
{
perror("write mmapFd failed");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
}
}
else
{
int mmapFd = open(mmapFileName, O_RDWR, 00666);
if (mmapFd < 0)
{
return NULL;
}
int result = lseek(mmapFd, 0, SEEK_END);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
if (result == 0)
{
perror("The file has 0 bytes");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
close(mmapFd);
}
return retv;
}
I know this is old, but Google sent me here so I guess others will come too like me.
The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project
Just be aware that you can only add one Content Root
but you can add several Source Folders
. No need to touch __init__.py
files.
I found this solution online, and it addressed this pretty well. My only concern is looping through all the pivots and queries might become time consuming if there's a lot of them:
Sub RefreshTables()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim objList As ListObject
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
For Each objList In ws.ListObjects
If objList.SourceType = 3 Then
With objList.QueryTable
.BackgroundQuery = False
.Refresh
End With
End If
Next objList
Next ws
Call UpdateAllPivots
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Sub UpdateAllPivots()
Dim pt As PivotTable
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
Next ws
End Sub
This might work:
^(\*|\d+(\.\d+){0,2}(\.\*)?)$
At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.
The code for retrieving the matched sequences, especially the (\.\d+){0,2}
part, will depend on your particular regex library.
If you want to use patch you need to remove the a/
b/
prefixes that git uses by default. You can do this with the --no-prefix
option (you can also do this with patch's -p
option):
git diff --no-prefix [<other git-diff arguments>]
Usually though, it is easier to use straight git diff
and then use the output to feed to git apply
.
Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash
and bundles are easier to manage.
For your use case I think that stash
is most appropriate.
# save uncommitted changes
git stash
# do a merge or some other operation
git merge some-branch
# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop
Just wanted to add that I used Microsoft.Interop libraries, specifically ExportAsFixedFormat function which I did not see used in this thread.
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Office.Core;
Application app;
public string CreatePDF(string path, string exportDir)
{
Application app = new Application();
app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
app.Visible = true;
var objPresSet = app.Documents;
var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
var pdfFileName = Path.ChangeExtension(path, ".pdf");
var pdfPath = Path.Combine(exportDir, pdfFileName);
try
{
objPres.ExportAsFixedFormat(
pdfPath,
WdExportFormat.wdExportFormatPDF,
false,
WdExportOptimizeFor.wdExportOptimizeForPrint,
WdExportRange.wdExportAllDocument
);
}
catch
{
pdfPath = null;
}
finally
{
objPres.Close();
}
return pdfPath;
}
This article helped explain a lot of things. It's in FAQ style.
This part explains why Thread.Sleep
runs on the same original thread - leading to my initial confusion.
Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?
No. No. And no. See the previous questions. The “async” keyword indicates to the compiler that “await” may be used inside of the method, such that the method may suspend at an await point and have its execution resumed asynchronously when the awaited instance completes. This is why the compiler issues a warning if there are no “awaits” inside of a method marked as “async”.
Put it into a ScrollViewer
.
If I move
CreateUser.py
to the main user_management directory, I can easily use:import Modules.LDAPManager
to importLDAPManager.py
--- this works.
Please, don't. In this way the LDAPManager
module used by CreateUser
will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.
When you have a package structure you should either:
Use relative imports, i.e if the CreateUser.py
is in Scripts/
:
from ..Modules import LDAPManager
Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.
Use absolute imports using the whole package name(CreateUser.py
in Scripts/
):
from user_management.Modules import LDAPManager
In order for the second one to work the package user_management
should be installed inside the PYTHONPATH
. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append
anywhere.
Also I find it odd that Scripts/
is a subpackage. Because in a real installation the user_management
module would be installed under the site-packages
found in the lib/
directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/
directory (whichever contains executables for your OS).
In fact I believe Script/
shouldn't even be under user_management
. It should be at the same level of user_management
.
In this way you do not have to use -m
, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py
to launch the scripts with the correct path).
In summary, the hierarchy I would use is:
user_management (package)
|
|------- __init__.py
|
|------- Modules/
| |
| |----- __init__.py
| |----- LDAPManager.py
| |----- PasswordManager.py
|
Scripts/ (*not* a package)
|
|----- CreateUser.py
|----- FindUser.py
Then the code of CreateUser.py
and FindUser.py
should use absolute imports to import the modules:
from user_management.Modules import LDAPManager
During installation you make sure that user_management
ends up somewhere in the PYTHONPATH
, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py
adding the Scripts/
parent directory to the PYTHONPATH
(I mean the directory that contains both user_management
and Scripts
):
PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py
Or you can modify the PYTHONPATH
globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH
external variable, on Windows you have to change the environmental variables settings.
Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:
from __future__ import absolute_import
at the top of your modules. In this way import X
always means to import the toplevel module X
and will never try to import the X.py
file that's in the same directory (if that directory isn't in the PYTHONPATH
). In this way the only way to do a relative import is to use the explicit syntax (the from . import X
), which is better (explicit is better than implicit).
This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError
clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.
No, Bootstrap does not introduce special considerations for disabling a drop-down.
<select id="xxx" name="xxx" class="input-medium" disabled>
or
<select id="xxx" name="xxx" class="input-medium" disabled="disabled">
will work. I prefer to give attributes values (as in the second form; in XHTML, attributes must have a value), but the HTML spec says:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
The key differences between read-only and disabled:*
The Disabled attribute
The Read Only Attribute
<SELECT>
, <OPTION>
, and <BUTTON>
elements do not have readonly attributes (although thy both have disabled attributes)*-blatant plagiarism from http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
I know this one is not the best way. But you can try this.
string str = Path.GetRandomFileName(); //This method returns a random file name of 11 characters
str = str.Replace(".","");
Console.WriteLine("Random string: " + str);
Here is my code-
var datePicker = angular.module('appointmentApp', []);
datePicker.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(element).datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (date) {
scope.appoitmentScheduleDate = date;
scope.$apply();
}
});
}
};
});
Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.
That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010
Happy Coding!
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
Generic Collection classes cant be used with primitives. Use the Character and Integer wrapper classes instead.
Map<Character , Integer > checkSum = new HashMap<Character, Integer>();
Jokab's answer helped me a lot but in my case I could not push to github until I logged in my github account to my git bash so i ran the following commands
git config credential.helper store
then
git push http://github.com/[user name]/[repo name].git
After the second command a GUI window appeared, I provided my login credentials and it worked for me.
This three function are the same.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
here $
is used for define jQuery
like $
= jQuery
.
Now difference is that
$(document).ready
is jQuery event that is fired when DOM
is loaded, so it’s fired when the document structure is ready.
$(window).load
event is fired after whole content is loaded like page contain images,css etc.
given your example above - to find processes attached to shmid 98306
lsof | egrep "98306|COMMAND"
You can try with:
display: inline-table;
For me it works fine.
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941
This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}
.
This will result in Unexpected T_ENCAPSED_AND_WHITESPACE
:
echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^
In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE
. So the above could be written as:
echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^
The entire complex array variable and key(s) can be enclosed in {}
, in which case they should be quoted to avoid an E_NOTICE
. The PHP documentation recommends this syntax for complex variables.
echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";
Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:
echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^
For reference, see the section on Variable Parsing in the PHP Strings manual page
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
From command line query the logonserver env variable.
C:> SET L
LOGONSERVER='\'\DCNAME
A simple inline JavaScript confirm would suffice:
<form onsubmit="return confirm('Do you really want to submit the form?');">
No need for an external function unless you are doing validation, which you can do something like this:
<script>
function validate(form) {
// validation code here ...
if(!valid) {
alert('Please correct the errors in the form!');
return false;
}
else {
return confirm('Do you really want to submit the form?');
}
}
</script>
<form onsubmit="return validate(this);">
another solution:
add src/myproject
to $GOPATH.
Then import "mylib"
will compile.
TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor
at the end of your MySQLdb.connect
.
I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:
conn = MySQLdb.connect(host="oldhost",
user="olduser",
passwd="oldpass",
db="olddb",
cursorclass=MySQLdb.cursors.DictCursor)
Which was replaced by:
conn = MySQLdb.connect(host="newhost",
user="newuser",
passwd="newpass",
db="newdb")
The parameter cursorclass=MySQLdb.cursors.DictCursor
at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.
So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.
My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
function getWidth() {_x000D_
return Math.max(_x000D_
document.body.scrollWidth,_x000D_
document.documentElement.scrollWidth,_x000D_
document.body.offsetWidth,_x000D_
document.documentElement.offsetWidth,_x000D_
document.documentElement.clientWidth_x000D_
);_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
return Math.max(_x000D_
document.body.scrollHeight,_x000D_
document.documentElement.scrollHeight,_x000D_
document.body.offsetHeight,_x000D_
document.documentElement.offsetHeight,_x000D_
document.documentElement.clientHeight_x000D_
);_x000D_
}_x000D_
_x000D_
console.log('Width: ' + getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
and similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
Call both of these in your scripts using getWidth()
or getHeight()
. If none of the browser's native properties are defined, it will return undefined
.
To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.
The easiest way to do this is by first getting the local hostname using uname()
or gethostname()
and then performing a lookup with gethostbyname()
and looking at the h_name
member of the struct it returns. If you are using ANSI c, you must use uname()
instead of gethostname()
.
Example:
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);
Unfortunately, gethostbyname()
is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo()
.
Example:
struct addrinfo hints, *info, *p;
int gai_result;
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
exit(1);
}
for(p = info; p != NULL; p = p->ai_next) {
printf("hostname: %s\n", p->ai_canonname);
}
freeaddrinfo(info);
Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo()
ends up being the same as the unqualified hostname.
If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
select E1.emp_id [Emp_id],E1.emp_name [Emp_name],
E2.emp_mgr_id [Mgr_id],E2.emp_name [Mgr_name]
from [tblEmployeeDetails] E1 left outer join
[tblEmployeeDetails] E2
on E1.emp_mgr_id=E2.emp_id
The best way is to use spyOnProperty
. It expects 3 parameters and you need to pass get
or set
as a third param.
const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
// now mock properties
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
Here I am setting the get
of clientWidth
of div.nativeElement
object.
list(your_iterator)
You could use some CSS and with the idea of kbrimington it should do the trick.
The CSS could be like this.
img {
width: 75px;
height: auto;
}
I got it from here: another post
read this...
Portable HttpClient for .NET Framework and Windows Phone
see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx
You could also solve this problem in following way:
$totalView = View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
->groupBy(DB::raw('Date(read_at)'))
->orderBy(DB::raw('Date(read_at)'))
->get();
android:layout_weight=".YOURVALUE" is best way to implement in percentage
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/logTextBox"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".20"
android:maxLines="500"
android:scrollbars="vertical"
android:singleLine="false"
android:text="@string/logText" >
</TextView>
</LinearLayout>
Classloaders can be a tricky problem. You can especially run into problems if you're using multiple classloaders and don't have their interactions clearly and rigorously defined. I think in order to actually be able to unload a class youlre going go have to remove all references to any classes(and their instances) you're trying to unload.
Most people needing to do this type of thing end up using OSGi. OSGi is really powerful and surprisingly lightweight and easy to use,
I think it's meant to mean nothing. The wiki says:
"Foo is commonly used with the metasyntactic variables bar and foobar."
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
Suggestions are (basically) based on the text in the current open file and any snippets or completions you have defined (ref). If you want more text suggestions, I'd recommend:
As a side note, I'd really recommend installing Package control to take full advantage of the Sublime community. Some of the options above use Package control. I'd also highly recommend the tutsplus Sublime tutorial videos, which include all sorts of information about improving your efficiency when using Sublime.
Older versions of JSP did not support the second syntax.
If you are not able to find platform-tools folder, please open SDK Manager and install "Android SDK Platform-Tools" from SDK Tools tab.
There is a good solution to this issue:
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class);
Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);
Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.
Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();
BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);
BigDecimal revenue = results.getResult().get(0).getRevenue();
Don't reinvent the wheel; check out Ruby's way-cool OptionParser library.
It offers parsing of flags/switches, parameters with optional or required values, can parse lists of parameters into a single option and can generate your help for you.
Also, if any of your information being passed in is pretty static, that doesn't change between runs, put it into a YAML file that gets parsed. That way you can have things that change every time on the command-line, and things that change occasionally configured outside your code. That separation of data and code is nice for maintenance.
Here are some samples to play with:
require 'optparse'
require 'yaml'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on('-n', '--sourcename NAME', 'Source name') { |v| options[:source_name] = v }
opts.on('-h', '--sourcehost HOST', 'Source host') { |v| options[:source_host] = v }
opts.on('-p', '--sourceport PORT', 'Source port') { |v| options[:source_port] = v }
end.parse!
dest_options = YAML.load_file('destination_config.yaml')
puts dest_options['dest_name']
This is a sample YAML file if your destinations are pretty static:
---
dest_name: [email protected]
dest_host: imap.gmail.com
dest_port: 993
dest_ssl: true
dest_user: [email protected]
dest_pass: password
This will let you easily generate a YAML file:
require 'yaml'
yaml = {
'dest_name' => '[email protected]',
'dest_host' => 'imap.gmail.com',
'dest_port' => 993,
'dest_ssl' => true,
'dest_user' => '[email protected]',
'dest_pass' => 'password'
}
puts YAML.dump(yaml)
print
outputs each argument, followed by $,
, to $stdout
, followed by $\
. It is equivalent to args.join($,) + $\
puts
sets both $,
and $\
to "\n" and then does the same thing as print
. The key difference being that each argument is a new line with puts
.
You can require 'english'
to access those global variables with user-friendly names.
FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
You have to use the iterator's remove() method, which means no enhanced for loop:
for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
iterator.next();
if (someCondition) {
iterator.remove();
}
}
If you know all your 21 characters in advance you can write them all as one String and then check it like this:
char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;
I think this is the shortest way.
public static async Task<byte[]> GetBytesAsync(string url) {
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = await request.GetResponseAsync())
using (var content = new MemoryStream())
using (var responseStream = response.GetResponseStream()) {
await responseStream.CopyToAsync(content);
return content.ToArray();
}
}
public static async Task<string> GetStringAsync(string url) {
var bytes = await GetBytesAsync(url);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
This will list all jpg
files in the folder you define under url: and append them to a div
as a paragraph. Can do it with ul li
as well.
$.ajax({
url: "YOUR FOLDER",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
If you are looking for a pure vanilla javascript method, you can also use:
document.createRange().selectNodeContents( element );
This will select all the text and is supported by all major browsers.
To trigger the selection on focus, you just need to add the event listener like so:
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
If you want to place it inline in your HTML, then you can do this:
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
This is just another option. There appears to be a few ways of doing this. (document.execCommand("selectall") as mentioned here as well)
document.querySelector('#myElement1').addEventListener('focusin', function() {
document.createRange().selectNodeContents(this);
});
_x000D_
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
_x000D_
I think that error from Nginx is indicating that the connection was closed by your nodejs server (i.e., "upstream"). How is nodejs configured?
Below is the core JavaScript you need to write:
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('color');
if(val=='pick a color'||val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>
If all you want to know is if the browser is IE or not, you can do this:
var isIE = false;
var ua = window.navigator.userAgent;
var old_ie = ua.indexOf('MSIE ');
var new_ie = ua.indexOf('Trident/');
if ((old_ie > -1) || (new_ie > -1)) {
isIE = true;
}
if ( isIE ) {
//IE specific code goes here
}
I recommend this now. It is still very readable and is far less code :)
var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);
if ( isIE ) {
//IE specific code goes here
}
Thanks to JohnnyFun in the comments for the shortened answer :)
Firstly, if you can, you should use @supports
statements instead of JS for checking if a browser supports a certain CSS feature.
.element {
/* styles for all browsers */
}
@supports (display: grid) {
.element {
/* styles for browsers that support display: grid */
}
}
(Note that IE doesn't support @supports
at all and will ignore any styles placed inside an @supports
statement.)
If the issue can't be resolved with @supports
then you can do this:
// JS
var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);
if ( isIE ) {
document.documentElement.classList.add('ie')
}
/* CSS */
.element {
/* styles that apply everywhere */
}
.ie .element {
/* styles that only apply in IE */
}
(Note: classList
is relatively new to JS and I think, out of the IE browsers, it only works in IE11. Possibly also IE10.)
If you are using SCSS (Sass) in your project, this can be simplified to:
/* SCSS (Sass) */
.element {
/* styles that apply everywhere */
.ie & {
/* styles that only apply in IE */
}
}
If you also want to add Microsoft Edge into the list, you can do the following. However I do not recommend it as Edge is a much more competent browser than IE.
var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident|Edge\//.test(ua);
if ( isIE ) {
//IE & Edge specific code goes here
}
Pretty easy:
public void PrintSql_Array()
{
int[] numbers = new int[4];
string[] names = new string[4];
string[] secondNames = new string[4];
int[] ages = new int[4];
int cont = 0;
string cs = @"Server=ADMIN\SQLEXPRESS; Database=dbYourBase; User id=sa; password=youpass";
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM tbl_Datos";
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
numbers[cont] = row.Field<int>(0);
names[cont] = row.Field<string>(1);
secondNames[cont] = row.Field<string>(2);
ages[cont] = row.Field<int>(3);
cont++;
}
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0} | {1} {2} {3}", numbers[i], names[i], secondNames[i], ages[i]);
}
con.Close();
}
}
}
Two things are happening here.
Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.
What you want to do is the following:
<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
<div class="row">
<div class="col-md-4 myClassName"> <!-- myClassName is defined in my CSS as you defined your container -->
<img src="#.jpg" height="200px" width="300px">
</div>
</div>
</div>
Here you can find more info on the Bootstrap grid system.
That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
max-width: 900px;
overflow:hidden;
min-height:0px !important;
}
But I have always found that the "!important" clause just makes for messy CSS.
If you have two or more selects and use Steve McLenithan's answer, try to replace the first line with:
$('#CHOSENINPUTFIELDID_chosen > div > div input').autocomplete({
not remove suffix: _chosen
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
Simply you can use this snippet:
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main()
{
array<int,3> values;
cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
cout << "sizeof(myints): " << sizeof(values) << endl;
}
and here is the reference : http://www.cplusplus.com/reference/array/array/size/
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
This is written in Kotlin, it will open the maps app if it's found and place the point and let you start the trip:
val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
}
Replace requireActivity()
with your Context
.
You are not creating a separate dictionary for each iframe, you just keep modifying the same dictionary over and over, and you keep adding additional references to that dictionary in your list.
Remember, when you do something like content.append(info)
, you aren't making a copy of the data, you are simply appending a reference to the data.
You need to create a new dictionary for each iframe.
for iframe in soup.find_all('iframe'):
info = {}
...
Even better, you don't need to create an empty dictionary first. Just create it all at once:
for iframe in soup.find_all('iframe'):
info = {
"src": iframe.get('src'),
"height": iframe.get('height'),
"width": iframe.get('width'),
}
content.append(info)
There are other ways to accomplish this, such as iterating over a list of attributes, or using list or dictionary comprehensions, but it's hard to improve upon the clarity of the above code.
The question is for linux but I had the same issue with git bash on my Windows machine.
My pqsql is installed here:
C:\Program Files\PostgreSQL\10\bin\psql.exe
You can add the location of psql.exe
to your Path environment variable as shown in this screenshot:
After changing the above, please close all cmd
and/or bash
windows, and re-open them (as mentioned in the comments @Ayush Shankar)
You might need to change default logging user using below command.
psql -U postgres
Here postgres
is the username. Without -U
, it will pick the windows loggedin user.
You can use this :
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
For more information see documentation https://square.github.io/retrofit/
$("#gst_show>input").change(function(){
var checked = $(this).is(":checked");
if($("#gst_show>input:checkbox").attr("checked",checked)){
alert('Checked Successfully');
}
});
In my case ( Visual Studio 2012 / IIS Express / ASP.NET MVC 4 app / .Net Framework 4.5 ) what really worked after 30 minutes of trial and error was setting the maxQueryStringLength
property in the <httpRuntime>
tag:
<httpRuntime targetFramework="4.5" maxQueryStringLength="10240" enable="true" />
maxQueryStringLength
defaults to 2048
.
More about it here:
Expanding the Range of Allowable URLs
I tried setting it in <system.webServer>
as @MattVarblow suggests, but it didn't work... and this is because I'm using IIS Express (based on IIS 8) on my dev machine with Windows 8.
When I deployed my app to the production environment (Windows Server 2008 R2 with IIS 7), IE 10 started returning 404 errors in AJAX requests with long query strings. Then I thought that the problem was related to the query string and tried @MattVarblow's answer. It just worked on IIS 7. :)
By default, the Terminal has these shortcuts to move (left and right) word-by-word:
You can configure alt+← and → to generate those sequences for you:
? ?
if it's there, or add it if it's not.\033b
(you can't type this text manually).\033f
) Alternatively, you can refer to this blog post over at textmate:
I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell.
rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:
dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))
or
dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))
The worksheet function sum will correctly ignore blank spaces.
Let me know if this helps!
Everything in Java is passed by value .
In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .
Take a look at this interesting article for further information ...
os.path.exists(path) Returns True if path refers to an existing path. An existing path can be regular files (http://en.wikipedia.org/wiki/Unix_file_types#Regular_file), but also special files (e.g. a directory). So in essence this function returns true if the path provided exists in the filesystem in whatever form (notwithstanding a few exceptions such as broken symlinks).
os.path.isdir(path) in turn will only return true when the path points to a directory
devnull is right;
sudo update-alternatives --config x-terminal-emulator
If you are dealing with more dynamic screen resolution/sizes, instead of hardcoding the size in pixels you can change the width to a percentage of the media width as such
@media (min-width: 1200px) {
.container{
max-width: 70%;
}
}
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).
I could recommend the following trick: Create a special boost.props
file
This procedure has the value that boost is included only in projects where you want to explicitly include it. When you have a new project that uses boost, do:
EDIT (following edit from @jim-fred):
The resulting boost.props
file looks something like this...
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<BOOST_DIR>D:\boost_1_53_0\</BOOST_DIR>
</PropertyGroup>
<PropertyGroup>
<IncludePath>$(BOOST_DIR);$(IncludePath)</IncludePath>
<LibraryPath>$(BOOST_DIR)stage\lib\;$(LibraryPath)</LibraryPath>
</PropertyGroup>
</Project>
It contains a user macro for the location of the boost directory (in this case, D:\boost_1_53_0) and two other parameters: IncludePath and LibraryPath. A statement #include <boost/thread.hpp>
would find thread.hpp in the appropriate directory (in this case, D:\boost_1_53_0\boost\thread.hpp). The 'stage\lib\' directory may change depending on the directory installed to.
This boost.props file could be located in the D:\boost_1_53_0\
directory.
.equals(false)
will be slower because you are calling a virtual method on an object rather than using faster syntax and rather unexpected by most of the programmers because code standards that are generally used don't really assume you should be doing that check via .equals(false)
method.
Is this markup added to the DOM asynchronously? You will need to use live
in that case:
NOTE: .live
has been deprecated and removed in the latest versions of jQuery (for good reason). Please refer to the event delegation strategy below for usage and solution.
<script>
$(document).ready(function(){
$('.play_navigation a').live('click', function(){
console.log("this is the click");
return false;
});
});
</script>
The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live
(or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.
Using jQuery 1.7 event delegation:
$(function () {
$('.play_navigation').on('click', 'a', function (e) {
console.log('this is the click');
e.preventDefault();
});
});
You can also delegate events up to the document if you feel that you would like to bind the event before the document is ready (note that this also causes jQuery to examine every click event to determine if the element matches the appropriate selector):
$(document).on('click', '.play_navigation a', function (e) {
console.log('this is the click');
e.preventDefault();
});
I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder
You could try to "weight" certain columns, like this:
<table border="1" style="width: 100%;">
<colgroup>
<col width="80%" />
<col width="20%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td>Less content here.</td>
</tr>
</table>
You can also try some more interesting tweaks, like using 0%-width columns and using some combination of the white-space
CSS property.
<table border="1" style="width: 100%;">
<colgroup>
<col width="100%" />
<col width="0%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td style="white-space: nowrap;">Less content here.</td>
</tr>
</table>
You get the idea.
Created the Data frame:
import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})
Now use DataFrame.replace()
function:
dk.BrandName.replace(to_replace=['ABC','AB'],value='A')
I get the following error message when trying to push with the GitHub Extension for Visual Studio:
Error encountered while pushing branch to the remote repository: Git failed with a fatal error repository 'https://github.com/my-repo' not found
I know that the repository exists, I pulled from it. Unfortunately the error message in this situation does not indicate the root cause: I did not have write permissions for that repository
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
var files = Directory.GetFiles(@"E:\ftproot\sales");
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello
and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml
file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
It is happening Due to:
<p><script>var _nwls=[];if(window.jQuery&&window.jQuery.find){_nwls=jQuery.find(".fw_link_newWindow");}else{if(document.getElementsByClassName){_nwls=document.getElementsByClassName("fw_link_newWindow");}else{if(document.querySelectorAll){_nwls=document.querySelectorAll(".fw_link_newWindow");}else{document.write('<scr'+'ipt src="http://static.websimages.com/static/global/js/sizzle/sizzle.min.js"><\/scr'+'ipt>');if(window.Sizzle){_nwls=Sizzle(".fw_link_newWindow");}}}}var numlinks=_nwls.length;for(var i=0;i<numlinks;i++){_nwls[i].target="_blank";}</script></p>
Remove <p></p>
around the script.
In Windows 10 using node v6.11.2 and npm v3.10.10, in order to execute directly in any folder:
> node-sass [options] <input.scss> [output.css]
I only followed the instructions in node-sass Github:
Add node-gyp prerequisites by running as Admin in a Powershell (it takes a while):
> npm install --global --production windows-build-tools
In a normal command-line shell (Win+R+cmd+Enter) run:
> npm install -g node-gyp
> npm install -g node-sass
The -g
places these packages under %userprofile%\AppData\Roaming\npm\node_modules
. You may check that npm\node_modules\node-sass\bin\node-sass
now exists.
Check if your local account (not the System) PATH
environment variable contains:
%userprofile%\AppData\Roaming\npm
If this path is not present, npm and node may still run, but the modules bin files will not!
Close the previous shell and reopen a new one and run either > node-gyp
or > node-sass
.
Note:
windows-build-tools
may not be necessary (if no compiling is done? I'd like to read if someone made it without installing these tools), but it did add to the admin account the GYP_MSVS_VERSION
environment variable with 2015
as a value.> uglifyjs main.js main.min.js
and > mocha
There is no TCP API that will tell you the current state of the connection. isConnected()
and isClosed()
tell you the current state of your socket. Not the same thing.
isConnected()
tells you whether you have connected this socket. You have, so it returns true.
isClosed()
tells you whether you have closed this socket. Until you have, it returns false.
If the peer has closed the connection in an orderly way
read()
returns -1readLine()
returns null
readXXX()
throws EOFException
for any other XXX.
A write will throw an IOException
: 'connection reset by peer', eventually, subject to buffering delays.
If the connection has dropped for any other reason, a write will throw an IOException
, eventually, as above, and a read may do the same thing.
If the peer is still connected but not using the connection, a read timeout can be used.
Contrary to what you may read elsewhere, ClosedChannelException
doesn't tell you this. [Neither does SocketException: socket closed.
] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.
As a result of some experiments with Java 7 on Windows XP it also appears that if:
OP_READ
select()
returns a value of greater than zeroSelectionKey
is already invalid (key.isValid() == false
)it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.
osascript -e 'display notification "hello world!"'
osascript -e 'display notification "hello world!" with title "This is the title"'
osascript -e 'display notification "hello world!" with title "Greeting" sound name "Submarine"'
osascript -e 'display notification "'"$TR_TORRENT_NAME has finished downloading!"'" with title " ? Transmission-daemon"'
credits: https://code-maven.com/display-notification-from-the-mac-command-line
First, you need to initialize the toolbar :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then call the back button from the action bar :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
let is a part of es6. These functions will explain the difference in easy way.
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
pip install -U setuptools
and easy_install
was putting egg-info in the wrong directory.
Then I just reinstalled apt-get install python-dev
.
Let me install the drivers I want after that
Well that is Because of
you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.
look this. Try and u will be able to resolve this
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
System.out.println("This is Data to be Decrypted" + decordedValue);
return decordedValue;
}
hope that will help.
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:
def compare(item1, item2):
if fitness(item1) < fitness(item2):
return -1
elif fitness(item1) > fitness(item2):
return 1
else:
return 0
# Calling
list.sort(key=compare)
You just need to feed the path to your file to pd.read_excel
import pandas as pd
file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)
Checkout the documentation to explore parameters like skiprows
to ignore rows when loading the excel
s = "I have white space".delete(' ')
And to emulate PHP's trim()
function:
s = " I have leading and trailing white space ".strip
Put this in your CMakeLists.txt
file (change any options from OFF to ON if you want):
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.45.0 COMPONENTS *boost libraries here*)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(progname file1.cxx file2.cxx)
target_link_libraries(progname ${Boost_LIBRARIES})
endif()
Obviously you need to put the libraries you want where I put *boost libraries here*
. For example, if you're using the filesystem
and regex
library you'd write:
find_package(Boost 1.45.0 COMPONENTS filesystem regex)
You are trying to insert data that is larger than allowed for the column logo
.
Use following data types as per your need
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
Use LONGBLOB
to avoid this exception.
We can achieve it as below, it will skip even numbers
local len = 5
for i = 1, len do
repeat
if i%2 == 0 then break end
print(" i = "..i)
break
until true
end
O/P:
i = 1
i = 3
i = 5
You could use an OrderedDictionary, but I would question why you would want to do that.
Try
Server.MapPath(FileUpload1.FileName);
Edit: This answer describes how to get the path to a file on the server. It does not describe how to get the path to a file on the client, which is what the question asked. The answer to that question is "you can't", because modern browser will not tell you the path on the client, for security reasons.
If you want the margin-left
to work on a span
element you'll need to make it display: inline-block
or display:block
as well.
Download it from here and extract LatoOFL.rar
then go to TTF and open this font-face-generator click at Choose File
choose font which you want to use and click at generate then download it and then go html
file open it and you see the code like this
@font-face {
font-family: "Lato Black";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body{
font-family: "Lato Black";
direction: ltr;
}
change the src code and give the url where your this font directory placed, now you can use it at your website...
If you don't want to download it use this
<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.
You have to set translate property in such way that both the <div>
overlap each other then You can use JavaScript to show and hide both the <div>
according to your requirements
use tortoise svn to cleanup with 'break write locks' option checked
I needed something that I could use to search all my servers using CMS and search by server, DB, schema or table. This is what I found (originally posted by Michael Sorens here: How do I list all tables in all databases in SQL Server in a single result set? ).
SET NOCOUNT ON
DECLARE @AllTables TABLE
(
ServerName NVARCHAR(200)
,DBName NVARCHAR(200)
,SchemaName NVARCHAR(200)
,TableName NVARCHAR(200)
)
DECLARE @SearchSvr NVARCHAR(200)
,@SearchDB NVARCHAR(200)
,@SearchS NVARCHAR(200)
,@SearchTbl NVARCHAR(200)
,@SQL NVARCHAR(4000)
SET @SearchSvr = NULL --Search for Servers, NULL for all Servers
SET @SearchDB = NULL --Search for DB, NULL for all Databases
SET @SearchS = NULL --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL --Search for Tables, NULL for all Tables
SET @SQL = 'SELECT @@SERVERNAME
,''?''
,s.name
,t.name
FROM [?].sys.tables t
JOIN sys.schemas s on t.schema_id=s.schema_id
WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
-- AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
'
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables
INSERT INTO @AllTables
(
ServerName
,DBName
,SchemaName
,TableName
)
EXEC sp_MSforeachdb @SQL
SET NOCOUNT OFF
SELECT *
FROM @AllTables
ORDER BY 1,2,3,4
It's possible to have http://test_site.com and https://production_site.com. Then hardcoding the url is a bad idea. I would suggest this:
{{app.request.scheme ~ '://' ~ app.request.host ~ asset('bundle/myname/img/image.gif')}}
Your case is not talking about collision resolution, it is simply replacement of older value with a new value for the same key because Java's HashMap
can't contain duplicates (i.e., multiple values) for the same key.
In your example, the value 17 will be simply replaced with 20 for the same key 10 inside the HashMap.
If you are trying to put a different/new value for the same key, it is not the concept of collision resolution, rather it is simply replacing the old value with a new value for the same key. It is how HashMap
has been designed and you can have a look at the below API (emphasis is mine) taken from here.
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
On the other hand, collision resolution techniques comes into play only when multiple keys end up with the same hashcode (i.e., they fall in the same bucket location) where an entry is already stored. HashMap
handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries).
"Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.
It sounds like you're essentially trying to use the hash code as a key in a map (which is what HashSets do behind the scenes). You could just do it explicitly, by declaring HashMap<Integer, MyHashObject>
.
There is no get
for HashSets because typically the object you would supply to the get
method as a parameter is the same object you would get back.
If you target browsers that support the URLSearchParams
API (most recent browsers) and FormData(formElement)
constructor (most recent browsers), use this:
new URLSearchParams(new FormData(formElement)).toString()
For browsers that support URLSearchParams
but not the FormData(formElement)
constructor, use this FormData polyfill and this code (works everywhere except IE):
new URLSearchParams(Array.from(new FormData(formElement))).toString()
var form = document.querySelector('form');
var out = document.querySelector('output');
function updateResult() {
try {
out.textContent = new URLSearchParams(Array.from(new FormData(form)));
out.className = '';
} catch (e) {
out.textContent = e;
out.className = 'error';
}
}
updateResult();
form.addEventListener('input', updateResult);
_x000D_
body { font-family: Arial, sans-serif; display: flex; flex-wrap: wrap; }
input[type="text"] { margin-left: 6px; max-width: 30px; }
label + label { margin-left: 10px; }
output { font-family: monospace; }
.error { color: #c00; }
div { margin-right: 30px; }
_x000D_
<!-- FormData polyfill for older browsers -->
<script src="https://unpkg.com/[email protected]/formdata.min.js"></script>
<div>
<h3>Form</h3>
<form id="form">
<label>x:<input type="text" name="x" value="1"></label>
<label>y:<input type="text" name="y" value="2"></label>
<label>
z:
<select name="z">
<option value="a" selected>a</option>
<option value="b" selected>b</option>
</select>
</label>
</form>
</div>
<div>
<h3>Query string</h3>
<output for="form"></output>
</div>
_x000D_
For even older browsers (e.g. IE 10), use the FormData polyfill, an Array.from
polyfill if necessary and this code:
Array.from(
new FormData(formElement),
e => e.map(encodeURIComponent).join('=')
).join('&')
You can try configure SQL server:
NOTE: ALL TCP port is 1433 Finally, restart the server.
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
A 32 bit integer ranges from -2,147,483,648 to 2,147,483,647. However the fact that you are on a 32-bit machine does not mean your C
compiler uses 32-bit integers.
A clean and easy solution (C#):
static class Utilities {
public static List<T> GetAllControls<T>(this Control container) where T : Control {
List<T> controls = new List<T>();
if (container.Controls.Count > 0) {
controls.AddRange(container.Controls.OfType<T>());
foreach (Control c in container.Controls) {
controls.AddRange(c.GetAllControls<T>());
}
}
return controls;
}
}
Get all textboxes:
List<TextBox> textboxes = myControl.GetAllControls<TextBox>();
If you start 64bit Android Studio, you have to add in User Variable as
"JAVA_HOME"
"C:\Program Files\Java\jdk1.8.0_31"
If 32bit
"JAVA_HOME"
"C:\Program Files\Java\jdk1.8.0_31"
and don't put \bin
end
then comes to system variable
select and edit "path" as
"C:\Program Files\Java\jdk1.8.0_31\bin"
here u should must put " bin;
" at end also put ; together.....Okey do it
set
is what you want, so you should use set
. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)
! Code defensively. Worry about what's faster when you determine that it is too slow.
range(min(mylist), max(mylist) + 1) # <-- don't forget to add 1
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000
This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where
condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000
For the second query you must use IS
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null
EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000
To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)
This error because mysql is trying to connect via wrong socket file
try this command for MAMP servers
cd /var/mysql && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock
or
cd /tmp && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock
and this commands for XAMPP servers
cd /var/mysql && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock
or
cd /tmp && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock
I was also getting the same error --> "[PDOException] could not find driver "
I realized that the php was pointing to /usr/bin/php instead of the lampp /opt/lampp/bin/php so i simply created and alias
alias php="/opt/lampp/bin/php"
also had to make update to the .env file to ensure the database access credentials were updated.
And guess what, it Worked!
You could use a flag to keep track of the status:
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = 0;_x000D_
var t = window.setInterval(function() {_x000D_
if(!isPaused) {_x000D_
time++;_x000D_
output.text("Seconds: " + time);_x000D_
}_x000D_
}, 1000);_x000D_
_x000D_
//with jquery_x000D_
$('.pause').on('click', function(e) {_x000D_
e.preventDefault();_x000D_
isPaused = true;_x000D_
});_x000D_
_x000D_
$('.play').on('click', function(e) {_x000D_
e.preventDefault();_x000D_
isPaused = false;_x000D_
});
_x000D_
h1 {_x000D_
font-family: Helvetica, Verdana, sans-serif;_x000D_
font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="play">Play</button>_x000D_
<button class="pause">Pause</button>
_x000D_
This is just what I would do, I'm not sure if you can actually pause the setInterval.
Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.
As a reference it might help someone... On Debian system I hard to do the following:
apt-get install -y libsm6 libxext6 libxrender-dev
pip3 install opencv-python
python3 -c "import cv2"
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
The PID is stored in $$
.
Example: kill -9 $$
will kill the shell instance it is called from.
Might want to check out the TextWriter class.
//Open File
TextWriter tw = new StreamWriter("file.txt");
//Write to file
tw.WriteLine("test info");
//Close File
tw.Close();
I had the same problem. My socket was eventually found in /tmp/mysql.sock. Then I added that path to php.ini. I found the socket there from checking the page "Server Status" in MySQL Workbench. If your socket isn't in /tmp/mysql.sock then maybe MySQL Workbench could tell you where it is? (Granted you use MySQL Workbench...)
Either encode the needed XML entities or use CDATA.
<arg0>
<!--Optional:-->
<parameter1><test>like this</test></parameter1>
<!--Optional:-->
<parameter2><![CDATA[<test>or like this</test>]]></parameter2>
</arg0>
You should set the css property touch-action
to none
as described in this other answer https://stackoverflow.com/a/42288386/1128216
.disable-doubletap-to-zoom {
touch-action: none;
}
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
I caught this error a few days ago.
IN my case it was because I was using a Transaction on a Singleton.
.Net does not work well with Singleton as stated above.
My solution was this:
public class DbHelper : DbHelperCore
{
public DbHelper()
{
Connection = null;
Transaction = null;
}
public static DbHelper instance
{
get
{
if (HttpContext.Current is null)
return new DbHelper();
else if (HttpContext.Current.Items["dbh"] == null)
HttpContext.Current.Items["dbh"] = new DbHelper();
return (DbHelper)HttpContext.Current.Items["dbh"];
}
}
public override void BeginTransaction()
{
Connection = new SqlConnection(Entity.Connection.getCon);
if (Connection.State == System.Data.ConnectionState.Closed)
Connection.Open();
Transaction = Connection.BeginTransaction();
}
}
I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class
Or you can have your alias in a HAVING
clause
Use the FormBorderStyle
property. Make it FixedSingle
:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..
nmap
is the right tool.
Simply use nmap example.com -p 80
You can use it from local or remote server. It also helps you identify if a firewall is blocking the access.
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
You can use the following library: https://github.com/ink-spot/UPCarouselFlowLayout
It's very simple and ofc you do not need to think about details like other answers contain.
You can think of these as the opposites of one another.
When you free an area of memory, but still keep a pointer to it, that pointer is dangling:
char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!
When you lose the pointer, but keep the memory allocated, you have a memory leak:
void myfunc()
{
char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!
Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:
The portable way of doing this is that you create a
SOAPHandler
and mess with SAAJ, but the RI provides a better way of doing this.When you create a proxy or dispatch object, they implement
BindingProvider
interface. When you use the JAX-WS RI, you can downcast toWSBindingProvider
which defines a few more methods provided only by the JAX-WS RI.This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on
Headers
class to create one.import com.sun.xml.ws.developer.WSBindingProvider; HelloPort port = helloService.getHelloPort(); // or something like that... WSBindingProvider bp = (WSBindingProvider)port; bp.setOutboundHeader( // simple string value as a header, like <simpleHeader>stringValue</simpleHeader> Headers.create(new QName("simpleHeader"),"stringValue"), // create a header from JAXB object Headers.create(jaxbContext,myJaxbObject) );
Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.
Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.
you need implements Parcelable in your ContactBean
class, I put one example for you:
public class ContactClass implements Parcelable {
private String id;
private String photo;
private String firstname;
private String lastname;
public ContactClass()
{
}
private ContactClass(Parcel in) {
firstname = in.readString();
lastname = in.readString();
photo = in.readString();
id = in.readString();
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstname);
dest.writeString(lastname);
dest.writeString(photo);
dest.writeString(id);
}
public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
public ContactClass createFromParcel(Parcel in) {
return new ContactClass(in);
}
public ContactClass[] newArray(int size) {
return new ContactClass[size];
}
};
// all get , set method
}
and this get and set for your code:
Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);
second class:
ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
from io import BytesIO
df = pd.read_excel(BytesIO(bytes_content), engine='openpyxl')
worked for me
std::remove
does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase
to do the REAL removal of the extra elements that are now at the end of the container:
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
It depends how many times you're going to want to find this information, if more than once:
Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);
Otherwise a short circuited loop:
for (i = 0; i < myArray.length; i++) {
if (!myArray[i]) return false;
}
return true;
To return a value along with setting ref parameter, here is a piece of code:
public static class MoqExtensions
{
public static IReturnsResult<TMock> DelegateReturns<TMock, TReturn, T>(this IReturnsThrows<TMock, TReturn> mock, T func) where T : class
where TMock : class
{
mock.GetType().Assembly.GetType("Moq.MethodCallReturn`2").MakeGenericType(typeof(TMock), typeof(TReturn))
.InvokeMember("SetReturnDelegate", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, mock,
new[] { func });
return (IReturnsResult<TMock>)mock;
}
}
Then declare your own delegate matching the signature of to-be-mocked method and provide your own method implementation.
public delegate int MyMethodDelegate(int x, ref int y);
[TestMethod]
public void TestSomething()
{
//Arrange
var mock = new Mock<ISomeInterface>();
var y = 0;
mock.Setup(m => m.MyMethod(It.IsAny<int>(), ref y))
.DelegateReturns((MyMethodDelegate)((int x, ref int y)=>
{
y = 1;
return 2;
}));
}
you can add keyup event like this
template: `
<input (keyup)="onKey($event)">
<p>{{values}}</p>
`
in Component, code some like below
export class KeyUpComponent_v1 {
values = '';
onKey(event:any) { // without type info
this.values += event.target.value + ' | ';
}
}
I'm an async novice, so I can't tell you definitively what is happening here. I suspect that there's a mismatch in the method execution expectations, even though you are using tasks internally in the methods. I think you'd get the results you are expecting if you changed Print to return a Task<string>:
private static string Send(int id)
{
Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
Task<string> result;
responseTask.ContinueWith(x => result = Print(x));
result.Wait();
responseTask.Wait(); // There's likely a better way to wait for both tasks without doing it in this awkward, consecutive way.
return result.Result;
}
private static Task<string> Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
string result = string.Empty;
task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
result = t.Result;
});
return task;
}
This works:
Suppose
dbo.AsDesignedBites.XN1E1 = 4016519.564`
For the following string:
'POLYGON(('+STR(dbo.AsDesignedBites.XN1E1, 11, 3)+'...
I am using Android Studio 4 developing a Fluter/Dart application. There does not seem to be a Sync project with gradle button or file menu item, there is no clean or rebuild either.
I fixed the problem by removing the .idea folder. The suggestion included removing .gradle as well, but it did not exist.
Uninstalling the application would be enough to avoid this problem.
INSTALL_FAILED_UPDATE_INCOMPATIBLE
but sometimes even uninstalling the message is raised again, it occurs in Android OS 5.0 +, so this is the solution:
Go to Settings
> Apps
and you will find your app with the message:
"Not installed for this user"
, we have to uninstall manually for all users with the option:
"Uninstall for all users"
Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1
Code:-
If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}`
` @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
}
MemberwiseClone
is a good way to do a shallow copy as others have suggested. It is protected however, so if you want to use it without changing the class, you have to access it via reflection. Reflection however is slow. So if you are planning to clone a lot of objects it might be worthwhile to cache the result:
public static class CloneUtil<T>
{
private static readonly Func<T, object> clone;
static CloneUtil()
{
var cloneMethod = typeof(T).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
clone = (Func<T, object>)cloneMethod.CreateDelegate(typeof(Func<T, object>));
}
public static T ShallowClone(T obj) => (T)clone(obj);
}
public static class CloneUtil
{
public static T ShallowClone<T>(this T obj) => CloneUtil<T>.ShallowClone(obj);
}
You can call it like this:
Person b = a.ShallowClone();
Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.
Clion from JetBrains, also is available now, and uses Cmake as project model.
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
This issue is a pain in my a$$, I have this issue in my Mac, if I run
mvn clean install | grep "error reading"
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/aspose/aspose-pdf/11.5.0/aspose-pdf-11.5.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file
Removing all corrupted libs is the only solution
So I want to remove all of them at once.
mvn clean install | grep "error reading" | awk '{print "rm " $4 | "/bin/sh" }'
The command needs AWK to take libPath string from column $4
Then rerun
mvn clean install
Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS
entries for a host name and IP
entries for IP addresses).
To quote myself:
If you're using
keytool
, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1
Note that you only need Java 7's keytool
to use this command. Once you've prepared your keystore, it should work with previous versions of Java.
(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)
These answers actually dissuaded me from trying the simplest possible thing! Simply specify a threshold for an appender (say, "console") in your log4j.configuration
like so:
log4j.appender.console.threshold=${my.logging.threshold}
Then, on the command line, include the system property -Dlog4j.info -Dmy.logging.threshold=INFO
. I assume that any other property can be parameterized in this way, but this is the easiest way to raise or lower the logging level globally.
You can check the called
attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest
, you can check the contents of call_args_list
instead:
self.assertItemsEqual(my_var.call_args_list, [])
When it fails, it gives a message like this:
AssertionError: Element counts were not equal: First has 0, Second has 1: call('first argument', 4)
I just had same error. I had year 2015 in app id. I replaced 2015 by fifteen and that solved it.
Also, if you use Android Studio, you can try: Tools / Android / Synch Project with Gradle Files
Solution:
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)
x = [i for i in x if len(i)==2]
Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
It is 2017, but this thread is top in my search engine, today the following methods are preferred (initializer lists)
std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" };
From https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
This worked for me in swift:
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")
This will give you DD MM YYYY YY HH Min Sec
variables and works on any Windows machine from XP Pro and later.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
span {display:block;}
also adds a line-break.
To avoid that, use span {display:inline-block;}
and then you can add width and height to the inline element, and you can align it within the block as well:
span {
display:inline-block;
width: 5em;
font-weight: normal;
text-align: center
}
It is likely a case of IIS 7 'handling' the HTTP OPTIONS response instead of your application specifying it. To determine this, in IIS7,
Go to your site's Handler Mappings.
Scroll down to 'OPTIONSVerbHandler'.
Change the 'ProtocolSupportModule' to 'IsapiHandler'
Set the executable: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Now, your config entries above should kick in when an HTTP OPTIONS verb is sent.
Alternatively you can respond to the HTTP OPTIONS verb in your BeginRequest method.
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
You can use a dictionary comprehension.
d = {k:d[k] for k in d if d[k] != val}
Note: Note to Win32 Users In order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
This note solved my problem. Thought of sharing. libeay32.dll & ssleay.dll you will find in your php installation folder.
Imagine you are working on a machine where n
was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.
Assuming a simple LIFO caching policy, this code:
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
would first cause a
and b
to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c
and d
would then be loaded from disk into RAM and operated on.
the other loop
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.
You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.
There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.
Say n = 2
and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).
Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:
With
for(int j=0;j<n;j++){
a[j] += b[j];
}
for(int j=0;j<n;j++){
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[1] = a[1] + b[1]
in cache. Cost = 1 + 1.c
and d
.Total cost = (100 + 100 + 1 + 1) * 2 = 404
With
for(int j=0;j<n;j++){
a[j] += b[j];
c[j] += d[j];
}
cache a[0]
and a[1]
then b[0]
and b[1]
and set a[0] = a[0] + b[0]
in cache - there are now four bytes in cache, a[0], a[1]
and b[0], b[1]
. Cost = 100 + 100.
a[0], a[1], b[0], b[1]
from cache and cache c[0]
and c[1]
then d[0]
and d[1]
and set c[0] = c[0] + d[0]
in cache. Cost = 100 + 100.(100 + 100 + 100 + 100) * 2 = 800
This is a classic cache thrash scenario.
Here's a simple example using urllib2 that does a basic authentication against GitHub's API.
import urllib2
u='username'
p='userpass'
url='https://api.github.com/users/username'
# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
# create the request object and set some headers
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', encodeUserData(u, p))
# make the request and print the results
res = urllib2.urlopen(req)
print res.read()
Furthermore if you wrap this in a script and run it from a terminal you can pipe the response string to 'mjson.tool' to enable pretty printing.
>> basicAuth.py | python -mjson.tool
One last thing to note, urllib2 only supports GET & POST requests.
If you need to use other HTTP verbs like DELETE, PUT, etc you'll probably want to take a look at PYCURL
If you want to do something x times, you can do this:
Example (x = 200):
FOR /L %%A IN (1,1,200) DO (
ECHO %%A
)
1,1,200
means:
System.IO.DirectoryInfo myDirInfo = new DirectoryInfo(myDirPath);
foreach (FileInfo file in myDirInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in myDirInfo.GetDirectories())
{
dir.Delete(true);
}
To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir();
to get the allowed directory for the app.
Or:
getCashDir();
<-- should work
context.getCashDir();
(if in a broadcast receiver)
getDataDir();
<--Api 24
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
You can use the following code.
<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
_x000D_
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
this causes mainly because of errors in xml file, check your latest xml changes and rebuild it, same issue with me.
when in kotlin it will look like this :
editText.setOnFocusChangeListener { view, hasFocus ->
if (hasFocus) toast("focused") else toast("focuse lose")
}
I tried subtract, but the result was not consistent.
If I run df1.subtract(df2)
, not all lines of df1 are shown on the result dataframe, probably due distinct
cited on the docs.
This solved my problem:
df1.exceptAll(df2)
Add system variable path, this path is where jupyter and other scripts are located
PATH -->
`C:\Users\<userName>\AppData\Roaming\Python\Python39\Scripts`
Like in my laptop PATH is:
"C:\Users\developer\AppData\Roaming\Python\Python39\Scripts"
After that, You will be able to run jupyter from any folder & any directory by running the below command
jupyter notebook