These two commands should do it:
:set autoindent
:set cindent
For bonus points put them in a file named .vimrc located in your home directory on linux
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264
TLDR;
one needs to set {withCredentials: true}
in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.
Just throw some light in to some issues related to this control.
Date picker is not a standard control that comes with office package. So developers encountered issues like missing date picker controls when application deployed in some other machiens/versions of office. In order to use it you have to activate the reference to the .dll, .ocx file that contains it.
In the event of a missing date picker, you have to replace MSCOMCT2.OCX file in System or System32 directory and register it properly. Try this link to do the proper replacement of the file.
In the VBA editor menu bar-> select tools-> references and then find the date picker reference and check it.
If you need the file, download MSCOMCT2.OCX from here.
The example below is based on your comments. It uses a List of keywords, which will be searched in a given String using word boundaries. It uses StringUtils from Apache Commons Lang to build the regular expression and print the matched groups.
String text = "I will come and meet you at the woods 123woods and all the woods";
List<String> tokens = new ArrayList<String>();
tokens.add("123woods");
tokens.add("woods");
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
If you are looking for more performance, you could have a look at StringSearch: high-performance pattern matching algorithms in Java.
using namespace std;
// c++03
string s = "(555) 555-5555";
s.erase(remove_if(s.begin(), s.end(), not1(ptr_fun(::isdigit))), s.end());
// c++11
s.erase(remove_if(s.begin(), s.end(), ptr_fun(::ispunct)), s.end());
Note: It's posible you need write ptr_fun<int, int>
rather than simple ptr_fun
You can go through the below code to solve this.
$(document).on('click.bs.dropdown.data-api', '.keep_it_open', function (e) {_x000D_
e.stopPropagation();_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="dropdown keep_it_open">_x000D_
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example_x000D_
<span class="caret"></span></button>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution
Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
If you don't find Stencils you can locate them in your install location. C:\Program Files\Microsoft Office\Office15\Visio Content\1033 for UML Sequcen Stencies you can open
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
routerLink
directive as used like this:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
is just a wrapper around imperative navigation using router
and its navigateByUrl method:
router.navigateByUrl('/inbox/33/messages/44')
as can be seen from the sources:
export class RouterLink {
...
@HostListener('click')
onClick(): boolean {
...
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
So wherever you need to navigate a user to another route, just inject the router
and use navigateByUrl
method:
class MyComponent {
constructor(router: Router) {
this.router.navigateByUrl(...);
}
}
There's another method on the router that you can use - navigate:
router.navigate(['/inbox/33/messages/44'])
Using
router.navigateByUrl
is similar to changing the location bar directly–we are providing the “whole” new URL. Whereasrouter.navigate
creates a new URL by applying an array of passed-in commands, a patch, to the current URL.To see the difference clearly, imagine that the current URL is
'/inbox/11/messages/22(popup:compose)'
.With this URL, calling
router.navigateByUrl('/inbox/33/messages/44')
will result in'/inbox/33/messages/44'
. But calling it withrouter.navigate(['/inbox/33/messages/44'])
will result in'/inbox/33/messages/44(popup:compose)'
.
Read more in the official docs.
You need to make sure the checked
property to be true inside the component.ts
export class CheckboxComponent implements OnInit {
checked = true;
}
pymongo
Finding objects between two dates in Python with pymongo
in collection posts
(based on the tutorial):
from_date = datetime.datetime(2010, 12, 31, 12, 30, 30, 125000)
to_date = datetime.datetime(2011, 12, 31, 12, 30, 30, 125000)
for post in posts.find({"date": {"$gte": from_date, "$lt": to_date}}):
print(post)
Where {"$gte": from_date, "$lt": to_date}
specifies the range in terms of datetime.datetime
types.
Another way to do is is to use file_get_contents() and have a template HTML page
TEMPLATE PAGE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>
PHP Function
function YOURFUNCTIONNAME($url){
$html_string = file_get_contents($url);
return $html_string;
}
Apple introduced the topLayoutGuide and bottomLayoutGuide as properties of UIViewController way back in iOS 7. They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar. These layout guides are deprecated in iOS 11 and replaced by a single safe area layout guide.
Refer link for more information.
Try executing this SQL command:
> grant all privileges
on YOUR_DATABASE.*
to 'asdfsdf'@'localhost'
identified by 'your_password';
> flush privileges;
It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.
Also, make sure you have granted FILE
to user 'asdfsdf'@'localhost'
.
> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault()
. However as the OP alluded to, if you always call it preventDefault()
you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.
Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.
// Bind keydown event to this function. Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){
// Use jquery's constants rather than an unintuitive magic number.
// $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
if (e.keyCode == $.ui.keyCode.BACKSPACE) {
// Filters out events coming from any of the following tags so Backspace
// will work when typing text, but not take the page back otherwise.
var rx = /INPUT|SELECT|TEXTAREA/i;
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
// Add your code here.
}
});
This error has occurred when i was importing a project from Github. This happens as the project was of older version. Just try to delete these methods below from your root gradle.
android { compileSdkVersion 19 buildToolsVersion "19.1" }
then try again.
I hope it works.
I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).
If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac
offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac
with the @
prefix.
If you can create a list of all the *.java
files in your project, it's easy:
# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt
:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
sources.txt
file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.On the long run it is better to use a tool that was designed to build software.
If you create a simple build.xml
file that describes how to build the software:
<project default="compile">
<target name="compile">
<mkdir dir="bin"/>
<javac srcdir="src" destdir="bin"/>
</target>
</project>
you can compile the whole software by running the following command:
$ ant
Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.
Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.
They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException
.
For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse
command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)
The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.
Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.
I would echo the array as a string, then transform the spaces into line feeds, and then use paste
to join everything in one line like so:
tr " " "\n" <<< "$FOO" | paste -sd , -
Results:
a,b,c
This seems to be the quickest and cleanest to me !
So it looks like root.iconbitmap()
only supports a fixed directory.
sys.argv[0]
returns the directory that the file was read from so a simple code would work to create a fixed directory.
import sys
def get_dir(src):
dir = sys.argv[0]
dir = dir.split('/')
dir.pop(-1)
dir = '/'.join(dir)
dir = dir+'/'+src
return dir
This is the output
>>> get_dir('test.txt')
'C:/Users/Josua/Desktop/test.txt'
EDIT:
The only issue is that this method dosn't work on linux
josua@raspberrypi:~ $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[0]
''
>>>
The #1 reason has already been stated - it hides errors that you did not expect.
(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.
(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
Another option, if you want to define your constants in one place:
module DSL
module Constants
MY_CONSTANT = 1
end
end
But still make them globally visible without having to access them in fully qualified way:
DSL::Constants::MY_CONSTANT # => 1
MY_CONSTANT # => NameError: uninitialized constant MY_CONSTANT
Object.instance_eval { include DSL::Constants }
MY_CONSTANT # => 1
If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.
Modification of @Ilya_Gazman answer
private void callJavaScript(WebView view, String methodName, Object...params){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("javascript:try{");
stringBuilder.append(methodName);
stringBuilder.append("(");
String separator = "";
for (Object param : params) {
stringBuilder.append(separator);
separator = ",";
if(param instanceof String){
stringBuilder.append("'");
}
stringBuilder.append(param.toString().replace("'", "\\'"));
if(param instanceof String){
stringBuilder.append("'");
}
}
stringBuilder.append(")}catch(error){console.error(error.message);}");
final String call = stringBuilder.toString();
Log.i(TAG, "callJavaScript: call="+call);
view.loadUrl(call);
}
will correctly create JS calls e.g.
callJavaScript(mBrowser, "alert", "abc", "def");
//javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
callJavaScript(mBrowser, "alert", 1, true, "abc");
//javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}
Note that objects will not be passed correctly - but you can serialize them before passing as an argument.
Also I've changed where the error goes, I've diverted it to the console log which can be listened by:
webView.setWebChromeClient(new CustomWebChromeClient());
and client
class CustomWebChromeClient extends WebChromeClient {
private static final String TAG = "CustomWebChromeClient";
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
cm.lineNumber(), cm.sourceId()));
return true;
}
}
Have you tried it?
If you do:
var HI = 'Hello World';
In global.js
. And then do:
alert(HI);
In js1.js
it will alert it fine. You just have to include global.js
prior to the rest in the HTML document.
The only catch is that you have to declare it in the window's scope (not inside any functions).
You could just nix the var
part and create them that way, but it's not good practice.
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
Following are the prerequisites if you want to add firebase to your project.
I could only find out all this after hours of struggle.
Write a function that takes a number as an argument and prints the Fibonacci series till that number
def Series(n):
a = 0
b = 1
print(a)
print(b)
S = 0
for i in range(0,n):
if S <= n-1:
S = a + b
print(S)
a = b
b = S
Even I faced the same issue with my domain. If I gave an IP address it was working. But with a domain name it was not.
Then I checked my DNS A record. The domain had multiple entries with different IP addresses assigned. I removed all the wrong values, and it worked. Just one more check list if anyone faces a similar issue.
A better way to solve this problem is to use a function like this:
function scrollToTop(callback, q) {
if ($('html').scrollTop()) {
$('html').animate({ scrollTop: 0 }, function() {
console.log('html scroll');
callback(q)
});
return;
}
if ($('body').scrollTop()) {
$('body').animate({ scrollTop: 0 }, function() {
console.log('body scroll');
callback(q)
});
return;
}
callback(q);
}
This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");
).
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
Thanks @hoipolloi for the right direction in finding the solution.
Anyway, I had to do a bit different steps to fix the issue.
In my case, the Arduino Uno had worked fine, but it suddenly stopped after some playing with sketches. I was receiving the stk500_recv(): programmer is not responding
all the time and nothing worked. Then I paid attention that the LED 13 is always ON on my board. It looked like some hard looped sketch was running over and over on the board and was blocking any input to the board. Not sure, it's just my gues.
I tried clicking the RESET at all the possible moments without any luck and suddenly tried the following steps:
After this I noticed the onboard 13 LED turned off for a second and then turned on again. It looked like there were a short reset window when the board is actually being reset. Then as in @hoipolloi's solution I caught the moment of "reset" right before the three packets are sent and that worked.
I hope this will help you to figure out the problem if none of other solutions works.
TIP. If you do not see the three Send: 0 [30] [20]
lines when uploading the sketch in your console, do the following:
Look at the log window. You will be able to find a line like this:
E:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CE:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\Sergey\AppData\Local\Temp\build44ca75bc60fd83cc8ef41e35d4d83388.tmp/sketch_sep07a.ino.hex:i
Looks like it swallows line break or space symbols like here -CE:\Program Files...
. It should be -C E:\Program Files
. Copy this like into Notepad, add missing spaces to make the line this:
E:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -v -v -v -v -C "E:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -patmega328p -carduino -PCOM3 -b115200 -D -U flash:w:C:\Users\Sergey\AppData\Local\Temp\build44ca75bc60fd83cc8ef41e35d4d83388.tmp/sketch_sep07a.ino.hex:i
Add 4 -v
instructions like I did above.
Now you will see much more verbose thanks to 4 -v
arguments. Originally, Arduino Studio uses just one.
I have read the other answers and found it important to note a few other things:
1.) For Mac users: When you click "Load unpacked extension...", the Library folder is by default hidden and (even if the Show Hidden files option is toggled on your Mac) it might not show up in Chrome's finder window.
2.) The sub folder containing the extension is a random alpha-numeric string named after the extension's ID, which can be found on Chrome's extension page if Developer flag is set to true. (Upper right hand checkbox on the extensions page)
I know this is an old question that already has several answers, but I had this same problem and for me the issue was that I followed the example provided on console.developers.google.com and entered my domains in the format *.domain.tld/*
. This didn't work at all, and I tried adding all kinds of variations to this like domain.tld
, domain.tld/*
, *.domain.tld
etc.
What solved it for me was adding the actual protocol too; http://domain.tld/*
is the only one I need for it to work on my site. I guess I'll need to add https://domain.tld/*
if I were to switch to HTTPS.
Update: Google have finally updated the placeholder to include http
now:
As far as I know there is no management command to drop all tables. If you don't mind hacking Python you can write your own custom command to do that. You may find the sqlclear
option interesting. Documentation says that ./manage.py sqlclear
Prints the DROP TABLE SQL statements for the given app name(s).
Update: Shamelessly appropriating @Mike DeSimone's comment below this answer to give a complete answer.
./manage.py sqlclear | ./manage.py dbshell
As of django 1.9 it's now ./manage.py sqlflush
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;
You can use this.
I am currently on OS X 10.9 and my efforts to compile vim with +xterm_clipboard brought me nothing. So my current solution is to use MacVim in terminal mode with option set clipboard=unnamed
in my ~/.vimrc file. Works perfect for me.
What about a basic
your_string.strip("0")
to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip
instead (and .lstrip
for only the leading ones).
More info in the doc.
You could use some list comprehension to get the sequences you want like so:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]
BIOS -> Overclockong -> CPU Features -> Intel Virtualization Tech -> Enabled
If you need to duplicate more than a few redirects, you might consider using a map:
# map is outside of server block
map $uri $redirect_uri {
~^/issue1/?$ http://example.com/shop/issues/custom_isse_name1;
~^/issue2/?$ http://example.com/shop/issues/custom_isse_name2;
~^/issue3/?$ http://example.com/shop/issues/custom_isse_name3;
# ... or put these in an included file
}
location / {
try_files $uri $uri/ @redirect-map;
}
location @redirect-map {
if ($redirect_uri) { # redirect if the variable is defined
return 301 $redirect_uri;
}
}
select address from list where address = any (select address from (select address, count(id) cnt from list group by address having cnt > 1 ) as t1) order by address
the inner sub-query returns rows with duplicate address then the outer sub-query returns the address column for address with duplicates. the outer sub-query must return only one column because it used as operand for the operator '= any'
there are a couple of ways of using a timer:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:NO];
As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:
[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:@selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
Have you tried using 'onkeydown'? This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
You will get this error
ERROR 1410 (42000): You are not allowed to create a user with GRANT
If you are trying to run a GRANT
on a user that doesn't exist!
Therefore, first run this to make sure the user you use in your GRANT
matches exactly to what you have:
select User, Host from user;
In particular pay attention whether the user you created is at localhost
but the one you are trying to grant to is %
1:
[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})
>> Object {value: 15}
2:
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })
>> 15
3:
[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
return {value: previousValue.value + currentValue.value};
})
>> Object {value: 15}
I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):
export default class Singleton { static instance; constructor(){ if(instance){ return instance; } this.state = "duke"; this.instance = this; } }
The source code is from: adam-bien.com
You can simulate a friend access if the class that is given the right to access is inside another package and if the methods you are exposing are marked as internal or internal protected. You have to modify the assembly you want to share and add the following settings to AssemblyInfo.cs :
// Expose the internal members to the types in the My.Tester assembly
[assembly: InternalsVisibleTo("My.Tester, PublicKey=" +
"012700000480000094000000060200000024000052534131000400000100010091ab9" +
"ba23e07d4fb7404041ec4d81193cfa9d661e0e24bd2c03182e0e7fc75b265a092a3f8" +
"52c672895e55b95611684ea090e787497b0d11b902b1eccd9bc9ea3c9a56740ecda8e" +
"961c93c3960136eefcdf106955a4eb8fff2a97f66049cd0228854b24709c0c945b499" +
"413d29a2801a39d4c4c30bab653ebc8bf604f5840c88")]
The public key is optional, depending on your needs.
If you are using the latest version of Android studio. then you don't need to install additional software for Git other than GIT itself - https://git-scm.com/downloads
Steps
That's it. You can find your project on your github now
For Ubuntu 10.04 LTS, the sun-java6 packages have been dropped from the Multiverse section of the Ubuntu archive. It is recommended that you use openjdk-6 instead.
If you can not switch from the proprietary Sun JDK/JRE to OpenJDK, you can install sun-java6 packages from the Canonical Partner Repository. You can configure your system to use this repository via command-line:
sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin
sudo update-alternatives --config java
For Ubuntu 10.10, the sun-java6 packages have been dropped from the Multiverse section of the Ubuntu archive. It is recommended that you use openjdk-6 instead.
If you can not switch from the proprietary Sun JDK/JRE to OpenJDK, you can install sun-java6 packages from the Canonical Partner Repository. You can configure your system to use this repository via command-line:
sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin
sudo update-alternatives --config java
The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.
Check out this Example
SELECT first_name, last_name, hire_date, salary
FROM employee
ORDER BY hire_date DESC,last_name ASC;
It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .
Here's the answer to all your questions: http://wiki.python.org/moin/PythonEditors
There are a couple of things to check:
proceedToSecond
" into the FireBug console to see if the function gets definedscript
tag: it should be <script type="text/javascript">
instead of <script type = "text/javascript">
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
If the list you use for the spinner is an object then you can find its position like this
private int selectSpinnerValue( List<Object> ListSpinner,String myString)
{
int index = 0;
for(int i = 0; i < ListSpinner.size(); i++){
if(ListSpinner.get(i).getValueEquals().equals(myString)){
index=i;
break;
}
}
return index;
}
using:
int index=selectSpinnerValue(ListOfSpinner,StringEquals);
spinner.setSelection(index,true);
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"
if you need to append folder "ddd" by another path use;
String currentFolder= "/" + currentPath.getName().toString();
I understand this is an old post. But it is programmable. Otherwise make sure your fill is set to "No Fill" and your boarders are set to "No Boarder" via the user interface shown in the previous posts.
Sub clear()
Range("A4:G1000").Borders.LineStyle = xlNone
Range("A4:G1000").Interior.ColorIndex = xlNone
End Sub()
Well, even the SELECT COUNT(*) FROM Table
will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).
Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:
SELECT
SUM(used_page_count) * 8 AS SizeKB,
SUM(row_count) AS [RowCount],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
OBJECT_ID = OBJECT_ID('YourTableNameHere')
AND (index_id = 0 OR index_id = 1)
GROUP BY
OBJECT_ID
This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).
It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).
Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.
Marc
You can actualy fake the transparency of option
DOMElements with the following CSS:
option {
/* Whatever color you want */
background-color: #82caff;
}
The option
tag does not support rgba
colors yet.
And another useful command to do this (after git fetch) is:
git log origin/master ^master
This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.
I also experienced the same thing. I found out that my favicon.ico had not been processed as a legitimate shortcut icon. I understand that favicons must be scaled to 16x16 and follow the Microsoft Icon format.
You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.
Dim OutApp As Object, OutMail As Object, LogFile As String
Dim cell As Range, S As String, WMBody As String, lFile As Long
S = Environ("appdata") & "\Microsoft\Signatures\"
If Dir(S, vbDirectory) <> vbNullString Then S = S & Dir$(S & "*.htm") Else S = ""
S = CreateObject("Scripting.FileSystemObject").GetFile(S).OpenAsTextStream(1, -2).ReadAll
WMBody = "<br>Hi All,<br><br>" & _
"Last line,<br><br>" & S 'Add the Signature to end of HTML Body
Just thought I'd share how I achieve this. Not too sure if it's correct in the defining variables sense but it's small and easy to read which is what I like.
I attach WMBody to .HTMLBody within the object Outlook.Application OLE.
Hope it helps someone.
Thanks, Wes.
This method works best to me:
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = this.length - 1; i >= 0; i--) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
To use it we can deploy like this:
document.getElementsByID('DIV_Id').remove();
or
document.getElementsByClassName('DIV_Class').remove();
you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):
request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
Open task manager -> Processes -> Click on .exe (Fibonacci.exe) -> End Process
if it doesn't work
Close eclipse IDE (or whatever IDE you use) and repeat step 1.
This is similar to one of the answers but in different way :
scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)
scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)
XmlGrid.net has tool to convert csv to html table. Here is the link: http://xmlgrid.net/csvToHtml.html
I used your sample data, and got the following html table:
<table>
<!--Created with XmlGrid Free Online XML Editor (http://xmlgrid.net)-->
<tr>
<td>Name</td>
<td> Age</td>
<td> Sex</td>
</tr>
<tr>
<td>Cantor, Georg</td>
<td> 163</td>
<td> M</td>
</tr>
</table>
Actually, there are three ways to do it, precisely.
Type any of the following 3 commands.
P.S.: Sometimes, for someone, one of these options doesn't seem to work and for others it works.
One important thing to mention as well is the security improvement that comes with the package-lock file. Since it keeps all the hashes of the packages if someone would tamper with the public npm registry and change the source code of a package without even changing the version of the package itself it would be detected by the package-lock file.
From roseindia:
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor("alert.gif");
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
Try this very simple way
example givenString="ram is good boy"
public static String toTitleCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
Output will be: Ram Is Good Boy
to pass many options you can pass a object to a @Input decorator with custom data in a single line.
In the template
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
(selectedOption) = 'onOptionSelection($event)' >
{{opt.option}}
</li>
so in Directive class
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('myOptions') data;
//do something with data.first
...
// do something with data.second
}
String is immutable, meaning that when you perform an operation on a String you are really creating a whole new String.
StringBuffer is mutable, and you can append to it as well as reset its length to 0.
In practice, the compiler seems to use StringBuffer during String concatenation for performance reasons.
If you are working with ASP.NET MVC, you can solve the problem by adding the MaxJsonLength to your result:
var jsonResult = Json(new
{
draw = param.Draw,
recordsTotal = count,
recordsFiltered = count,
data = result
}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
You can have solution of this problem with help of only one extra pointer, that has to be static for the reverse function. It's in O(n) complexity.
#include<stdio.h>
#include<stdlib.h>
typedef struct List* List;
struct List {
int val;
List next;
};
List reverse(List list) { /* with recursion and one static variable*/
static List tail;
if(!list || !list->next) {
tail = list;
return tail;
} else {
reverse1(list->next);
list->next->next = list;
list->next = NULL;
return tail;
}
}
Unfortunately this answer is probably of little or no help whatsoever, but I did a forensics analysis of the Java Lambda Mailing list to see if I could find the cause of this design. This is what I found out.
In the beginning there was an instance method for Stream.concat(Stream)
In the mailing list I can clearly see the method was originally implemented as an instance method, as you can read in this thread by Paul Sandoz, about the concat operation.
In it they discuss the issues that could arise from those cases in which the stream could be infinite and what concatenation would mean in those cases, but I do not think that was the reason for the modification.
You see in this other thread that some early users of the JDK 8 questioned about the behavior of the concat instance method when used with null arguments.
This other thread reveals, though, that the design of the concat method was under discussion.
Refactored to Streams.concat(Stream,Stream)
But without any explanation, suddenly, the methods were changed to static methods, as you can see in this thread about combining streams. This is perhaps the only mail thread that sheds a bit of light about this change, but it was not clear enough for me to determine the reason for the refactoring. But we can see they did a commit in which they suggested to move the concat
method out of Stream
and into the helper class Streams
.
Refactored to Stream.concat(Stream,Stream)
Later, it was moved again from Streams
to Stream
, but yet again, no explanation for that.
So, bottom line, the reason for the design is not entirely clear for me and I could not find a good explanation. I guess you could still ask the question in the mailing list.
Some Alternatives for Stream Concatenation
This other thread by Michael Hixson discusses/asks about other ways to combine/concat streams
To combine two streams, I should do this:
Stream.concat(s1, s2)
not this:
Stream.of(s1, s2).flatMap(x -> x)
... right?
To combine more than two streams, I should do this:
Stream.of(s1, s2, s3, ...).flatMap(x -> x)
not this:
Stream.of(s1, s2, s3, ...).reduce(Stream.empty(), Stream::concat)
... right?
First mv -f /var/lib/mysql /var/lib/mysql.bak
and try the command mysql_install_db --user=mysql --ldata=[destination]
replace the destination with the data directory, after that start the MySQL with /etc/init.d/mysql restart
Old question, but none of the above solutions worked for me. What did work was to close eclipse, then using Tortoise, right click on the project in Windows Explorer and choose 'TortoiseSVN' -> 'Clean up', then just use the default checkboxed items (Clean up working copy status, include externals), then hit OK.
This cleaned up the folder, then I was able to update and commit files as normal.
I keep this answer which is useful for other cases, but @trutheality answer seems to be the most simple and direct way.
You can use DateFormatSymbols
DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example
For Windows users, the following helped me a lot to understand some memory limitations:
gc()
to do garbage collection => it works, I can see the memory use go down to 2 GBAdditional advice that works on my machine:
A quick and easy way for Mac OS X 10.8 (Mountain Lion), 10.9 (Mavericks), 10.10 (Yosemite), and 10.11 (El Capitan):
I assume you have XCode, its command line tools, Python, and MySQL installed.
Install PIP:
sudo easy_install pip
Edit ~/.profile: (Might not be necessary in Mac OS X 10.10)
nano ~/.profile
Copy and paste the following two line
export PATH=/usr/local/mysql/bin:$PATH
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
Save and exit. Afterwords execute the following command:
source ~/.profile
Install MySQLdb
sudo pip install MySQL-python
To test if everything works fine just try
python -c "import MySQLdb"
It worked like a charm for me. I hope it helps.
If you encounter an error regarding a missing library: Library not loaded: libmysqlclient.18.dylib then you have to symlink it to /usr/lib
like so:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
You can use:
SELECT USER();
or
SELECT CURRENT_USER();
See more here http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
To change the Android-x86 screen resolution on VirtualBox you need to:
Add custom screen resolution:
Android <6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x16"
Android >=6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"
Figure out what is the ‘hex’-value for your VideoMode
:
2.1. Start the VM
2.2. In GRUB menu enter a (Android >=6.0: e)
2.3. In the next screen append vga=ask
and press Enter
2.4. Find your resolution and write down/remember the 'hex'-value for Mode
column
Translate the value to decimal notation (for example 360
hex is 864
in decimal).
Go to menu.lst
and modify it:
4.1. From the GRUB menu select Debug Mode
4.2. Input the following:
mount -o remount,rw /mnt
cd /mnt/grub
vi menu.lst
4.3. Add vga=864
(if your ‘hex’-value is 360
). Now it should look like this:
kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode DPI=160 UVESA_MODE=320x480 SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img vga=864
4.4. Save it:
:wq
Unmount and reboot:
cd /
umount /mnt
reboot -f
Hope this helps.
Previous answers missed this addition: a generator has a close
method, while typical iterators don’t. The close
method triggers a StopIteration
exception in the generator, which may be caught in a finally
clause in that iterator, to get a chance to run some clean-up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.
That said, my personal answer to the first question would be: iteratable has an __iter__
method only, typical iterators have a __next__
method only, generators has both an __iter__
and a __next__
and an additional close
.
For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close
method an a greater composability with yield from
. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.
For control flow matters, generators are an as much important concept as promises: both are abstract and composable.
You can achieve that by redirecting the form's action
to an invisible <iframe>
. It doesn't require any JavaScript or any other type of scripts.
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="submitscript.php" target="dummyframe">
<!-- Form body here -->
</form>
source URL for image can be a URL on a website like http://www.google.co.il/images/srpr/nav_logo73.png or https://https.openbsd.org/images/tshirt-26_front.gif or if you want to use a local file try this: url("file:///MacintoshHDOriginal/Users/lowri/Desktop/acgnx/image s/images/acgn-site-background-X_07.jpg")
For inner classes to pass the reference of activity, I usually create a reference of activity in onCreate() and make it as a member. As inner classes have access to members of parent class you can get hold of your activity and thus its context:
class MyClass extends Activity{
private Activity thisActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
thisActivity = this;
}
}
Hope that helps.
Put the textarea to a form, naming them, and just use the DOM objects easily, like this:
<body onload="form1.box.value = 'Welcome!'">
<form name="form1">
<textarea name="box"></textarea>
</form>
</body>
Your regular expression [^a-zA-Z0-9]\s/g
says match any character that is not a number or letter followed by a space.
Remove the \s and you should get what you are after if you want a _ for every special character.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
That will result in hello_world___hello_universe
If you want it to be single underscores use a + to match multiple
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
That will result in hello_world_hello_universe
->> Apple's own tutorial <<- is the only working set of instructions I've come across. It's straight forward and I can confirm it works brilliantly on both a linux php server and a windows php server.
You can find their 5-step pem creation process right at the bottom of the page.
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
I had the same problem after moving my Windows installation to an SSD. None of the other solutions worked for me.
My solution was to open the project file in Notepad and remove all references to PFX keys. Once the file is saved, open the solution in Visual Studio. Go to project -> Properties -> Signing. You shouldn't see any keys listed in the 'choose the strong name key file' combo box. In the combo box, browse to the key, select it and your project can now be built.
The following helped me in Win10.
%M3_HOME%\bin;
as value for Path variable under User Variables.M3_HOME
variable under System Variables.%M3_HOME%\bin;
as value for Path variable under System Variables.mvn -version
It will work.
There is no need to either call non-portable APIs like sendfile
, or shell out to external utilities. The same method that worked back in the 70s still works now:
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int cp(const char *to, const char *from)
{
int fd_to, fd_from;
char buf[4096];
ssize_t nread;
int saved_errno;
fd_from = open(from, O_RDONLY);
if (fd_from < 0)
return -1;
fd_to = open(to, O_WRONLY | O_CREAT | O_EXCL, 0666);
if (fd_to < 0)
goto out_error;
while (nread = read(fd_from, buf, sizeof buf), nread > 0)
{
char *out_ptr = buf;
ssize_t nwritten;
do {
nwritten = write(fd_to, out_ptr, nread);
if (nwritten >= 0)
{
nread -= nwritten;
out_ptr += nwritten;
}
else if (errno != EINTR)
{
goto out_error;
}
} while (nread > 0);
}
if (nread == 0)
{
if (close(fd_to) < 0)
{
fd_to = -1;
goto out_error;
}
close(fd_from);
/* Success! */
return 0;
}
out_error:
saved_errno = errno;
close(fd_from);
if (fd_to >= 0)
close(fd_to);
errno = saved_errno;
return -1;
}
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
@gnarf answer is right . wanted to add more information .
Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader
I too had the same problem.
I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.
Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2
This worked for me:
1-
$ npm install -g n
$ n 9.11.2
2-
delete 'node_modules' from the route directory
3-
$ npm install
Still not sure how node/purgecss worked prior to updating.. but this did the trick.
$("#date").datepicker('getDate').getMonth() + 1;
The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.
Member functions that do not modify the class instance should be declared as const
:
int getId() const {
return id;
}
string getName() const {
return name;
}
Anytime you see "discards qualifiers", it's talking about const
or volatile
.
This may help you:
CREATE TABLE "custinf"
(
"CUST_ID" INT not null primary key
GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
"FNAME" VARCHAR(50),
"LNAME" VARCHAR(50),
"ADDR" VARCHAR(100),
"SUBURB" VARCHAR(20),
"PCODE" INTEGER,
"PHONE" INTEGER,
"MOB" INTEGER,
"EMAIL" VARCHAR(100),
"COMM" VARCHAR(450)
);
That's how i got mine to work... to ages to get the frigging thing to actually understand me but that's the nature of code :D
BTW!- There is a way to do it in the ide interface goto the services window, expand your connection, expand your projects name, expand tables, right click indexes and select add index... the rest of the process speaks for itself really...
Try gcc -c -I/home/me/development/skia sample.c
.
You are missing 'json' dataType in the $.post()
method:
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
.done(function(data){
alert(data);
}, "json");
//-^^^^^^-------here
Updates:
try with this:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
Easy Difference,
Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.
Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again. you can create object of class but that object will not have different x in them. if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.
Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.
"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so Class A has x =5, i can call and change it by A.x=6; "
I will add my answer since I don't use any of the other answers provided.
With the Support Library v7, all the styles are actually already defined and ready to use, for the standard buttons, all of these styles are available:
style="@style/Widget.AppCompat.Button"
style="@style/Widget.AppCompat.Button.Colored"
style="@style/Widget.AppCompat.Button.Borderless"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
Widget.AppCompat.Button.Colored
:
Widget.AppCompat.Button.Borderless
Widget.AppCompat.Button.Borderless.Colored
:
To answer the question, the style to use is therefore
<Button style="@style/Widget.AppCompat.Button.Colored"
.......
.......
.......
android:text="Button"/>
For the whole app:
The color of all the UI controls (not only buttons, but also floating action buttons, checkboxes etc.) is managed by the attribute colorAccent
as explained here.
You can modify this style and apply your own color in your theme definition:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
<item name="colorAccent">@color/Orange</item>
</style>
For a specific button:
If you need to change the style of a specific button, you can define a new style, inheriting one of the parent styles described above. In the example below I just changed the background and font colors:
<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
<item name="colorButtonNormal">@color/Red</item>
<item name="android:textColor">@color/White</item>
</style>
Then you just need to apply this new style on the button with:
android:theme="@style/AppTheme.Button"
To set a default button design in a layout, add this line to the styles.xml theme:
<item name="buttonStyle">@style/btn</item>
where @style/btn
is your button theme. This sets the button style for all the buttons in a layout with a specific theme
To see database name, startup;
then type show parameter db_name;
setSize
will resize the component to the specified size.
setPreferredSize
sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
Here is good article about unit testing of private methods. But I'm not sure what's better, to make you application designed specially for testing(it's like creating tests for testing only) or use reflexion for testing. Pretty sure most of us will choose second way.
The problem is clear: circular dependency between names in entity
and physics
modules.
Regardless of importing the whole module or just a class, the names must be loaded .
Watch this example:
# a.py
import b
def foo():
pass
b.bar()
# b.py
import a
def bar():
pass
a.foo()
This will be compiled into:
# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
pass
b.bar()
# done!
With one slight change we can solve this:
# a.py
def foo():
pass
import b
b.bar()
# b.py
def bar():
pass
import a
a.foo()
This will be compiled into:
# a.py
def foo():
pass
# import b
# b.py
def bar():
pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!
{% with ''|center:n as range %}
{% for _ in range %}
{{ forloop.counter }}
{% endfor %}
{% endwith %}
In my case a dependency was missing in the dll that threw this exception. I checked with Dependency Walker, added the missing dll and the problem was resolved.
More specifically, I somehow corrupted my opencv_core340.dll by accidentally adding SVN keywords to it, and thus my dll could no longer use it. However I don't believe that the solution to this problem depends on whether the dll is corrupted or missing. I'm just adding this for the sake of giving complete information.
A number of things can cause session state to mysteriously disappear.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
I had that problem too...turns out my credit card info on file needed updated to my new expiration date.
These instructions came from troubleshooting on my phone.
On a computer (not tablet or phone) sign into your Google Wallet, click Payment Methods then edit to edit info. Hope it works for you too!
To fully comply with RSpec ~> 3.1 syntax and rubocop-rspec
's default option for rule RSpec/MessageSpies
, here's what you can do with spy
:
Message expectations put an example's expectation at the start, before you've invoked the code-under-test. Many developers prefer using an arrange-act-assert (or given-when-then) pattern for structuring tests. Spies are an alternate type of test double that support this pattern by allowing you to expect that a message has been received after the fact, using have_received.
# arrange.
invitation = spy('invitation')
# act.
invitation.deliver("[email protected]")
# assert.
expect(invitation).to have_received(:deliver).with("[email protected]")
If you don't use rubocop-rspec or using non-default option. You may, of course, use RSpec 3 default with expect.
dbl = double("Some Collaborator")
expect(dbl).to receive(:foo).with("[email protected]")
As drawn from http://php.net/ && Chipmunkninja:
The system() Function
The system function in PHP takes a string argument with the command to execute as well as any arguments you wish passed to that command. This function executes the specified command, and dumps any resulting text to the output stream (either the HTTP output in a web server situation, or the console if you are running PHP as a command line tool). The return of this function is the last line of output from the program, if it emits text output.
The exec() Function
The system function is quite useful and powerful, but one of the biggest problems with it is that all resulting text from the program goes directly to the output stream. There will be situations where you might like to format the resulting text and display it in some different way, or not display it at all.
For this, the exec function in PHP is perfectly adapted. Instead of automatically dumping all text generated by the program being executed to the output stream, it gives you the opportunity to put this text in an array returned in the second parameter to the function:
The shell_exec() Function
Most of the programs we have been executing thus far have been, more or less, real programs1. However, the environment in which Windows and Unix users operate is actually much richer than this. Windows users have the option of using the Windows Command Prompt program, cmd.exe This program is known as a command shell.
The passthru() Function
One fascinating function that PHP provides similar to those we have seen so far is the passthru function. This function, like the others, executes the program you tell it to. However, it then proceeds to immediately send the raw output from this program to the output stream with which PHP is currently working (i.e. either HTTP in a web server scenario, or the shell in a command line version of PHP).
The proc_open() Function and popen() function
proc_open() is similar to popen() but provides a much greater degree of control over the program execution. cmd is the command to be executed by the shell. descriptorspec is an indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. pipes will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created. The return value is a resource representing the process; you should free it using proc_close() when you are finished with it.
After trying and reading carefully, I solved it myself. Solution is to add the following line in build.gradle.
flavorDimensions "versionCode"
android {
compileSdkVersion 24
.....
flavorDimensions "versionCode"
}
If you are using a dbproj in your solution you will want to add the following:
#Visual Studio DB Project
*.dbmdl
[Ss]ql/
char *s does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;
This would not lead to segmentation fault error as you will not be refering to an unknown location anymore
Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge
. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control
.
Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.
I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!
1-check your security groups
2-check internet gateway
3-check route tables
The Dev Tools in Edge finally added support for managing and browsing cookies.
Note: Even if you are testing and supporting IE targets, you mine as well do the heavy lifting of your browser compatibility testing by leveraging the new tooling in Edge, and defer checking in IE 11 (etc) for the last leg.
The benefit, of course, to the debugger tab is you don't have to hunt and peck for individual cookies across multiple different and historical requests.
This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).
Anyway, I hope that helps =D
Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
once you do that you can save the line into a variable and manipulate the contents.
from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
df.head()
This tutorial maybe of interest: http://www.neural.cz/dataset-exploration-boston-house-pricing.html
For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.
These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.
If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).
This works for me:
if(!driver.findElements(By.xpath("//*[@id='submit']")).isEmpty()){
//THEN CLICK ON THE SUBMIT BUTTON
}else{
//DO SOMETHING ELSE AS SUBMIT BUTTON IS NOT THERE
}
The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.
This code is also working:
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<table style="table-layout:fixed;">_x000D_
<tr>_x000D_
<td style="word-break: break-all; width:100px;">ThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrapThisStringWillNotWrap</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body></html>
_x000D_
Even better use implicit remoting to use a module from another Machine!
$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM
This will allow you to use the module off a remote PC for as long as the PSSession is connected.
More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx
If you want the result as the nearest binary floating point number use float
:
result = [float(x.strip(' "')) for x in A1]
If you want the result stored exactly use Decimal
instead of float
:
from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]
Here's a short and ugly way to do search file names using the AWS CLI:
aws s3 ls s3://your-bucket --recursive | grep your-search | cut -c 32-
This answer will be for swift dictionary w/ String keys. Like this one below.
let dict: [String: Int] = ["hey": 1, "yo": 2, "sup": 3, "hello": 4, "whassup": 5]
Here's the extension I'll use.
extension Dictionary {
func allKeys() -> [String] {
guard self.keys.first is String else {
debugPrint("This function will not return other hashable types. (Only strings)")
return []
}
return self.flatMap { (anEntry) -> String? in
guard let temp = anEntry.key as? String else { return nil }
return temp }
}
}
And I'll get all the keys later using this.
let componentsArray = dict.allKeys()
Only Files
Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Only Folders
Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Both
Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
You can also use -match against a Regular expression. Ex:
if ($dbUserName -match ".{8}" )
{
Write-Output " Please enter more than 8 characters "
$dbUserName=read-host " Re-enter database user name"
}
Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.
require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')
One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:
f $ x = f x
and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4+)
analogous to (++", world") "hello"
.
Why would anyone do this? For lists of functions, for example. Both:
map (++", world") ["hello","goodbye"]`
and:
map ($ 3) [(4+),(3*)]
are shorter than map (\x -> x ++ ", world") ...
or map (\f -> f 3) ...
. Obviously, the latter variants would be more readable for most people.
A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:
# Search for entry.
for x in y:
if x == 3:
found = x
# Work with found entry.
try:
print('Found: {0}'.format(found))
except NameError:
print('Not found')
else:
# Handle rest of Found case here
...
Both of the options you provided are the same. Both of them will still point to the same object in memory and have the same array values. You should treat the state object as immutable as you said, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state. Example:
onChange(event){
var newArray = this.state.arr.slice();
newArray.push("new value");
this.setState({arr:newArray})
}
I simply use
git fetch origin
to fetch the remote changes, and then I view both local and pending remote commits (and their associated changes) with the nice gitk tool involving the --all
argument like:
gitk --all
You could do
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text (note the apostrophe as the first character).
The [A1].Value
is VBA shorthand for Range("A1").Value
.
If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")
There is "sprintf" for JavaScript which you can find at http://www.webtoolkit.info/javascript-sprintf.html.
From the documentation:
/is
Includes the same files./it
Includes "tweaked" files.
"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.
robocopy src dst sample.txt /is # copy if attributes are equal
robocopy src dst sample.txt /it # copy if attributes differ
robocopy src dst sample.txt /is /it # copy irrespective of attributes
This answer on Super User has a good explanation of what kind of files the selection parameters match.
With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy
generated in my tests I would consider this a bug.
PS C:\temp> New-Item src -Type Directory >$null PS C:\temp> New-Item dst -Type Directory >$null PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00" PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Modified 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ Same 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\src\sample.txt test001 PS C:\temp> Get-Content .\dst\sample.txt test002
The file is listed as copied, and since it becomes a same file after the first robocopy
run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall
). The behavior also doesn't change if the data flag is set explicitly (/copy:d
).
I had to modify the last write time to get robocopy
to actually synchronize the data.
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date) PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir ... Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30 ------------------------------------------------------------------------------ 1 C:\temp\src\ 100% Newer 7 sample.txt ------------------------------------------------------------------------------ Total Copied Skipped Mismatch FAILED Extras Dirs : 1 0 0 0 0 0 Files : 1 1 0 0 0 0 Bytes : 7 7 0 0 0 0 ... PS C:\temp> Get-Content .\dst\sample.txt test001
An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy
to copy the data:
& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
Where-Object { $_.Trim() } |
ForEach-Object {
$f = Get-Item $_
$f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
}
& robocopy src dst /copyall /mir
Switching to xcopy
is probably your best option:
& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y
The difference between factory and service is just like the difference between a function and an object
Factory Provider
Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Factory are a great way for communicating between controllers like sharing data.
Can use other dependencies
Usually used when the service instance requires complex creation logic
Cannot be injected in .config()
function.
Used for non configurable services
If you're using an object, you could use the factory provider.
Syntax: module.factory('factoryName', function);
Service Provider
Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Services are used for communication between controllers to share data
You can add properties and functions to a service object by using the this
keyword
Dependencies are injected as constructor arguments
Used for simple creation logic
Cannot be injected in .config()
function.
If you're using a class you could use the service provider
Syntax: module.service(‘serviceName’, function);
In below example I have define MyService
and MyFactory
. Note how in .service
I have created the service methods using this.methodname.
In .factory
I have created a factory object and assigned the methods to it.
AngularJS .service
module.service('MyService', function() {
this.method1 = function() {
//..method1 logic
}
this.method2 = function() {
//..method2 logic
}
});
AngularJS .factory
module.factory('MyFactory', function() {
var factory = {};
factory.method1 = function() {
//..method1 logic
}
factory.method2 = function() {
//..method2 logic
}
return factory;
});
Also Take a look at this beautiful stuffs
Confused about service vs factory
import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS
class Worker(object):
def __init__(self, img):
self.img = img
self.exif_data = self.get_exif_data()
self.lat = self.get_lat()
self.lon = self.get_lon()
self.date =self.get_date_time()
super(Worker, self).__init__()
@staticmethod
def get_if_exist(data, key):
if key in data:
return data[key]
return None
@staticmethod
def convert_to_degress(value):
"""Helper function to convert the GPS coordinates
stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0)
def get_exif_data(self):
"""Returns a dictionary from the exif data of an PIL Image item. Also
converts the GPS Tags"""
exif_data = {}
info = self.img._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data
def get_lat(self):
"""Returns the latitude and longitude, if available, from the
provided exif_data (obtained through get_exif_data above)"""
# print(exif_data)
if 'GPSInfo' in self.exif_data:
gps_info = self.exif_data["GPSInfo"]
gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
if gps_latitude and gps_latitude_ref:
lat = self.convert_to_degress(gps_latitude)
if gps_latitude_ref != "N":
lat = 0 - lat
lat = str(f"{lat:.{5}f}")
return lat
else:
return None
def get_lon(self):
"""Returns the latitude and longitude, if available, from the
provided exif_data (obtained through get_exif_data above)"""
# print(exif_data)
if 'GPSInfo' in self.exif_data:
gps_info = self.exif_data["GPSInfo"]
gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
if gps_longitude and gps_longitude_ref:
lon = self.convert_to_degress(gps_longitude)
if gps_longitude_ref != "E":
lon = 0 - lon
lon = str(f"{lon:.{5}f}")
return lon
else:
return None
def get_date_time(self):
if 'DateTime' in self.exif_data:
date_and_time = self.exif_data['DateTime']
return date_and_time
if __name__ == '__main__':
try:
img = PILimage.open(sys.argv[1])
image = Worker(img)
lat = image.lat
lon = image.lon
date = image.date
print(date, lat, lon)
except Exception as e:
print(e)
In general you want to program against an interface. This allows you to exchange the implementation at any time. This is very useful especially when you get passed an implementation you don't know.
However, there are certain situations where you prefer to use the concrete implementation. For example when serialize in GWT.
You can use the password_verify function with the PHP. It verifies that a password matches with the hash
password_verify ( string $password , string $hash ) : bool
more details: https://www.php.net/manual/en/function.password-verify.php
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.
Something like this?
for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
Just created this:
https://gist.github.com/3854049
//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");
//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
Throwable
is super class of Exception
as well as Error
. In normal cases we should always catch sub-classes of Exception
, so that the root cause doesn't get lost.
Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error
or Throwable
.
I remember catching Throwable to flag that a native library is not loaded.
I find that when I include a blank line in my source after the \\ then I also get a blank line in my output. Example:
It's time to recognize the income tax as another horrible policy mistake like banning beer, and to return to the tax policies that were correct in the Constitution in the first place. Our future depends on it.
\\
Wherefore the 16th Amendment must forthwith be repealed.
However you are correct that LaTeX only lets you do this once. For a more general solution allowing you to make as many blank lines as you want, use \null to make empty paragraphs. Example:
It's time to recognize the income tax as another horrible policy mistake like banning beer, and to return to the tax policies that were correct in the Constitution in the first place. Our future depends on it.
\null
\null
\null
Wherefore the 16th Amendment must forthwith be repealed.
Use the --sort=-committerdate
option of git for-each-ref
;
Also available since Git 2.7.0 for git branch
:
git for-each-ref --sort=-committerdate refs/heads/
# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate # DESC
git branch --sort=committerdate # ASC
git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
If you need to make a comparison between a class and a known type, for example:
class Example{};
...
Example eg = Example();
You can use this comparison line:
bool isType = string( typeid(eg).name() ).find("Example") != string::npos;
which checks the typeid
name contains the string type (the typeid name has other mangled data, so its best to do a s1.find(s2)
instead of ==
).
Dictionary: A python dictionary is used like a hash table with key as index and object as value.
List: A list is used for holding objects in an array indexed by position of that object in the array.
Set: A set is a collection with functions that can tell if an object is present or not present in the set.
Take an example
<root>
<parent>
<child_one>Y</child_one>
<child_two>12</child_two>
</parent>
</root>
and design an xsd for that:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="parent">
<xs:complexType>
<xs:sequence>
<xs:element name="child_one" type="xs:string" />
<xs:element name="child_two" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
What isn't possible with XSD: would like to write it first as the list is very small
1) You can't validate a node/attribute using the value of another node/attribute.
2) This is a restriction : An element defined in XSD file must be defined with only one datatype. [in the above example, for <child_two>
appearing in another <parent>
node, datatype cannot be defined other than int.
3) You can't ignore the validation of elements and attributes, ie, if an element/attribute appears in XML, it must be well-defined in the corresponding XSD. Though usage of <xsd:any>
allows it, but it has got its own rules. Abiding which leads to the validation error. I had tried for a similar approach, and certainly wasn't successful, here is the Q&A
what are possible with XSD:
1) You can test the proper hierarchy of the XML nodes. [xsd defines which child should come under which parent, etc, abiding which will be counted as error, in above example, child_two cannot be the immediate child of root, but it is the child of "parent" tag which is in-turn a child of "root" node, there is a hierarchy..]
2) You can define Data type of the values of the nodes. [in above example child_two cannot have any-other data than number]
3) You can also define custom data_types, [example, for node <month>
, the possible data can be one of the 12 months.. so you need to define all the 12 months in a new data type writing all the 12 month names as enumeration values .. validation shows error if the input XML contains any-other value than these 12 values .. ]
4) You can put the restriction on the occurrence of the elements, using minOccurs and maxOccurs, the default values are 1 and 1.
.. and many more ...
You can't close an alert box with Javascript.
You could, however, use a window instead:
var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)
Use numpy. array. flatten() to convert a 2D NumPy array into a 1D array
print(array_2d)
array_1d = array_2d. flatten() flatten array_2d
print(array_1d)
You can go to fullscreen when user allows it :)
<button id="goFS">Go fullscreen</button>
<script>
var goFS = document.getElementById("goFS");
goFS.addEventListener("click", function() {
const elem = document.documentElement;
if (elem.requestFullscreen) {elem.requestFullscreen()}
}, false);
</script>
if you want to compute differences between two known dates, use total_seconds
like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0
#note that seconds doesn't give you what you want:
(b-a).seconds
0
Instead of putting in root folder as given in docs of firebase, just copy the google-json file in the projectname/app 's root folder and it works fine then . Its just simple !
Python doesn't have builtin unsigned types. You can use mathematical operations to compute a new int representing the value you would get in C, but there is no "unsigned value" of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.
You can use nslookup
on the IP. Reverse DNS is defined with the .in-addr.arpa
domain.
Example:
nslookup somedomain.com
yields 123.21.2.3
, and then you do:
nslookup 123.21.2.3
this will ask 3.2.21.123.in-addr.arpa
and yield the domain name (if there is one defined for reverse DNS).
$name = str_replace(' ', '_', $name);
Also; auto it = std::next(v.begin(), index);
Update: Needs a C++11x compliant compiler
in laravel 4
you just have to paste {{ URL::asset('/') }}
this way:
<link rel="stylesheet" href="{{ URL::asset('/') }}css/app.css" />.
It is the same for:
<script language="JavaScript" src="{{ URL::asset('/') }}js/jquery.js"></script>
<img src="{{ URL::asset('/') }}img/image.gif">
Have you looked in firebug if POST or GET?.
check the console display.
Put in the test script:
console.log(data);
You can see the response from the server, if it shows something.
For offline Javadoc from zip file rather than extracting it.
This is already answered which uses extracted zip data but it consumes more memory than simple zip file.
Comparison of zip file and extracted data.
jdk-6u25-fcs-bin-b04-apidocs.zip ---> ~57 MB
after extracting this zip file ---> ~264 MB !
So this approach saves my approx. 200 MB.
1.Open
Windows -> Preferences
2.Select
jre
fromInstalled JREs
then ClickEdit...
3.Select all
.jar
files fromJRE system libraries
then ClickJavadoc Location...
4.Browse for
apidocs.zip
file forArchive path
and setPath within archive
as shown above. That's it.5.Put cursor on any class name or method name and hit Shift + F2
In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column
import pandas as pd
import numpy as np
e = np.random.normal(size=100)
e_dataframe = pd.DataFrame(e)
e_dataframe.rename(index=str, columns={0:'new_column_name'})
The most direct solution is this:
s = set(filelist)
The issue in your original code is that the values weren't being assigned to the set. Here's the fixed-up version of your code:
s = set()
for filename in filelist:
s.add(filename)
print(s)
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
if you can't or don't want to set the autoincrement property of the id, you can set value for the id for each row, like this:
INSERT INTO role (id, name, created)
SELECT
(select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
, name
, created
FROM (
VALUES
('Content Coordinator', GETDATE())
, ('Content Viewer', GETDATE())
) AS x(name, created)
base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z
, a-z
, 0-9
, +
, /
* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.
Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b''
syntax.
If you remove the b
, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)
In your second example:
>>> encoded = base64.b64encode('data to be encoded')
All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with
>>> encoded = 'data to be encoded'.encode('ascii')
Or simpler:
>>> encoded = b'data to be encoded'
Which would be the same thing in this case.
* Most base64 flavours may also include a =
at the end as padding. In addition, some base64 variants may use characters other than +
and /
. See the Variants summary table at Wikipedia for an overview.
You can clear the whole form using onclick function.Here is the code for it.
<button type="reset" value="reset" type="reset" class="btnreset" onclick="window.location.reload()">Reset</button>
window.location.reload() function will refresh your page and all data will clear.
Use HttpClient to grab the contents of the URL. And then use the library from json.org to parse the JSON. I've used these two libraries on many projects and they have been robust and simple to use.
Other than that you can try using a Facebook API java library. I don't have any experience in this area, but there is a question on stack overflow related to using a Facebook API in java. You may want to look at RestFB as a good choice for a library to use.
A simple solution is to set the spring bean in the Job Data Map and then retrieve the bean in the job class, for instance
// the class sets the configures the MyJob class
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
Date startTime = DateBuilder.nextGivenSecondDate(null, 15);
JobDetail job = newJob(MyJob.class).withIdentity("job1", "group1").build();
job.getJobDataMap().put("processDataDAO", processDataDAO);
`
// this is MyJob Class
ProcessDataDAO processDataDAO = (ProcessDataDAO) jec.getMergedJobDataMap().get("processDataDAO");
This is working for IE/Netscape/Chrome :
function ClearAuthentication(LogOffPage)
{
var IsInternetExplorer = false;
try
{
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
}
catch(e)
{
IsInternetExplorer = false;
};
if (IsInternetExplorer)
{
// Logoff Internet Explorer
document.execCommand("ClearAuthenticationCache");
window.location = LogOffPage;
}
else
{
// Logoff every other browsers
$.ajax({
username: 'unknown',
password: 'WrongPassword',
url: './cgi-bin/PrimoCgi',
type: 'GET',
beforeSend: function(xhr)
{
xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
},
error: function(err)
{
window.location = LogOffPage;
}
});
}
}
$(document).ready(function ()
{
$('#Btn1').click(function ()
{
// Call Clear Authentication
ClearAuthentication("force_logout.html");
});
});
simple:
myArray.indexOf(myArray.filter(function(item) {
return item.hello == "stevie"
})[0])
I copied a small sub project I had that was under Git source control into another project and forgot to delete the .git folder. When I went to commit I got the same message as above and couldn't clear it until I deleted the .git
folder.
It is a bit silly, but it is worth checking you don't have a .git folder under the folder that doesn't commit.
Java 8 alternative one-liner for merging two maps:
defaultMap.forEach((k, v) -> destMap.putIfAbsent(k, v));
The same with method reference:
defaultMap.forEach(destMap::putIfAbsent);
Or idemponent for original maps solution with third map:
Map<String, Integer> map3 = new HashMap<String, Integer>(map2);
map1.forEach(map3::putIfAbsent);
And here is a way to merge two maps into fast immutable one with Guava that does least possible intermediate copy operations:
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.<String, Integer>builder();
builder.putAll(map1);
map2.forEach((k, v) -> {if (!map1.containsKey(k)) builder.put(k, v);});
ImmutableMap<String, Integer> map3 = builder.build();
See also Merge two maps with Java 8 for cases when values present in both maps need to be combined with mapping function.
Ubuntu 18.04
Install and ensure mysqld us running..
Go into database and setup root user:
sudo mysql -u root
SELECT User,Host FROM mysql.user;
DROP USER 'root'@'localhost';
CREATE USER 'root'@'%' IDENTIFIED BY 'obamathelongleggedmacdaddy';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;
Edit mysqld permissions and restart:
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
# edit the line to be this:
bind-address=0.0.0.0
sudo systemctl stop mysql
sudo systemctl start mysql
From another machine, test.. Obvs port (3306) on mysqld machine must allow connection from test machine.
mysql -u root -p -h 123.456.789.666
All the additional "security" of MySql doesn't help security at all, it just complicates and obfuscates, it is now actually easier to screw it up than in the old days, where you just used a really long password.
The issue is quite simple: one or more of the columns in the source query contains data that exceeds the length of its destination column. A simple solution would be to take your source query and execute Max(Len( source col ))
on each column. I.e.,
Select Max(Len(TextCol1))
, Max(Len(TextCol2))
, Max(Len(TextCol3))
, ...
From ...
Then compare those lengths to the data type lengths in your destination table. At least one, exceeds its destination column length.
If you are absolutely positive that this should not be the case and do not care if it is not the case, then another solution is to forcibly cast the source query columns to their destination length (which will truncate any data that is too long):
Select Cast(TextCol1 As varchar(...))
, Cast(TextCol2 As varchar(...))
, Cast(TextCol3 As varchar(...))
, ...
From ...
A production quality program should use one of the many logging alternatives (e.g. log4j, logback, java.util.logging) to report errors and other diagnostics. This has a number of advantages:
By contrast, if you just use printStackTrace, the deployer / end user has little if any control, and logging messages are liable to either be lost or shown to the end user in inappropriate circumstances. (And nothing terrifies a timid user more than a random stack trace.)
Report Manager has been around for quite a few years. It's written in Delphi (at least it was originally) and has components that can be used in Delphi, but is usable via ActiveX or dll from just about any language. Now has a native .NET library too. Has a nifty report-serving webserver you can set up too. The designer gui looks and feels a little rough around the edges but it works. http://reportman.sourceforge.net/
Some colleague of mine had good experience with Learn You a Haskell for Great Good!.
Tutorial aimed at people who have experience in imperative programming languages but haven't programmed in a functional language before.
And check the answers here too
Use the constructor which takes an int ("capacity") as an argument:
List<string> = new List<string>(10);
EDIT: I should add that I agree with Frederik. You are using the List in a way that goes against the entire reasoning behind using it in the first place.
EDIT2:
EDIT 2: What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.
Why would anyone need to know the size of a List with all null values? If there are no real values in the list, I would expect the length to be 0. Anyhow, the fact that this is cludgy demonstrates that it is going against the intended use of the class.