To install all currently supported python versions (python 3.6 is already pre-installed) including pip for Ubuntu 18.04 do the following:
To install python3.5 and python3.7, use the deadsnakes ppa:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5
sudo apt-get install python3.7
Install python2.7 via distribution packages:
sudo apt install python-minimal # on Ubuntu 18.04 python-minimal maps to python2.7
To install pip use:
sudo apt install python-pip # on Ubuntu 18.04 this refers to pip for python2.7
sudo apt install python3-pip # on Ubuntu 18.04 this refers to pip for python3.6
python3.5 -m pip install pip # this will install pip only for the current user
python3.7 -m pip install pip
I used it for setting up a CI-chain for a python project with tox and Jenkins.
In MacOS, a simple way is to use Sublime settings and bindings.
Navigate to VS Code.
Click on Help -> Welcome
On the top right, you can find Customise section and in that click on Sublime.
Bingo. Done.
Reload VS Code and you are free to use Command
+ [
and Command
+ ]
For Apps converted from older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.
import { HttpModule } from '@angular/http';
with the new HttpClientModule import { HttpClientModule} from "@angular/common/http";
Note: Be sure to then update the modules imports[]
array by removing the old HttpModule
and replacing it with the new HttpClientModule
.import { Http } from '@angular/http';
with the new HttpClient import { HttpClient } from '@angular/common/http';
Update how you handle your Http response. For example - If you have code that looks like this
http.get('people.json').subscribe((res:Response) => this.people = res.json());
The above code example will result in an error. We no longer need to parse the response, because it already comes back as JSON in the config object.
The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.
For more information please see the - Angular HttpClientModule - Official Documentation
I think I ran into the similar problem. If you started a local git repository but have not set up a remote git project and want to push your local project to to git project.
1) create a remote git project and note the URL of project
2) open/edit your local git project
3) in the VS terminal type: git push --set-upstream [URL of project]
docker image prune -a
Remove all unused images, not just dangling ones. Add
-f
option to force.
Local docker version: 17.09.0-ce, Git commit: afdb6d4, OS/Arch: darwin/amd64
$ docker image prune -h
Flag shorthand -h has been deprecated, please use --help
Usage: docker image prune [OPTIONS]
Remove unused images
Options:
-a, --all Remove all unused images, not just dangling ones
--filter filter Provide filter values (e.g. 'until=<timestamp>')
-f, --force Do not prompt for confirmation
--help Print usage
Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.
Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.
import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule
...
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
RouterModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MaterialModule],
Add the NUnit test adapter NuGet package to your test projects
Or install the Test Adapter Visual Studio extension. There is one for
I prefer the NuGet package, because it will be in sync with the NUnit version used by your project and will thus automatically match the version used in any build server.
Like this ? (Visual Studio Code version 0.10.11)
Fold All (Ctrl+K Ctrl+0)
Unfold All (Ctrl+K Ctrl+J)
Fold Level n (Ctrl+K Ctrl+N)
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
On OS X, choose "Document Format", and select all lines that you need format.
Then Option + Shift + F.
It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).
To do so:
"terminal.integrated.shell.windows": "cmd.exe"
"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]
Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.
The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.
(The below code is 32-bit, but can be easily converted to 64-bit)
For example, the sequence function can be optimized to only 5 instructions:
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
The whole code looks like:
include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"
start:
InitializeAll
mov ecx, 999999
xor edi, edi ; max
xor ebx, ebx ; max i
.main_loop:
xor esi, esi
mov eax, ecx
.seq:
inc esi ; counter
lea edx, [3*eax+1] ; edx = 3*n+1
shr eax, 1 ; eax = n/2
cmovc eax, edx ; if CF eax = edx
jnz .seq ; jmp if n<>1
cmp edi, esi
cmovb edi, esi
cmovb ebx, ecx
dec ecx
jnz .main_loop
OutputValue "Max sequence: ", edi, 10, -1
OutputValue "Max index: ", ebx, 10, -1
FinalizeAll
stdcall TerminateAll, 0
In order to compile this code, FreshLib is needed.
In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0
: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3
.
The output of both programs is the same: max sequence = 525 on i = 837799.
This worked for me: :)
<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
alert('PlanId:' + planId + ' ParticipantId:' + participantId);
}
Select multiple lines by clicking first line then holding shift and clicking last line. Then press:
CTRL+SHIFT+L
or on MAC: CMD+SHIFT+L (as per comments)
Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.
Now you can edit multiple lines, move cursors etc. for all selected lines.
In Idea 17eap:
sout
: Prints
System.out.println();
soutm
: Prints current class and method names to System.out
System.out.println("$CLASS_NAME$.$METHOD_NAME$");
soutp
: Prints method parameter names and values to System.out
System.out.println($FORMAT$);
soutv
: Prints a value to System.out
System.out.println("$EXPR_COPY$ = " + $EXPR$);
Edit / Paste from the title bar's context menu (until they fix the control key shortcuts)
Well in my case i was accessing an static array of a class by reference of that class, but as we know we can directly access static member via class name. So when I replaced reference with class name where I was accessing that array. It fixed this error.
Visual Studio Code: Version: 1.53.2
If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.
Go to Edit > Replace in Files
From there it is similar to the search funtionality for a single file.
I changed the name of a class I was using across files and this worked perfectly.
Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.
If you are using Docker toolkit on window 10 home you will need to access the webpage through docker-machine ip command. It is generally 192.168.99.100:
It is assumed that you are running with publish command like below.
docker run -it -p 8080:8080 demo
With Window 10 pro version you can access with localhost or corresponding loopback 127.0.0.1:8080 etc (Tomcat or whatever you wish). This is because you don't have a virtual box there and docker is running directly on Window Hyper V and loopback is directly accessible.
Verify the hosts file in window for any digression. It should have 127.0.0.1 mapped to localhost
If you want to have access to the id
attribute of the button in angular 6 follow this code
`@Component({
selector: 'my-app',
template: `
<button (click)="clicked($event)" id="myId">Click Me</button>
`
})
export class AppComponent {
clicked(event) {
const target = event.target || event.srcElement || event.currentTarget;
const idAttr = target.attributes.id;
const value = idAttr.nodeValue;
}
}`
your id
in the value,
the value of value
is myId
.
I too faced such scenario where I had to run a web app in nodejs with index.html being the entry point. Here is what I did:
node init
in root of app (this will create a package.json file)npm install --save express
(save will update package.json with express dependency)server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public')); //__dir and not _dir
var port = 8000; // you can use any port
app.listen(port);
console.log('server on' + port);
do node server
: it should output "server on 8000"
start http://localhost:8000/ : your index.html will be called
You can find the number of members in a Javascript array by using its length
property:
var number = $scope.names.length;
Docs - Array.prototype.length
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above).
File-> Preferences -> Keyboard Shortcuts.
An editor will appear with keybindings.json file. Place the following JSON in there and save.
[
{
"key": "ctrl+shift+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
}
]
Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.
These commands are built into VS Code, and no extensions are required to make them work.
You have enabled CORS and enabled Access-Control-Allow-Origin : *
in the server.If still you get GET
method working and POST
method is not working then it might be because of the problem of Content-Type
and data
problem.
First AngularJS transmits data using Content-Type: application/json
which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded
Example :-
$scope.formLoginPost = function () {
$http({
url: url,
method: "POST",
data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Note : I am using $.params
to serialize the data to use Content-Type: x-www-form-urlencoded
. Alternatively you can use the following javascript function
function params(obj){
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
and use params({ 'username': $scope.username, 'Password': $scope.Password })
to serialize it as the Content-Type: x-www-form-urlencoded
requests only gets the POST data in username=john&Password=12345
form.
Mine had to do with unnecessarily putting curly braces around a variable holding a HTML element inside the return statement of the render() function. This made React treat it as an object rather than an element.
render() {
let element = (
<div className="some-class">
<span>Some text</span>
</div>
);
return (
{element}
)
}
Once I removed the curly braces from the element, the error was gone, and the element was rendered correctly.
Press Ctl+T
will open a search box. Delete # symbol and enter your file name.
The "Getting Started" page is the introduction to the documentation. Most documentation will start off with installation instructions, just like Composer's do.
The page that contains information on the composer.json
file is located here - under "Basic Usage", the second page.
I'd recommend reading over the documentation in full, so that you gain a better understanding of how to use Composer. I'd also recommend removing what you have and following the installation instructions provided in the documentation.
This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.
If you add / before /n, it should work, you need to escape new line character.
"Hello there //n start coding"
The result should be as following
Hello there
start coding
Another option is to ask IDEA to behave like eclipse with eclipse shortcut keys. You can use all eclipse shortcuts by enabling this.
Here are the steps:
1- With IDEA open, press Control + `. Following options will be popped up.
2- Select Keymap. You will see another pop-up. Select Eclipse there.
3- Now press Ctrl + Shift + O
. You are done!
To permanently set the language syntax:
open settings.json
file
*) format all txt files with javascript formatting
"files.associations": {
"*.txt": "javascript"
}
*) format all unsaved files (untitled-1 etc) to javascript:
"files.associations": {
"untitled-*": "javascript"
}
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function ($scope) {_x000D_
_x000D_
//Comments object having reply oject_x000D_
$scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];_x000D_
_x000D_
//push reply_x000D_
$scope.insertReply = function (index, reply) {_x000D_
$scope.comments[index].reply.push({ comment: reply });_x000D_
}_x000D_
_x000D_
//push commnet_x000D_
$scope.newComment = function (comment) {_x000D_
$scope.comments.push({ comment:comment, reply: [] });_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
<!--Comment section-->_x000D_
<ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">_x000D_
<li>_x000D_
<b>Comment {{$index}} : </b>_x000D_
<br>_x000D_
{{comment.comment}}_x000D_
<!--Reply section-->_x000D_
<ul ng-repeat="reply in comment.reply track by $index">_x000D_
<li><i>Reply {{$index}} :</i><br>_x000D_
{{reply.comment}}</li>_x000D_
</ul>_x000D_
<!--End reply section-->_x000D_
<input type="text" ng-model="reply" placeholder=" Write your reply." /><a href="" ng-click="insertReply($index,reply)">Reply</a>_x000D_
</li>_x000D_
</ul>_x000D_
<!--End comment section -->_x000D_
_x000D_
_x000D_
<!--Post your comment-->_x000D_
<b>New comment</b>_x000D_
<input type="text" placeholder="Your comment" ng-model="comment" />_x000D_
<a href="" ng-click="newComment(comment)">Post </a>_x000D_
</div>
_x000D_
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:
Between the []
brackets add:
{
"key": "ctrl+k ctrl+u",
"command": "editor.action.transformToUppercase",
"when": "editorTextFocus"
},
{
"key": "ctrl+k ctrl+l",
"command": "editor.action.transformToLowercase",
"when": "editorTextFocus"
}
Save and close "keybindings.json"
$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
'langs' => $langs
]);
then in view
<script type="text/javascript">
var langs = {{json_encode($langs)}};
console.log(langs);
</script>
Its not pretty tho
Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.
To set VSCODE Default Formatter
File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)
Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.
You can also put the item with the default value selected out of the ng-repeat like follow :
<div ng-app="app" ng-controller="myCtrl">
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
<option value="yourDefaultValue">Default one</option>
<option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
</select>
</div>
and don't forget the value atribute if you leave it blank you will have the same issue.
For me Alt
+ Middle Click
(scroll wheel) worked fine
You have to click on Alt
then long click on Middle Click
then scroll Up or down
The simplest way I use in Visual Studio Code (Ubuntu) is:
Select the text which you want to format with the mouse.
Right click and choose "Format selection".
Use triple single quotes '''
at the beginning and end. It will be ignored as a doc string
within the function.
'''
This is how you would
write multiple lines of code
in Jupyter notebooks.
'''
I can't figure out how to print that in multiple lines but you can add a line anywhere in between those quotes and your code will be fine.
In the latest Mac OS You can use shift
+ home
or shift
+ end
Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.
nano /etc/apache2/sites-available/mydomain.xyz.conf
my config that worked to allow CORS Support
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName mydomain.xyz
ServerAlias www.mydomain.xyz
ServerAdmin [email protected]
DocumentRoot /var/www/mydomain.xyz/public
### following three lines are for CORS support
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem
</VirtualHost>
</IfModule>
a2enmod headers
I had this same issue, and running script in robomongo (Robo 3T 1.1.1) also doesn't allow to copy values and there was no export option either. The best way I could achieve this is to use mongoexport, if mongodb is installed on your local, you can use mongoexport to connect to database on any server and extract data
To connect to Data on remote server, and csv output file, run the following mongoexport in your command line
mongoexport --host HOSTNAME --port PORT --username USERNAME --password "PASSWORD" --collection COLLECTION_NAME --db DATABASE_NAME --out OUTPUTFILE.csv --type=csv --fieldFile fields.txt
fieldFile: helps to extract the desired columns, ex: contents of fields.txt can be just:
userId
to only extract values of the column 'userId'
Data on remote server, json output file:
mongoexport --host HOST_NAME --port PORT --username USERNAME --password "PASSWORD" --collection COLECTION_NAME --db DATABASE_NAME --out OUTPUT.json
this extracts all fields into the json file
data on localhost (mongodb should be running on localhost)
mongoexport --db DATABASE_NAME --collection COLLECTION --out OUTPUT.json
Reference: https://docs.mongodb.com/manual/reference/program/mongoexport/#use
Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.
So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.
import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack
first_link.send_keys(Keys.CONTROL + Keys.RETURN)
# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
driver.quit()
I think this is better solution so far.
I had a case where the error was thrown by a
$state.go('');
Which is obvious. I guess this can help someone in future.
Using Eclipse key mapping inside Android Studio is the better choice. It will easily adapt to existing key structure. But all the new persons are using new shortcut key structures in Android Studio has. So we will learn and follow Android Studio itself contain shortcuts will help easily interact the team mates.
If you use Android Studio in Max OS X mean to follow the below link. It works for me. https://stackoverflow.com/a/30891985/2219406
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:
$ curl -XGET 'localhost:9200/_cluster/health?pretty'
This will give you the status and other related data you need.
{
"cluster_name" : "xxxxxxxx",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 2,
"number_of_data_nodes" : 2,
"active_primary_shards" : 15,
"active_shards" : 12,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0
}
It's not the angular way, remove the function from html body and use it in controller, or use
angular.element(document).ready
More details are available here: https://stackoverflow.com/a/18646795/4301583
CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!
For Spring boot web apps, Spring boot provides the out-of-box solution for graceful shutdown from version 2.3.0.RELEASE
.
An excerpt from Spring doc
Refer this answer for the Code Snippet
I was getting this error because of the new Google Universal Analytics code, particularly caused by using the Remarketing lists on Analytics.
Here's how I fixed it.
1) Log into Google Analytics
2) Click "Admin" in top menu
3) In "Property" column, click "Property Settings"
4) Make sure "Enable Display Advertiser Features" is "On"
5) Click "Save" at bottom
6) Click ".js Tracking Info" in left menu
7) Click "Tracking Code"
8) Update your website's tracking code
When you run the debugger again, hopefully it will be taken care of.
You can still use angular.isDefined()
You just need to set
$rootScope.angular = angular;
in the "run" phase.
See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview
To comment/uncomment one line, use: Ctrl + /.
To comment/uncomment a block, use: Ctrl + Shift + /.
You don't necessarily need to have the parameters inside the URL.
For instance, with:
$stateProvider
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
},
params: {
foo: null,
bar: null
}
})
You will be able to send parameters to the state, using either:
$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>
Of course, if you reload the page once on the home
state, you will loose the state parameters, as they are not stored anywhere.
A full description of this behavior is documented here, under the params
row in the state(name, stateConfig)
section.
Follow the steps:
More details for each step Click Here
app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
$scope.post = {url: 'http://', title: ''};
$scope.createVariable = function(url) {
$window.location.href = url;
};
$scope.createFixed = function() {
$window.location.href = '/tab/newpost';
};
});
HTML
<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>
If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require
a controller (instance of a component) from a another component that follows a certain hierarchy.
For example:
//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
...,
controller : function WizardController() {
this.disableNext = function() {
//disable next step... some implementation to disable the next button hosted by the wizard
}
},
...
});
//some child component
myModule.component('onboardingStep', {
...,
controller : function OnboadingStepController(){
this.$onInit = function() {
//.... you can access this.container.disableNext() function
}
this.onChange = function(val) {
//..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
if(notIsValid(val)){
this.container.disableNext();
}
}
},
...,
require : {
container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
},
...
});
Now the usage of these above components might be something like this:
<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->
<on-boarding-step ...>
<!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>
There are many ways you can set up require.
(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.
Old Answer:
You need to inject $controller
service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.
Example:
app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
//Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
//In this case it is the child scope of this scope.
$controller('TestCtrl1',{$scope : testCtrl1ViewModel });
testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);
In any case you cannot call TestCtrl1.myMethod()
because you have attached the method on the $scope
and not on the controller instance.
If you are sharing the controller, then it would always be better to do:-
.controller('TestCtrl1', ['$log', function ($log) {
this.myMethod = function () {
$log.debug("TestCtrl1 - myMethod");
}
}]);
and while consuming do:
.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $controller('TestCtrl1');
testCtrl1ViewModel.myMethod();
}]);
In the first case really the $scope
is your view model, and in the second case it the controller instance itself.
Add this to .project file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>framework</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
you can try this
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
Commenting just so people can have a solution to the intended question.
You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.
In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.
The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.
iOS Simulator -> I/O -> Keyboard -> Connect Hardware Keyboard
I was facing similar issues but above flow chart is the fix for your issue.
generate sql:
docker exec -t your-db-container pg_dumpall -c -U your-db-user > dump_$(date +%Y-%m-%d_%H_%M_%S).sql
to reduce the size of the sql you can generate a compress:
docker exec -t your-db-container pg_dumpall -c -U your-db-user | gzip > ./dump_$(date +"%Y-%m-%d_%H_%M_%S").gz
cat your_dump.sql | docker exec -i your-db-container psql -U your-db-user -d your-db-name
to restore a compressed sql:
gunzip < your_dump.sql.gz | docker exec -i your-db-container psql -U your-db-user -d your-db-name
PD: this is a compilation of what worked for me, and what I got from here and elsewhere. I am beginning to make contributions, any feedback will be appreciated.
For added information, under the context of running the application in docker.
In docker-compose.yml file, under the application container itself, you can use one of the following:
command: ["rm /your-app-path/tmp/pids/server.pid && bundle exec bin/rails s -p 3000 -b '0.0.0.0'"]
or
command: ["rm /your-app-path/tmp/pids/server.pid; foreman start"]
Note the use of either ;
or &&
, that &&
will send an exit signal if rm
fails to find the file, forcing your container to prematurely stop. Using ;
will continue to execute.
Why is this caused in the first place? The rationale is that if the server (puma/thin/whatever) does not cleanly exit, it will leave a pid in the host machine causing an exit error.
For portability rather than manually deleting the file on the host system, it's better to check if the file exists within scripted or compose file itself.
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
///////////////// OR ////////////
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
</div>
menuController have access for menu div. And widgetController have access to both.
New version 4.100.x.xxxx
Try this:
More Apps > Android Settings > Accessibility > Auto-rotate screen = Enabled
You may use formatters after picking value inside your datepicker directive. For example
angular.module('foo').directive('bar', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.push(function(value) {
if (value) {
// format and return date here
}
return undefined;
});
}
};
});
LINK.
Not Just HTML, Using atom-beautify
- Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.
To Install the atom-beautify
package :
Install Packages & Themes
. A Install Package window comes up.Beautify
package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify
.To Format text Using atom-beautify
:
The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.
The name of the extension is: "Allow-Control-Allow-Origin: *" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Make a toggle function in the respective scope to grey out the link.
First,create the following CSS classes in your .css file.
.disabled {
pointer-events: none;
cursor: default;
}
.enabled {
pointer-events: visible;
cursor: auto;
}
Add a $scope.state and $scope.toggle variable. Edit your controller in the JS file like:
$scope.state='on';
$scope.toggle='enabled';
$scope.changeState = function () {
$scope.state = $scope.state === 'on' ? 'off' : 'on';
$scope.toggleEdit();
};
$scope.toggleEdit = function () {
if ($scope.state === 'on')
$scope.toggle = 'enabled';
else
$scope.toggle = 'disabled';
};
Now,in the HTML a tags edit as:
<a href="#" ng-click="create()" class="{{toggle}}">CREATE</a><br/>
<a href="#" ng-click="edit()" class="{{toggle}}">EDIT</a><br/>
<a href="#" ng-click="delete()" class="{{toggle}}">DELETE</a>
To avoid the problem of the link disabling itself, change the DOM CSS class at the end of the function.
document.getElementById("create").className = "enabled";
I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The code from the example should not be difficult to adapt to your specific situation:
<script>
function Ctrl($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
EDIT: This answer is correct for version 0.2.10
. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14
.
Another reason to use $state.params
is when you need to extract query parameters like this:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/?yetAnotherParam',
controller: 'ACtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
I think you can create expression to show or hide
<div ng-app>
<div ng-controller="MyCtrl">
<div><button id="mybutton" ng-click="myvalue = myvalue == true ? false : true;">Click me</button></div>
<div>Value: {{myvalue}}</div>
<div><div ng-show="myvalue" class="hideByDefault">Here I am</div></div>
</div>
</div>
If you experience this issue on vagrant 1.8.5, then check out this thread on github:
https://github.com/mitchellh/vagrant/issues/7610
It's caused basically by a permission issue, the workaround is just
vagrant ssh
password: vagrant
chmod 0600 ~/.ssh/authorized_keys
exit
then
vagrant reload
FYI: this issue only affects CentOS, Ubuntu works fine.
Capitalization matters as well! Inside my directive, I tried specifying:
templateUrl: 'Views/mytemplate'
and got the "more than once" warning. The warning disappeared when I changed it to:
templateUrl: 'views/mytemplate'
Correct me, but I think this happened because page that I placed the directive on was under "views" and not "Views" in the route config function.
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
BlobBuilder
is obsolete, use Blob
constructor instead:
URL.createObjectURL(new Blob([/*whatever content*/] , {type:'text/plain'}));
This returns a blob URL which you can then use in an anchor's href
. You can also modify an anchor's download
attribute to manipulate the file name:
<a href="/*assign url here*/" id="link" download="whatever.txt">download me</a>
Fiddled. If I recall correctly, there are arbitrary restrictions on trusted non-user initiated downloads; thus we'll stick with a link clicking which is seen as sufficiently user-initiated :)
Update: it's actually pretty trivial to save current document's html! Whenever our interactive link is clicked, we'll update its href
with a relevant blob. After executing the click-bound event, that's the download URL that will be navigated to!
$('#link').on('click', function(e){
this.href = URL.createObjectURL(
new Blob([document.documentElement.outerHTML] , {type:'text/html'})
);
});
When you have replace: true
you get the following piece of DOM:
<div ng-controller="Ctrl" class="ng-scope">
<div class="ng-binding">hello</div>
</div>
whereas, with replace: false
you get this:
<div ng-controller="Ctrl" class="ng-scope">
<my-dir>
<div class="ng-binding">hello</div>
</my-dir>
</div>
So the replace
property in directives refer to whether the element to which the directive is being applied (<my-dir>
in that case) should remain (replace: false
) and the directive's template should be appended as its child,
OR
the element to which the directive is being applied should be replaced (replace: true
) by the directive's template.
In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:
.directive('myDir', function() {
return {
restrict: 'E',
replace: false,
transclude: true,
template: '<div>{{title}}<div ng-transclude></div></div>'
};
});
In that case if in the directive's template you have an element (or elements) with attribute ng-transclude
, its content will be replaced by the element's (to which the directive is being applied) original content.
See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview
See this to read more about translusion.
What you should do is create a service to share data between controllers.
Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk
Try using No Wrap - In Head or No wrap - in body in your fiddle:
Working fiddle: http://jsfiddle.net/Q5hd6/
Explanation:
Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad
(onload option in fiddle) => it's too late to register your myApp
module because angular begins compiling the DOM and angular sees that there is no module named myApp
and throws an exception.
By using No Wrap - In Head, your code looks like this:
<head>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>
<script type='text/javascript'>
//Your script.
</script>
</head>
Your script has a chance to run before angular begins compiling the DOM and myApp
module is already created when angular starts compiling the DOM.
you can use Alt + Enter in Android Studio as Shortcut Key
After testing different proposals, I found that the easiest way is often the best.
If you use angular ui-router and that you need a button to go back best is this:
<button onclick="history.back()">Back</button>
or
<a onclick="history.back()>Back</a>
// Warning don't set the href or the path will be broken.
Explanation: Suppose a standard management application. Search object -> View object -> Edit object
Using the angular solutions From this state :
Search -> View -> Edit
To :
Search -> View
Well that's what we wanted except if now you click the browser back button you'll be there again :
Search -> View -> Edit
And that is not logical
However using the simple solution
<a onclick="history.back()"> Back </a>
from :
Search -> View -> Edit
after click on button :
Search -> View
after click on browser back button :
Search
Consistency is respected. :-)
Worked for me on OS X + Sublime build 3083:
OPTION (ALT) + select lines
If you have a named container then it can be started by running
docker container start container_name
where container_name is name of the container that must be given at the time of creating container. You can replace container_name
with the container id in case the container is not named. The container ID can be found by running:
docker ps -a
There are multiple ways to share data between controllers
As we know $rootscope
is not preferable way for data transfer or communication because it is a global scope which is available for entire application
For data sharing between Angular Js controllers Angular services are best practices eg. .factory
, .service
For reference
In case of data transfer from parent to child controller you can directly access parent data in child controller through $scope
If you are using ui-router
then you can use $stateParmas
to pass url parameters like id
, name
, key
, etc
$broadcast
is also good way to transfer data between controllers from parent to child and $emit
to transfer data from child to parent controllers
HTML
<div ng-controller="FirstCtrl">
<input type="text" ng-model="FirstName">
<br>Input is : <strong>{{FirstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{FirstName}}
</div>
JS
myApp.controller('FirstCtrl', function( $rootScope, Data ){
$rootScope.$broadcast('myData', {'FirstName': 'Peter'})
});
myApp.controller('SecondCtrl', function( $rootScope, Data ){
$rootScope.$on('myData', function(event, data) {
$scope.FirstName = data;
console.log(data); // Check in console how data is coming
});
});
Refer given link to know more about $broadcast
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
The accepted answer is correct. I would like to provide an example to elaborate it a bit to those who aren't familiar with promise
.
Example:
In my example, I need to replace the src
attributes of img
tags with different mirror urls if available before rendering the content.
var img_tags = content.querySelectorAll('img');
function checkMirrorAvailability(url) {
// blah blah
return promise;
}
function changeSrc(success, y, response) {
if (success === true) {
img_tags[y].setAttribute('src', response.mirror_url);
}
else {
console.log('No mirrors for: ' + img_tags[y].getAttribute('src'));
}
}
var promise_array = [];
for (var y = 0; y < img_tags.length; y++) {
var img_src = img_tags[y].getAttribute('src');
promise_array.push(
checkMirrorAvailability(img_src)
.then(
// a callback function only accept ONE argument.
// Here, we use `.bind` to pass additional arguments to the
// callback function (changeSrc).
// successCallback
changeSrc.bind(null, true, y),
// errorCallback
changeSrc.bind(null, false, y)
)
);
}
$q.all(promise_array)
.then(
function() {
console.log('all promises have returned with either success or failure!');
render(content);
}
// We don't need an errorCallback function here, because above we handled
// all errors.
);
Explanation:
From AngularJS docs:
The then
method:
then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason.
$q.all(promises)
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
The promises
param can be an array of promises.
About bind()
, More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
You can use jquery for this:
$('body').bind('copy paste',function(e) {
e.preventDefault(); return false;
});
Using jQuery bind()
and specififying your desired eventTypes
.
Similar answers:
Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
at all:A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.
First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.
I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http
service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.
app.factory('locations', function($http) {
var promise = null;
return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('locations/locations.json');
return promise;
}
};
});
As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations
service into the directive, but this couples the directive to that service.
A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.
In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.
app.controller('SomeController', function($scope, locations) {
locations().success(function(data) {
$scope.locations = data;
});
});
<ul class="list">
<li ng-repeat="location in locations">
<a href="#">{{location.id}}. {{location.name}}</a>
</li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
// creates a scope variable in your directive
// called `locations` bound to whatever was passed
// in via the `locations` attribute in the DOM
locations: '=locations'
},
link: function(scope, element, attrs) {
scope.$watch('locations', function(locations) {
angular.forEach(locations, function(location, key) {
// do something
});
});
}
};
});
In this way, the map
directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.
Its been a year asking this question but still for someone.
While declaring the UITapGestureRecognizer
on a particular view assign the tag as
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandlerMethod:)];
[yourGestureEnableView addGestureRecognizer:tapRecognizer];
yourGestureEnableView.tag=2;
and in your handler do like this
-(void)gestureHandlerMethod:(UITapGestureRecognizer*)sender {
if(sender.view.tag == 2) {
// do something here
}
}
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
The following worked for me:
I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.
Overwrite their default template:
<script type="text/ng-template" id="myDlgTemplateWrapper.html">
<div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}"
ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)">
<!-- <div class="modal-dialog"
ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
>
<div class="modal-content" modal-transclude></div>
</div>-->
<div modal-transclude>
<!-- Your content goes here -->
</div>
</div>
</script>
Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-dialog {{extraDlgClass}}"
style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
<div class="modal-content">
<div class="modal-header bg-primary">
<h3>I am a more flexible modal!</h3>
</div>
<div class="modal-body"
style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
<p>Make me any size you want</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
</script>
And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):
<script type="text/javascript">
app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
{
// Adjust these with your parameters as needed
$scope.extraDlgClass = undefined;
$scope.width = "70%";
$scope.height = "200px";
$scope.maxWidth = undefined;
$scope.maxHeight = undefined;
$scope.minWidth = undefined;
$scope.minHeight = undefined;
$scope.open = function ()
{
$scope.modalInstance = $modal.open(
{
backdrop: 'static',
keyboard: false,
modalFade: true,
templateUrl: "myModalContent.html",
windowTemplateUrl: "myDlgTemplateWrapper.html",
scope: $scope,
//size: size, - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)
extraDlgClass: $scope.extraDlgClass,
width: $scope.width,
height: $scope.height,
maxWidth: $scope.maxWidth,
maxHeight: $scope.maxHeight,
minWidth: $scope.minWidth,
minHeight: $scope.minHeight
});
$scope.modalInstance.result.then(function ()
{
console.log('Modal closed at: ' + new Date());
},
function ()
{
console.log('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.close("OK");
};
$scope.cancel = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.dismiss('cancel');
};
$scope.openFlexModal = function ()
{
$scope.open();
}
}]);
</script>
Add an "open" button and fire away.
<button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>
Now you can add whatever extra class you want, or simply change width/height sizes as necessary.
I further enclosed it within a wrapper directive, which is should be trivial from this point forward.
Cheers.
I had the same problem. You should type your Angular js code outside of any function like this:
$( document ).ready(function() {});
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
Btw you can also use the ui-sref attribute in your templates to pass objects
ui-sref="myState({ myParam: myObject })"
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
MyApp.service('getData',
[
'$http',
function($http) {
this.getQuote = function(ticker) {
var _url = 'https://www.google.com/finance/info?q=' + ticker;
return $http.get(_url); //Simply return the promise to the caller
};
}
]
);
The controller:
MyApp.controller('StockREST',
[
'$scope',
'getData', //<-- the service above
function($scope, getData) {
var getQuote = function(symbol) {
getData.getQuote(symbol)
.success(function(response, status, headers, config) {
var _data = response.substring(4, response.length);
var _json = JSON.parse(_data);
$scope.stockQuoteData = _json[0];
// ticker: $scope.stockQuoteData.t
// last price: $scope.stockQuoteData.l
// last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
// last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
})
.error(function(response, status, headers, config) {
console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
});
};
getQuote($scope.ticker.tick.name); //Initialize
$scope.getQuote = getQuote; //as defined above
}
]
);
The HTML:
<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
var custApp = angular.module("custApp", [])
.controller('FirstController', FirstController)
.controller('SecondController',SecondController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
SecondController.$inject['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default Value'
}
}
First Controller
<div ng-controller="FirstController as vm">
<input type=text ng-model="vm.data.value" />
</div>
Second Controller
<div ng-controller="SecondController as vm">
Second Controller<br>
{{vm.data.value}}
</div>
You can add this to your _Layout.cshtml:
@using MyProj.ViewModels;
...
@if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert @message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>@message.Title</strong>
@message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
You can kill all node processes using pkill node
or you can do a ps T
to see all processes on this terminal
then you can kill a specific process ID doing a kill [processID]
example: kill 24491
Additionally, you can do a ps -help
to see all the available options
What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:
app.js
var app = angular.module("myApp", ['deps']);
myCtrl.js
app.controller("myCtrl", function($scope) { ..});
html
<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.
Do not use $scope.$apply()
angular already uses it and it can result in this error
$rootScope:inprog Action Already In Progress
if you use twice, use $timeout
or interval
Try this
in view:
<form name="formName" ng-submit="submitForm(formName)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(form){
if(form.$valid) {
// Code here if valid
}
};
or
in view:
<form name="formName" ng-submit="submitForm(formName.$valid)">
<!-- fields -->
</form>
in controller:
$scope.submitForm = function(formValid){
if(formValid) {
// Code here if valid
}
};
You need also $sce.trustAsResourceUrl
or it won't open the website inside the iframe:
angular.module('myApp', [])_x000D_
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
$scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
$scope.changeIt = function () {_x000D_
$scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
}_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
<iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
<br>_x000D_
<button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
Sending data to some service page.
<form class="form-horizontal" role="form" ng-submit="submit_form()">
<input type="text" name="user_id" ng-model = "formAdata.user_id">
<input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>
$scope.submit_form = function()
{
$http({
url: "http://localhost/services/test.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
$scope.status = status;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
If you just want to make some modification to files or inspect processes, here's one another solution you probably want.
You could run the following command to execute a new process from the existing container:
sudo docker exec -ti [CONTAINER-ID] bash
will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.
This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html',
controller: function ($scope) {
$scope.selectThisOption = function () {
// some code
};
}
};
});
When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html'
controller: ['$scope', function ($scope) { //<-- difference
$scope.selectThisOption = function () {
// some code
};
}]
};
});
When you change files or add a new ones in repository you first must stage them.
git add <file>
or if you want to stage all
git add .
By doing this you are telling to git what files you want in your next commit. Then you do:
git commit -m 'your message here'
You use
git push origin master
where origin is the remote repository branch and master is your local repository branch.
Usually this is due to another directive in-between your ng-controller and your input that is creating a new scope. When the select writes out it value, it will write it up to the most recent scope, so it would write it to this scope rather than the parent that is further away.
The best practice is to never bind directly to a variable on the scope in an
ng-model
, this is also known as always including a "dot" in your ngmodel. For a better explanation of this, check out this video from John:
Solution from: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU
If you want to use asynchronous method you need to use callback function by $promise, here is example:
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
$scope.regions = result;
});
sometimes something wrong in the syntax of the code inside the function throws this error. Check your function correctly. In my case it happened when I was trying to assign Json fields with values and was using colon : to make the assignment instead of equal sign = ...
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
I would do something like,
Main
var getPage = get_page
func get_page (...
func downloader() {
dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
content := getPage(BASE_URL)
links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
matches := links_regexp.FindAllStringSubmatch(content, -1)
for _, match := range matches{
go serie_dl(match[1], match[2])
}
}
Test
func TestDownloader (t *testing.T) {
origGetPage := getPage
getPage = mock_get_page
defer func() {getPage = origGatePage}()
// The rest to be written
}
// define mock_get_page and rest of the codes
func mock_get_page (....
And I would avoid _
in golang. Better use camelCase
Factory and Service are the most commonly used method. The only difference between them is that the Service method works better for objects that need inheritance hierarchy, while the Factory can produce JavaScript primitives and functions.
The Provider function is the core method and all the other ones are just syntactic sugar on it. You need it only if you are building a reusable piece of code that needs global configuration.
There are five methods to create services: Value, Factory, Service, Provider and Constant. You can learn more about this here angular service, this article explain all this methods with practical demo examples.
.
There are multiple ways to achieve this one:-
1. Add $rootScope
in .run
method
.run(function ($rootScope) {
$rootScope.name = "Peter";
});
// Controller
.controller('myController', function ($scope,$rootScope) {
console.log("Name in rootscope ",$rootScope.name);
OR
console.log("Name in scope ",$scope.name);
});
2. Create one service and access it in both the controllers.
.factory('myFactory', function () {
var object = {};
object.users = ['John', 'James', 'Jake'];
return object;
})
// Controller A
.controller('ControllerA', function (myFactory) {
console.log("In controller A ", myFactory);
})
// Controller B
.controller('ControllerB', function (myFactory) {
console.log("In controller B ", myFactory);
})
The line
$location.absUrl() == 'http://www.google.com';
is wrong. First == makes a comparison, and what you are probably trying to do is an assignment, which is with simple = and not double ==.
And because absUrl() getter only. You can use url(), which can be used as a setter or as a getter if you want.
reference : http://docs.angularjs.org/api/ng.$location
If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}"
to the md-select tag ash shown in this pen
Code:
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
<md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
<md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
In your 'test' directive Html tag, the attribute name of the function should not be camelCased, but dash-based.
so - instead of :
<test color1="color1" updateFn="updateFn()"></test>
write:
<test color1="color1" update-fn="updateFn()"></test>
This is angular's way to tell the difference between directive attributes (such as update-fn function) and functions.
Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix
or tr
, for example:
tr -d '\015' < yourscript.sh > newscript.sh
This removes any CR characters from the file.
Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
Hope that helps!
After many months, I returned to develop an AngularJS (1.6.4) app, for which I chose Chrome (PC) and Safari (MAC) for testing during development. This code presented this Error: $injector:modulerr Module Error on IE 11.0.9600 (Windows 7, 32-bit).
Upon investigation, it became clear that error was due to forEach loop being used, just replaced all the forEach loops with normal for loops for things to work as-is...
It was basically an IE11 issue (answered here) rather than an AngularJS issue, but I want to put this reply here because the exception raised was an AngularJS exception. Hope it would help some of us out there.
similarly. don't use lambda functions... just replace ()=>{...} with good ol' function(){...}
here is what i came up with. combining multiple answers
#computer list below
$computers = (
'computer1.domain.local',
'computer2.domain.local'
)
foreach ($Computer in $computers) {
Invoke-Command -ComputerName $Computer -ScriptBlock {
Write-Host '______ '$Env:Computername
$usertocheck = 'SomeUserName'
$sessionID = ((quser | Where-Object { $_ -match $usertocheck }) -split ' +')[2]
If([string]::IsNullOrEmpty($sessionID)){
Write-Host -ForegroundColor Yellow "User Not Found."
} else {
write-host -ForegroundColor Green 'Logging off ' $usertocheck 'Session ID' $sessionID
logoff $sessionID
}
}
}
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic); than element.html(attr.dynamic);
onSelect doesn't work well in ng-repeat, so I made another version using event bind
html
<tr ng-repeat="product in products">
<td>
<input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>
script
angular.module('app', []).directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker();
element.bind('blur keyup change', function(){
var model = attrs.ngModel;
if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
else scope[model] = element.val();
});
}
};
});
I've solved my problems, so I post here the correct code in case someone needs similar stuff.
Open Port
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );
Set parameters
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
Write
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1)
worked fine.
At last, read:
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( USB, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
This one worked for me. Thank you all!
I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion
please note, if you use $filter like this:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});
and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);
This really killed me when I was pulling in some commission details like this:
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];
only get called in for a bug because it was pulling in the commission ID 56 rather than 6.
Adding the true forces an exact match.
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];
Yet still, I prefer this (I use typescript, hence the "Let" and =>):
let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{
return item.commission_type_id === 6;
})[0];
I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.
You can always add it exactly for your application
angular.isUndefinedOrNull = function(val) {
return angular.isUndefined(val) || val === null
}
In case anyone has had further issues with Sublime 3 on Windows 7, the above suggestions all did not work for me. However, when I 1 - reran the app as administrator and 2 - highlighted, and chose Edit -> Comment -> toggle comment, afterwards I was able to use a user preferences set keybinding to toggle comments. I don't really have an explanation for why it worked, except that it did.
Another (and I think better) way to achieve this is to actually intercept the data. limitTo is okay but what if you're limiting to 10 when your array actually contains thousands?
When calling my service I simply did this:
TaskService.getTasks(function(data){
$scope.tasks = data.slice(0,10);
});
This limits what is sent to the view, so should be much better for performance than doing this on the front-end.
I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.
If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.
Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.
We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.
Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)
Specifically, Trello does this:
TrelloClipboard = new class
constructor: ->
@value = ""
$(document).keydown (e) =>
# Only do this if there's something to be put on the clipboard, and it
# looks like they're starting a copy shortcut
if !@value || !(e.ctrlKey || e.metaKey)
return
if $(e.target).is("input:visible,textarea:visible")
return
# Abort if it looks like they've selected some text (maybe they're trying
# to copy out a bit of the description or something)
if window.getSelection?()?.toString()
return
if document.selection?.createRange().text
return
_.defer =>
$clipboardContainer = $("#clipboard-container")
$clipboardContainer.empty().show()
$("<textarea id='clipboard'></textarea>")
.val(@value)
.appendTo($clipboardContainer)
.focus()
.select()
$(document).keyup (e) ->
if $(e.target).is("#clipboard")
$("#clipboard-container").empty().hide()
set: (@value) ->
In the DOM we've got:
<div id="clipboard-container"><textarea id="clipboard"></textarea></div>
CSS for the clipboard stuff:
#clipboard-container {
position: fixed;
left: 0px;
top: 0px;
width: 0px;
height: 0px;
z-index: 100;
display: none;
opacity: 0;
}
#clipboard {
width: 1px;
height: 1px;
padding: 0px;
}
... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.
When you hover over a card, it calls
TrelloClipboard.set(cardUrl)
... so then the clipboard helper knows what to select when the Ctrl key is pressed.
Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl
You can use a function to generate the template string:
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href
attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href
attributes blank.
<a href="" data-router="article" ng-click="changeListName('metro')">
Also I don't know what data-router
is doing but if you still aren't getting the proper result, that could be why.
I prefer, putting git in environment variable and just calling
c:\Users\[myname]>sh
or
c:\Users\[myname]>bash
Steps to create Environment variable (Win7)
In the section User variables, hit button NEW, put variable name as GIT_HOME
, value as (folder-where-you-installed-git).
c:\tools\git
, others maybe have C:\Program Files\Git
find the PATH
environment variable and select it. Click Edit. (If the PATH environment variable does not exist, click New).
%GIT_HOME%
and %GIT_HOME%\bin
. Click OK. Close all remaining windows by clicking OK.sh
or bash
or git-bash
Turns out it's the Cache of the browser, using Chrome here. Simply check the "Disable cache" under Inspect (Element) solved my problem.
Just for the records you can also define your object in the controller like this:
this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };
and then you can define a function to change the property of the object directly:
this.changeBackgroundImage = function (){
this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
}
Doing it in that way you can modify dinamicaly your style.
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You can use the simple program StarUML. The trial version is unlimited and can do almost anything.
Onced installed you can use it to generate great number of uml digrams just by pasting the source code. Class diagram is just one type of it. (It understands not only Java language but C#, C++ and other)
P.S. The program is great for drawing architectural diagrams before you start to code the program.
The accepted answer which was triggering input
event with jQuery didn't work for me. Creating an event and dispatching with native JavaScript did the trick.
$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));
It's mentioned by @watsonic that in Sublime Text 3 on Mac OS, starting with an empty selection, simply ^?G (AltF3 on Windows) does the trick, instead of ?D + ^?G in Sublime Text 2.
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*
Add below lib inside gradle file
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
Create class HomeActivityTest inside androidTest directory and before running the test add flurry_api_key and sender_id string inside string resource file and change the value for failure and success case.
@RunWith(AndroidJUnit4.class)
public class HomeActivityTest
{
private static final String SENDER_ID = "abc";
private static final String RELEASE_FLURRY_API_KEY = "xyz";
@Test
public void gcmRegistrationId_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(SENDER_ID, appContext.getString(R.string.sender_id));
}
@Test
public void flurryApiKey_isCorrect() throws Exception
{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
Assert.assertEquals(RELEASE_FLURRY_API_KEY, appContext.getString(R.string.flurry_api_key));
}
}
For formatting code in Android Studio on Linux you could instead use Ctrl + Alt + Super + L. You could use this and avoid having to change the system shortcut. (Super key is the Windows icon key besides the Alt key).
I solved to
test: {
options: {
port: 9000,
base: [
'.tmp',
'test',
'<%= yeoman.app %>'
],
middleware: function (connect) {
return [
modRewrite(['^[^\\.]*$ /index.html [L]']),
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static('app')
];
}
}
},
Now the plugin is Multi Line tricks. The end and start buttons broke the selection.
Could be due to the TCP protocol turned off.
How to check/enable: https://dba.stackexchange.com/questions/11377/cannot-connect-to-ms-sql-2008-r2-by-dbvisualizer-native-sspi-library-not-loade/144097#144097
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
Alternatively - make sure that Resharper is enabled. My visual studio didn't update my Resharper license information, so when opening the resharper menu (after trying to figure out why my shortcuts stopped working!), the was a menu item "Why is Resharper disabled?" Clicking on the menu item opens up a dialog, which then automatically resolved the license. The next question for Jetbrains is why do I have to open the dialog for the thing to automatically renew??
For anyone else who wants to set Eclipse style goto definition, you need to create .sublime-mousemap
file in Sublime User
folder.
Windows - create Default (Windows).sublime-mousemap
in %appdata%\Sublime Text 3\Packages\User
Linux - create Default (Linux).sublime-mousemap
in ~/.config/sublime-text-3/Packages/User
Mac - create Default (OSX).sublime-mousemap
in ~/Library/Application Support/Sublime Text 3/Packages/User
Now open that file and put the following configuration inside
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
You can change modifiers
key as you like.
Since Ctrl-button1
on Windows and Linux is used for multiple selections, adding a second modifier key like Alt might be a good idea if you want to use both features:
[
{
"button": "button1",
"count": 1,
"modifiers": ["ctrl", "alt"],
"press_command": "drag_select",
"command": "goto_definition"
}
]
Alternatively, you could use the right mouse button (button2
) with Ctrl alone, and not interfere with any built-in functions.
This worked for me:
A solution very easy to do it
Note : it's only for an asynchrone call, because service isn't initialized on config execution.
You can use run()
method. Example :
Your code :
(function () { //To isolate code TO NEVER HAVE A GLOBAL VARIABLE!
//Store your service into an internal variable
//It's an internal variable because you have wrapped this code with a (function () { --- })();
var theServiceToInject = null;
//Declare your application
var myApp = angular.module("MyApplication", []);
//Set configuration
myApp.config(['MyProvider', function (MyProvider) {
MyProvider.callMyMethod(function () {
theServiceToInject.methodOnService();
});
}]);
//When application is initialized inject your service
myApp.run(['MyService', function (MyService) {
theServiceToInject = MyService;
}]);
});
Late to the party, but for future Googlers - don't use the provided answer.
JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".
In above example, instead of binding attributes of a service, why don't we expose the service to the scope?
$scope.hello = HelloService;
This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.
And if you are worried about your view accidentally overwriting your service attributes, use defineProperty
to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.
Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.
In that particular demo code you supplied I would recommend you do:
function TimerCtrl1($scope, Timer) {
$scope.timer = Timer;
}
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...
Edit:
As I mentioned above, you can control the behaviour of your service attributes using defineProperty
Example:
// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
get: function() { return self.data.variable; },
set: function(newValue) {
self.data.variable = newValue;
// let's update the database too to reflect changes in data-model !
self.updateDatabaseWithNewData(data);
},
enumerable: true,
configurable: true
});
Now in our controller if we do
$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';
our service will change the value of propertyWithSetter
and also post the new value to database somehow!
Or we can take any approach we want.
Refer to the MDN documentation for defineProperty
.
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
I did it slightly different using threads
from werkzeug.serving import make_server
class ServerThread(threading.Thread):
def __init__(self, app):
threading.Thread.__init__(self)
self.srv = make_server('127.0.0.1', 5000, app)
self.ctx = app.app_context()
self.ctx.push()
def run(self):
log.info('starting server')
self.srv.serve_forever()
def shutdown(self):
self.srv.shutdown()
def start_server():
global server
app = flask.Flask('myapp')
...
server = ServerThread(app)
server.start()
log.info('server started')
def stop_server():
global server
server.shutdown()
I use it to do end to end tests for restful api, where I can send requests using the python requests library.
The most simplest way to achieve your goal is to open a new incognito window in your chrome or private window in firefox which will by default, not cache.
You can use this for development purposes so that you don't have to inject some random cache preventing code in your project.
If you are using IE then may god help you!
I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).
**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
$('#btnClose').click();// this is bootstrap modal close button id that fire click event
})
--------------------------------------------------------------------------------
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()
If you insert ng-click="$event.stopPropagation" on the parent element of your template, the stopPropogation will be caught as it bubbles up the tree, so you only have to write it once for your entire template.
modification for the code above:
$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
console.log('prev path: ' + absOldUrl.$$route.originalPath);
});
Though this post is old and has had an answer accepted, using reloadOnSeach=false does not solve the problem for those of us who need to change actual path and not just the params. Here's a simple solution to consider:
Use ng-include instead of ng-view and assign your controller in the template.
<!-- In your index.html - instead of using ng-view -->
<div ng-include="templateUrl"></div>
<!-- In your template specified by app.config -->
<div ng-controller="MyController">{{variableInMyController}}</div>
//in config
$routeProvider
.when('/my/page/route/:id', {
templateUrl: 'myPage.html',
})
//in top level controller with $route injected
$scope.templateUrl = ''
$scope.$on('$routeChangeSuccess',function(){
$scope.templateUrl = $route.current.templateUrl;
})
//in controller that doesn't reload
$scope.$on('$routeChangeSuccess',function(){
//update your scope based on new $routeParams
})
Only down-side is that you cannot use resolve attribute, but that's pretty easy to get around. Also you have to manage the state of the controller, like logic based on $routeParams as the route changes within the controller as the corresponding url changes.
Here's an example: http://plnkr.co/edit/WtAOm59CFcjafMmxBVOP?p=preview
In Sublime Text, after you select multiple regions of text, a click is considered a way to exit the multi-select mode. Move the cursor with the keyboard keys (arrows, Ctrl+arrows, etc.) instead, and you'll be fine
Why so complicated?
I solved my problem this way simply:
<pre>{{existingCategory+thisCategory}}</pre>
It will make <br />
automatically if the string contains '\n' that contain when I was saving data from textarea.
April 20, 2017
I've read all the previously posted answers, and they require a lot of extra work. The quick and simple solution I have found is as follows:
1) Un-group the date field in the pivot table. 2) Go to the Pivot Field List UI. 3) Re-arrange your fields so that the Date field is listed FIRST in the ROWS section. 4) Under the Design menu, select Report Layout / Show in Tabular Form.
By default, Excel sorts by the first field in a pivot table. You may not want the Date field to be first, but it's a compromise that will save you time and much work.
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
$scope.init = function () {
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
};
Reload page: using init
Although this question is rather old, I'd like to share my solution for angular 1 developers. The point is to just reuse the original angular filter, but transparently passing any objects as an array.
app.filter('objectFilter', function ($filter) {
return function (items, searchToken) {
// use the original input
var subject = items;
if (typeof(items) == 'object' && !Array.isArray(items)) {
// or use a wrapper array, if we have an object
subject = [];
for (var i in items) {
subject.push(items[i]);
}
}
// finally, apply the original angular filter
return $filter('filter')(subject, searchToken);
}
});
use it like this:
<div>
<input ng-model="search" />
</div>
<div ng-repeat="item in test | objectFilter : search">
{{item | json}}
</div>
here is a plunker
I write out a rule in web.config after $locationProvider.html5Mode(true)
is set in app.js
.
Hope, helps someone out.
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
In my index.html I added this to <head>
<base href="/">
Don't forget to install url rewriter for iis on server.
Also if you use Web Api and IIS, this match url will not work out, as it will change your api calls. So add third input(third line of condition) and give out a pattern that will exclude calls from www.yourdomain.com/api
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
Well, you have [[
and ]]
to go to the start and end of file. This works in vi.
Here is a comparison of the 3 ways you can watch a scope variable with examples:
$watch() is triggered by:
$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;
$watchCollection() is triggered by everything above AND:
$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value
$watch(..., true) is triggered by EVERYTHING above AND:
$scope.myArray[0].someProperty = "someValue";
JUST ONE MORE THING...
$watch() is the only one that triggers when an array is replaced with another array even if that other array has the same exact content.
For example where $watch()
would fire and $watchCollection()
would not:
$scope.myArray = ["Apples", "Bananas", "Orange" ];
var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange");
$scope.myArray = newArray;
Below is a link to an example JSFiddle that uses all the different watch combinations and outputs log messages to indicate which "watches" were triggered:
Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.
now I'll show you a sample example that exaplain how can you update your model from server.
HTML Code:
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="updateData()">Refresh Data</button>
</div>
So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData()
that will be invoked when we are need to update and refresh our Model persons.
Javascript Code:
app.controller('adsController', function($log,$scope,...){
.....
$scope.updateData = function(){
$http.get('/persons').success(function(data) {
$scope.persons = data;// Update Model-- Line X
});
}
});
Now I explain for you how it work:
when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get()
and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.
Just type the following commands from console.
cd /your_project
heroku restart
Like @akonsu and Nigel Findlater suggest, you can read the url where url is index.html#/user/:id
with $routeParams.id
and use it inside the controller.
your app:
var app = angular.module('myApp', [ 'ngResource' ]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:type/:id', {templateUrl: 'myView.html', controller: 'myCtrl'});
}]);
the resource service
app.factory('MyElements', ['$resource', function($resource) {
return $resource('url/to/json/:type/:id', { type:'@type', id:'@id' });
}]);
the controller
app.controller('MyCtrl', ['$scope', '$routeParams', 'MyElements', function($scope, $routeParams, MyElements) {
MyElements.get({'type': $routeParams.type, "id": $routeParams.id }, function(elm) {
$scope.elm = elm;
})
}]);
then, elm
is accessible in the view depending on the id
.
The Easiest way :
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"> Send Data </button>
</div>
JavaScript
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $rootScope) {
function sendData($scope) {
var arrayData = ['sam','rumona','cubby'];
$rootScope.$emit('someEvent', arrayData);
}
});
app.controller('yourCtrl', function($scope, $rootScope) {
$rootScope.$on('someEvent', function(event, data) {
console.log(data);
});
});
</script>
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
The cause of this error for me was...
ng-if="{{myTrustSrc(chat.src)}}"
in my template
It causes the function myTrustSrc in my controller to be called in an endless loop. If I remove the ng-if from this line, then the problem is solved.
<iframe ng-if="chat.src" id='chat' name='chat' class='chat' ng-src="{{myTrustSrc(chat.src)}}"></iframe>
The function is only called a few times when ng-if isn't used. I still wonder why the function is called more than once with ng-src?
This is the function in the controller
$scope.myTrustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
}
This line:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
$scope.myForm.file.$setValidity("size", false);
If you are wanting to configure this locally on OS X 10.8 serving Angular with Apache then you might find the following in your .htaccess file helps:
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /~yourusername/appname/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
RewriteRule (.*) index.html [L]
</IfModule>
Options +FollowSymlinks if not set may give you a forbidden error in the logs like so:
Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden
Rewrite base is required otherwise requests will be resolved to your server root which locally by default is not your project directory unless you have specifically configured your vhosts, so you need to set the path so that the request finds your project root directory. For example on my machine I have a /Users/me/Sites directory where I keep all my projects. Like the old OS X set up.
The next two lines effectively say if the path is not a directory or a file, so you need to make sure you have no files or directories the same as your app route paths.
The next condition says if request not ending with file extensions specified so add what you need there
And the [L] last one is saying to serve the index.html file - your app for all other requests.
If you still have problems then check the apache log, it will probably give you useful hints:
/private/var/log/apache2/error_log
function ngController($scope,$filter){
$scope.name = "aaaa";
$scope.age = "32";
$scope.result = function(){
return $filter('lowercase')($scope.name);
};
}
The controller method 2nd argument name should be "$filter" then only the filter functionality will work with this example. In this example i have used the "lowercase" Filter.
Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase
//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
$scope = $scope || angular.element(document).scope();
if(forceReload || $scope.$$phase) {
window.location = url;
}
else {
//only use this if you want to replace the history stack
//$location.path(url).replace();
//this this if you want to change the URL and add it to the history stack
$location.path(url);
$scope.$apply();
}
};
Another solution but without using ng-click which still works even for other tags than <a>
:
<tr [routerLink]="['/about']">
This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494
(This is my first day with angular. Gentle feedback is welcome)
I took a combo of all answers, and now have two ways of doing this with the ng-model attribute:
var app = angular.module('model', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
$scope.name = "Felipe";_x000D_
$scope.label = "The Label";_x000D_
});_x000D_
_x000D_
app.directive('myDirectiveWithScope', function() {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: {_x000D_
ngModel: '=',_x000D_
},_x000D_
// Notice how label isn't copied_x000D_
template: '<div class="some"><label>{{label}}: <input ng-model="ngModel"></label></div>',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myDirectiveWithChildScope', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: true,_x000D_
// Notice how label is visible in the scope_x000D_
template: '<div class="some"><label>{{label}}: <input></label></div>',_x000D_
replace: true,_x000D_
link: function ($scope, element) {_x000D_
// element will be the div which gets the ng-model on the original directive_x000D_
var model = element.attr('ng-model');_x000D_
$('input',element).attr('ng-model', model);_x000D_
return $compile(element)($scope);_x000D_
}_x000D_
};_x000D_
});_x000D_
app.directive('myDirectiveWithoutScope', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
template: '<div class="some"><label>{{$parent.label}}: <input></label></div>',_x000D_
replace: true,_x000D_
link: function ($scope, element) {_x000D_
// element will be the div which gets the ng-model on the original directive_x000D_
var model = element.attr('ng-model');_x000D_
return $compile($('input',element).attr('ng-model', model))($scope);_x000D_
}_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirectiveIsolate', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: {},_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirectiveChild', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
scope: true,_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});_x000D_
app.directive('myReplacedDirective', function($compile) {_x000D_
return {_x000D_
restrict: 'E',_x000D_
template: '<input class="some">',_x000D_
replace: true_x000D_
};_x000D_
});
_x000D_
.some {_x000D_
border: 1px solid #cacaca;_x000D_
padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>_x000D_
<div ng-app="model" ng-controller="MainCtrl">_x000D_
This scope value <input ng-model="name">, label: "{{label}}"_x000D_
<ul>_x000D_
<li>With new isolate scope (label from parent):_x000D_
<my-directive-with-scope ng-model="name"></my-directive-with-scope>_x000D_
</li>_x000D_
<li>With new child scope:_x000D_
<my-directive-with-child-scope ng-model="name"></my-directive-with-child-scope>_x000D_
</li>_x000D_
<li>Same scope:_x000D_
<my-directive-without-scope ng-model="name"></my-directive-without-scope>_x000D_
</li>_x000D_
<li>Replaced element, isolate scope:_x000D_
<my-replaced-directive-isolate ng-model="name"></my-replaced-directive-isolate>_x000D_
</li>_x000D_
<li>Replaced element, child scope:_x000D_
<my-replaced-directive-child ng-model="name"></my-replaced-directive-child>_x000D_
</li>_x000D_
<li>Replaced element, same scope:_x000D_
<my-replaced-directive ng-model="name"></my-replaced-directive>_x000D_
</li>_x000D_
</ul>_x000D_
<p>Try typing in the child scope ones, they copy the value into the child scope which breaks the link with the parent scope._x000D_
<p>Also notice how removing jQuery makes it so only the new-isolate-scope version works._x000D_
<p>Finally, note that the replace+isolate scope only works in AngularJS >=1.2.0_x000D_
</div>
_x000D_
I'm not sure I like the compiling at link time. However, if you're just replacing the element with another you don't need to do that.
All in all I prefer the first one. Simply set scope to {ngModel:"="}
and set ng-model="ngModel"
where you want it in your template.
Update: I inlined the code snippet and updated it for Angular v1.2. Turns out that isolate scope is still best, especially when not using jQuery. So it boils down to:
Are you replacing a single element: Just replace it, leave the scope alone, but note that replace is deprecated for v2.0:
app.directive('myReplacedDirective', function($compile) {
return {
restrict: 'E',
template: '<input class="some">',
replace: true
};
});
Otherwise use this:
app.directive('myDirectiveWithScope', function() {
return {
restrict: 'E',
scope: {
ngModel: '=',
},
template: '<div class="some"><input ng-model="ngModel"></div>'
};
});
I have always wanted Visual Studio to include an option to just collapse / expand the regions. I have the following macros which will do just that.
Imports EnvDTE
Imports System.Diagnostics
' Macros for improving keyboard support for "#region ... #endregion"
Public Module CollapseExpandRegions
' Expands all regions in the current document
Sub ExpandAllRegions()
Dim objSelection As TextSelection ' Our selection object
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.StartOfDocument() ' Shoot to the start of the document
' Loop through the document finding all instances of #region. This action has the side benefit
' of actually zooming us to the text in question when it is found and ALSO expanding it since it
' is an outline.
Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
' This next command would be what we would normally do *IF* the find operation didn't do it for us.
'DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
Loop
objSelection.StartOfDocument() ' Shoot us back to the start of the document
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
' Collapses all regions in the current document
Sub CollapseAllRegions()
Dim objSelection As TextSelection ' Our selection object
ExpandAllRegions() ' Force the expansion of all regions
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.EndOfDocument() ' Shoot to the end of the document
' Find the first occurence of #region from the end of the document to the start of the document. Note:
' Note: Once a #region is "collapsed" .FindText only sees it's "textual descriptor" unless
' vsFindOptions.vsFindOptionsMatchInHiddenText is specified. So when a #region "My Class" is collapsed,
' .FindText would subsequently see the text 'My Class' instead of '#region "My Class"' for the subsequent
' passes and skip any regions already collapsed.
Do While (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards))
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion") ' Collapse this #region
'objSelection.EndOfDocument() ' Shoot back to the end of the document for
' another pass.
Loop
objSelection.StartOfDocument() ' All done, head back to the start of the doc
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
End Module
EDIT: There is now a shortcut called Edit.ToggleOutliningExpansion (Ctrl+M, Ctrl+M) for doing just that.
Just wanted to mention death
package here: https://github.com/jprichardson/node-death
Example:
var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly
ON_DEATH(function(signal, err) {
//clean up code here
})
I was able to achieve the desired result by using Alt + Shift + up/down and then typing the desired comment characters and additional character.
Yet another take on this is to match the model of one input to another input’s value.
app.directive('nxEqual', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, model) {
if (!attrs.nxEqual) {
console.error('nxEqual expects a model as an argument!');
return;
}
scope.$watch(attrs.nxEqual, function (value) {
model.$setValidity('nxEqual', value === model.$viewValue);
});
model.$parsers.push(function (value) {
var isValid = value === scope.$eval(attrs.nxEqual);
model.$setValidity('nxEqual', isValid);
return isValid ? value : undefined;
});
}
};
});
So, if the password box’s model is login.password
then you set the following attribute on the verification box: nx-equal="login.password"
, and test for formName.elemName.$error.nxEqual
. Like so:
<form name="form">
<input type="password" ng-model="login.password">
<input type="password" ng-model="login.verify" nx-equal="login.password" name="verify">
<span ng-show="form.verify.$error.nxEqual">Must be equal!</span>
</form>
Extended version:
For a new project of mine I had to modify the above directive so that it would only display the nxEqual
error when, and only when, the verification input had a value. Otherwise the nxEqual
error should be muted. Here’s the extended version:
app.directive('nxEqualEx', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, model) {
if (!attrs.nxEqualEx) {
console.error('nxEqualEx expects a model as an argument!');
return;
}
scope.$watch(attrs.nxEqualEx, function (value) {
// Only compare values if the second ctrl has a value.
if (model.$viewValue !== undefined && model.$viewValue !== '') {
model.$setValidity('nxEqualEx', value === model.$viewValue);
}
});
model.$parsers.push(function (value) {
// Mute the nxEqual error if the second ctrl is empty.
if (value === undefined || value === '') {
model.$setValidity('nxEqualEx', true);
return value;
}
var isValid = value === scope.$eval(attrs.nxEqualEx);
model.$setValidity('nxEqualEx', isValid);
return isValid ? value : undefined;
});
}
};
});
And you would use it like so:
<form name="form">
<input type="password" ng-model="login.password">
<input type="password" ng-model="login.verify" nx-equal-ex="login.password" name="verify">
<span ng-show="form.verify.$error.nxEqualEx">Must be equal!</span>
</form>
Try it: http://jsfiddle.net/gUSZS/
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider
object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider
isn’t available in the standard angular.js script any longer.
After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:
var app = angular.module('customersApp', []);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'customersController',
templateUrl: '/app/views/customers.html'
});
});
How do you fix it?
Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:
var app = angular.module('customersApp', ['ngRoute']);
If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:
var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);
Your Code can be as follows:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/controllerone', {
controller: 'friendDetails',
templateUrl: 'controller3.html'
}, {
controller: 'friendsName',
templateUrl: 'controller3.html'
}
)
.when('/controllerTwo', {
controller: 'simpleControoller',
templateUrl: 'views.html'
})
.when('/controllerThree', {
controller: 'simpleControoller',
templateUrl: 'view2.html'
})
.otherwise({
redirectTo: '/'
});
});
There are three ways of handling business logic in AngularJS: (Inspired by Yaakov's Coursera AngularJS course) which are:
Here we are only going to talk about Service vs Factory
SERVICE:
Syntax:
app.js
var app = angular.module('ServiceExample',[]);
var serviceExampleController =
app.controller('ServiceExampleController', ServiceExampleController);
var serviceExample = app.service('NameOfTheService', NameOfTheService);
ServiceExampleController.$inject = ['NameOfTheService'] //very important as this protects from minification of js files
function ServiceExampleController(NameOfTheService){
serviceExampleController = this;
serviceExampleController.data = NameOfTheService.getSomeData();
}
function NameOfTheService(){
nameOfTheService = this;
nameOfTheService.data = "Some Data";
nameOfTheService.getSomeData = function(){
return nameOfTheService.data;
}
}
index.html
<div ng-controller = "ServiceExampleController as serviceExample">
{{serviceExample.data}}
</div>
The main features of Service:
Lazily Instantiated: If the service is not injected it won't be instantiated ever. So to use it you will have to inject it to a module.
Singleton: If it is injected to multiple modules, all will have access to only one particular instance. That is why, it is very convenient to share data across different controllers.
FACTORY
Now let's talk about the Factory in AngularJS
First let's have a look at the syntax:
app.js:
var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);
//first implementation where it returns a function
function NameOfTheFactoryOne(){
var factory = function(){
return new SomeService();
}
return factory;
}
//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
var factory = {
getSomeService : function(){
return new SomeService();
}
};
return factory;
}
Now using the above two in the controller:
var factoryOne = NameOfTheFactoryOne() //since it returns a function
factoryOne.someMethod();
var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
factoryTwo.someMethod();
Features of Factory:
This types of services follow the factory design pattern. The factory can be thought of as a central place that creates new objects or methods.
This does not only produce singleton, but also customizable services.
The .service()
method is a factory that always produces the same type of service, which is a singleton. There is no easy way to configure it's behavior. That .service()
method is usually used as a shortcut for something that doesn't require any configuration whatsoever.
This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
For IntelliJ 2019:
Intellij IDEA -> Preferences -> Build, Execution, Deployment -> Build Tools -> Gradle -> Gradle JVM
Select correct version.
If you're looking for an address (IPv4) of the specific interface say wlan0 then try this code which uses getifaddrs():
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL)
continue;
s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if((strcmp(ifa->ifa_name,"wlan0")==0)&&(ifa->ifa_addr->sa_family==AF_INET))
{
if (s != 0)
{
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("\tInterface : <%s>\n",ifa->ifa_name );
printf("\t Address : <%s>\n", host);
}
}
freeifaddrs(ifaddr);
exit(EXIT_SUCCESS);
}
You can replace wlan0 with eth0 for ethernet and lo for local loopback.
The structure and detailed explanations of the data structures used could be found here.
To know more about linked list in C this page will be a good starting point.
To get the text of the selected option
$("#your_select :selected").text();
To get the value of the selected option
$("#your_select").val();
cURL file object in procedural method:
$file = curl_file_create('full path/filename','extension','filename');
cURL file object in Oop method:
$file = new CURLFile('full path/filename','extension','filename');
$post= array('file' => $file);
$curl = curl_init();
//curl_setopt ...
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:
$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
The difference is very platform-specific.
clock() is very different on Windows than on Linux, for example.
For the sort of examples you describe, you probably want the "timeit" module instead.
There is no way to create a file without opening it There is os.mknod("newfile.txt")
(but it requires root privileges on OSX). The system call to create a file is actually open()
with the O_CREAT
flag. So no matter how, you'll always open the file.
So the easiest way to simply create a file without truncating it in case it exists is this:
open(x, 'a').close()
Actually you could omit the .close()
since the refcounting GC of CPython will close it immediately after the open()
statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.
In case you want touch
's behaviour (i.e. update the mtime in case the file exists):
import os
def touch(path):
with open(path, 'a'):
os.utime(path, None)
You could extend this to also create any directories in the path that do not exist:
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
The approach with the most upvotes (from John Doe) does somehow work for me but in my case from expected 422 rows i get only 180. I couldn't find anything wrong and there are no errors at all, so i looked for a different simple approach.
Using IF NOT FOUND THEN
after a SELECT
just works perfectly for me.
(described in PostgreSQL Documentation)
Example from documentation:
SELECT * INTO myrec FROM emp WHERE empname = myname;
IF NOT FOUND THEN
RAISE EXCEPTION 'employee % not found', myname;
END IF;
simply set Autoscroll = true
for ur windows form.. (its not good solution but helpful)..
try for panel also(Autoscroll
property = true
)
You can always format a date by extracting the parts and combine them using string functions:
var date = new Date();_x000D_
var dateStr =_x000D_
("00" + (date.getMonth() + 1)).slice(-2) + "/" +_x000D_
("00" + date.getDate()).slice(-2) + "/" +_x000D_
date.getFullYear() + " " +_x000D_
("00" + date.getHours()).slice(-2) + ":" +_x000D_
("00" + date.getMinutes()).slice(-2) + ":" +_x000D_
("00" + date.getSeconds()).slice(-2);_x000D_
console.log(dateStr);
_x000D_
Get FireBug for Mozilla Firefox.
use console.log(obj);
select t1.*, sq.*
from table1 t1,
(select a,b,c from table2 ...) sq
where ...
I had the app with multiple subdomains and session cookie was the problem between those. Clearing the cookies resolved my problem.
Also, try setting the SESSION_DOMAIN
in .env file. Use the exact subdomain you are browsing.
Check out these implementations
$(document).ready(function () {
$.ajax({
url: '/functions.php',
type: 'GET',
data: { get_param: 'value' },
success: function (data) {
for (var i=0;i<data.length;++i)
{
$('#cand').append('<div class="name">data[i].name</>');
}
}
});
});
You can do that with cat and that pipe the output to less:
cat -e yourFile | less
This excerpt from man cat
explains what -e
means:
-e equivalent to -vE
-E, --show-ends
display $ at end of each line
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
Try adding message credentials on your app.config like:
<bindings>
<basicHttpBinding>
<binding name="defaultBasicHttpBinding">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
<message clientCredentialType="Certificate" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
An alternative is to define a task that runs only on release builds.
android {
...
signingConfigs {
release {
// We can leave these in environment variables
storeFile file('nameOfKeystore.keystore')
keyAlias 'nameOfKeyAlias'
// These two lines make gradle believe that the signingConfigs
// section is complete. Without them, tasks like installRelease
// will not be available!
storePassword "notYourRealPassword"
keyPassword "notYourRealPassword"
}
}
buildTypes {
...
release {
signingConfig signingConfigs.release
...
}
}
...
}
task setupKeystore << {
final Console console = System.console();
if (console != null) {
//def keyFile = console.readLine(“\nProject: “ + project.name + “Enter keystore path: "))
//def keyAlias = console.readLine(“Project: “ + project.name + “Enter key alias: ")
def storePw = new String(console.readPassword(“Project: “ + project.name + “. Enter keystore password: "))
def keyPw = new String(console.readPassword(“Project: “ + project.name + “.Enter keystore password: "))
//android.signingConfigs.release.storeFile = file(keyFile);
//android.signingConfigs.release.keyAlias = keyAlias
android.signingConfigs.release.storePassword = storePw
android.signingConfigs.release.keyPassword = keyPw
}
}
//Validate t
def isReleaseConfig = gradle.startParameter.taskNames.any {it.contains('Release') }
if (isReleaseConfig) {
setupKeystore.execute();
}
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
You can use XML literals to sort of do this:
Dim s = <sql>
Create table article
(articleID int -- sql comment
,articleName varchar(50) <comment text="here's an xml comment" />
)
</sql>.Value
warning: XML text rules apply, like & for ampersand, < for <, etc.
Dim alertText = "Hello World"
Dim js = <script>
$(document).ready(function() {
alert('<%= alertText %>');
});
</script>.ToString 'instead of .Value includes <script> tag
note: the above is problematic when it includes characters that need to be escaped. Better to use "<script>"+js.Value+"</script>"
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
Clyde's solution works, but it is a broadcast, which I am pretty sure will be less efficient than calling a method directly. I could be mistaken, but I think the broadcasts are meant more for inter-application communication.
I'm assuming you already know how to bind a service with an Activity. I do something sort of like the code below to handle this kind of problem:
class MyService extends Service {
MyFragment mMyFragment = null;
MyFragment mMyOtherFragment = null;
private void networkLoop() {
...
//received new data for list.
if(myFragment != null)
myFragment.updateList();
}
...
//received new data for textView
if(myFragment !=null)
myFragment.updateText();
...
//received new data for textView
if(myOtherFragment !=null)
myOtherFragment.updateSomething();
...
}
}
class MyFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyFragment=null;
}
public void updateList() {
runOnUiThread(new Runnable() {
public void run() {
//Update the list.
}
});
}
public void updateText() {
//as above
}
}
class MyOtherFragment extends Fragment {
public void onResume() {
super.onResume()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=this;
}
public void onPause() {
super.onPause()
//Assuming your activity bound to your service
getActivity().mMyService.mMyOtherFragment=null;
}
public void updateSomething() {//etc... }
}
I left out bits for thread safety, which is essential. Make sure to use locks or something like that when checking and using or changing the fragment references on the service.
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
You can use xargs
which supports running many processes at a time. For your case it will be:
ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/
You can implement a static formatting method or an HTML helper, then use this syntaxe :
@using class_of_method_namespace
...
// HTML page here
@className.MethodName()
or in case of HTML Helper
@Html.MehtodName()
I just found TryParse()
has an issue that it accounts for thousands seperator. Example in En-US, 10,36.00 is ok. I had a specific scenario where the thousands seperator should not be considered and hence regex \d(\.\d)
turned out to be the best bet. Of course had to keep the decimal char variable for different locales.
I think this is the most clear solution, using an extension method:
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}
So just use it like:
var ipAddress = request.GetClientIpAddress();
We use this in our projects.
Source/Reference: Retrieving the client’s IP address in ASP.NET Web API
Try this. It uses the split
function which is a core part of javascript, nothing to do with jQuery.
var parts = html.split(":-"),
i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
$("#" + parts[i]).text(parts[i + 1]);
}
put ur js code under the form html or use $(document).ready(function(){}) and try this.
$('#inline_content input[type="radio"]').click(function(){
if($(this).val() == "walk_in"){
alert('ok');
}
});
You can also use sqlalchemy builtin function for default DateTime
from sqlalchemy.sql import func
DT = Column(DateTime(timezone=True), default=func.now())
Due to security violations, organizations may have their own repositories.
set your local repo as below.
npm config set registry https://yourorg-artifactory.com/
I hope this will solve the issue.
If you are trying to create a File from some ready path (saved in database, per example) using Linux separator, what should I do?
Maybe just use the path do create the file:
new File("/shared/folder/file.jpg");
But Windows use a different separator (\
). So, is the alternative convert the slash separator to platform independent? Like:
new File(convertPathToPlatformIndependent("/shared/folder"));
This method convertPathToPlatformIndependent
probably will have some kind of split by "/" and join with File.separator.
Well, for me, that's not nice for a language that is platform independent (right?) and Java already support the use of /
on Windows or Linux. But if you are working with paths and need to remember to this conversion every single time this will be a nightmare and you won't have any real gain for the application on the future (maybe in the universe that @Pointy described).
If you won't always have images posting to your action, you can do something like this:
[HttpPost]
public ActionResult Uploadfile(Container container, HttpPostedFileBase file)
{
//do container stuff
if (Request.Files != null)
{
foreach (string requestFile in Request.Files)
{
HttpPostedFileBase file = Request.Files[requestFile];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string directory = Server.MapPath("~/App_Data/uploads/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string path = Path.Combine(directory, fileName);
file.SaveAs(path);
}
}
}
}
The cleanest way in modern Python >=3.6
, is to use an f-string with string formatting:
>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'
Late to the game, but you can do it without @string/xyz
by using ?android:attr
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionName"
/>
<!-- or -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionCode"
/>
For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.
So I ended up by writing custom regex as below.
/^([a-z]+[\s]*[0-9]+[\s]*)+$/i
Here, I gave * in [\s]*
as it is not mandatory to have a space. A postal code may or may not contains space in my case.
One can also use stringByAppendingFormat in Swift.
var finalString : NSString = NSString(string: "Hello")
finalString = finalString.stringByAppendingFormat("%@", " World")
print(finalString) //Output:- Hello World
finalString = finalString.stringByAppendingFormat("%@", " Of People")
print(finalString) //Output:- Hello World Of People
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
.button input,
.button a {
...
}
The page you linked states
If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.
Speed issue: Any differences would be negligible for arrays this small. If you work with large arrays and speed is much more important than size, you can have a const array of the default values (initialized at compile time) and then memcpy
them to the modifiable array.
I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable which returned an IEnumerable and the properties couldn't be enumerated. This did the trick:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
List<IDataRecord> list = data.Cast<IDataRecord>().ToList();
PropertyDescriptorCollection props = null;
DataTable table = new DataTable();
if (list != null && list.Count > 0)
{
props = TypeDescriptor.GetProperties(list[0]);
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
if (props != null)
{
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
}
return table;
}
Here is a similar question to yours. (Practically the same.)
What ways are there to validate PHP code?
Edit
The top answer there suggest this resource:
http://www.meandeviation.com/tutorials/learnphp/php-syntax-check/v4/syntax-check.php
Most of the answers to this question are either outdated, ineffective, or require the inclusion of large bloated libraries:
Today, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
The only drawbacks of the Proxy
object are:
Proxy
object is not available in older browsers (such as IE11) and the polyfill cannot fully replicate Proxy
functionality.Date
) -- the Proxy
object is best paired with plain Objects or Arrays.If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I have published) which works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
I created a helper class for this by extending the new MaterialAlertDialogBuilder
Usage
new InputPopupBuilder(context)
.setInput(R.string.send,
R.string.enter_your_message,
text -> sendFeedback(text, activity))
.setTitle(R.string.contact_us)
.show();
Code
public class InputPopupBuilder extends MaterialAlertDialogBuilder {
private final Context context;
private final AppCompatEditText input;
public InputPopupBuilder(Context context) {
super(context);
this.context = context;
input = new AppCompatEditText(context);
input.setInputType(InputType.TYPE_CLASS_TEXT);
setView(input);
}
public InputPopupBuilder setInput(int actionLabel, int hint, Callback callback) {
input.setHint(hint);
input.setImeActionLabel(context.getString(actionLabel), KeyEvent.KEYCODE_ENTER);
input.setOnEditorActionListener((TextView.OnEditorActionListener) (v, actionId, event) -> {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
Editable text = input.getText();
if (text != null) {
callback.onClick(text.toString());
return true;
}
}
return false;
});
setPositiveButton(actionLabel, (dialog, which) -> {
Editable text = input.getText();
if (text != null) {
callback.onClick(text.toString());
}
});
return this;
}
public InputPopupBuilder setText(String text){
input.setText(text);
return this;
}
public InputPopupBuilder setInputType(int inputType){
input.setInputType(inputType);
return this;
}
public interface Callback {
void onClick(String text);
}
}
Requires
implementation 'com.google.android.material:material:1.3.0-alpha04'
It's easy, just use
list.Find(x => x.name == "stringNameOfObjectToFind");
I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :
import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class SessionStorage extends Storage {
isLoggedIn: boolean;
private _isLoggedInSource = new Subject<boolean>();
isLoggedIn = this._isLoggedInSource.asObservable();
constructor() {
super('session');
this.currIsLoggedIn = false;
}
setIsLoggedIn(value: boolean) {
this.setItem('_isLoggedIn', value, () => {
this._isLoggedInSource.next(value);
});
this.isLoggedIn = value;
}
}
A component that needs the current value could just then access it from the service, i.e,:
sessionStorage.isLoggedIn
Not sure if this is the right practice :)
The variable set by varStatus
is a LoopTagStatus
object, not an int. Use:
<div id="divIDNo${theCount.index}">
To clarify:
${theCount.index}
starts counting at 0
unless you've set the begin
attribute${theCount.count}
starts counting at 1
You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page
Also you can use Flash to embed the document into any HTML page like that:
<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
<p>
It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
</p>
</object>
For a 2d numpy
array, simply use imshow()
may help you:
import matplotlib.pyplot as plt
import numpy as np
def heatmap2d(arr: np.ndarray):
plt.imshow(arr, cmap='viridis')
plt.colorbar()
plt.show()
test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)
This code produces a continuous heatmap.
You can choose another built-in colormap
from here.
Change =
to ==
i.e
if (strcmp("hello", "hello") == 0)
You want to compare the result of strcmp()
to 0. So you need ==
. Assigning it to 0 won't work because rvalues cannot be assigned to.
Don't worry so much framing the button from code, you can do that on the storyboard. This worked for me, one line...more simple.
[self.button setBackgroundImage:[UIImage imageNamed: @"yourPic.png"] forState:UIControlStateNormal];
@anubhava's answer is great, but unfortunately won't work on BSD tools – i.e. it won't work with the find
that comes installed by default on macOS, because BSD find
doesn't have the -printf
operator.
So here's a variation that works with macOS + BSD (tested on my Catalina Mac), which combines BSD find
with xargs and stat
:
$ find . -type f -print0 \
| xargs -0 -n1 -I{} stat -f '%Fm %N' "{}" \
| sort -rn
While I'm here, here's BSD command sequence I like to use, which puts the timestamp in ISO-8601 format
$ find . -type f -print0 \
| xargs -0 -n1 -I{} \
stat -f '%Sm %N' -t '%Y-%m-%d %H:%M:%S' "{}" \
| sort -rn
(note that both my answers, unlike @anubhava's, pass the filenames from find
to xargs
as a single argument rather than a \0
terminated list, which changes what gets piped out at the very end)
And here's the GNU version (i.e. @anubhava's answer, but in iso-8601 format):
$ gfind . -type f -printf "%T+ %p\0" | sort -zk1nr
Related q: find lacks the option -printf, now what?
I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).
I'd recomment that you look at the OpenPCD platform if you are into development.
This is also of interest regarding the cryptographic functions in some RFID cards.
It's easiest to just use .read()
to read the partial or entire response, then write it into a file you've opened in a known good location.
do you called the ViewTreeObserver and not remove it.
mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// do nothing here can cause such problem
});
Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.
PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.
INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.
ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.
THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.
In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.
List anyObject = new ArrayList();
or
List<Object> anyObject = new ArrayList<Object>();
now anyObject
can hold objects of any type
.
use instanceof to know what kind of object it is
.
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementResponse.Redirect
simply sends a message (HTTP 302) down to the browser.
Server.Transfer
happens without the browser knowing anything, the browser request a page, but the server returns the content of another.
If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.dateFormat(new ISO8601DateFormat());
}
};
}
(Since VS2012 ...and at least until VS2017 v15.8.1)
Since it's a MFC project & CString is a MFC class, MS provides a Technical Note TN059: Using MFC MBCS/Unicode Conversion Macros and Generic Conversion Macros:
A2CW (LPCSTR) -> (LPCWSTR)
A2W (LPCSTR) -> (LPWSTR)
W2CA (LPCWSTR) -> (LPCSTR)
W2A (LPCWSTR) -> (LPSTR)
Use:
void Example() // ** UNICODE case **
{
USES_CONVERSION; // (1)
// CString to std::string / std::wstring
CString strMfc{ "Test" }; // strMfc = L"Test"
std::string strStd = W2A(strMfc); // ** Conversion Macro: strStd = "Test" **
std::wstring wstrStd = strMfc.GetString(); // wsrStd = L"Test"
// std::string to CString / std::wstring
strStd = "Test 2";
strMfc = strStd.c_str(); // strMfc = L"Test 2"
wstrStd = A2W(strStd.c_str()); // ** Conversion Macro: wstrStd = L"Test 2" **
// std::wstring to CString / std::string
wstrStd = L"Test 3";
strMfc = wstrStd.c_str(); // strMfc = L"Test 3"
strStd = W2A(wstrStd.c_str()); // ** Conversion Macro: strStd = "Test 3" **
}
--
Footnotes:
(1) In order to for the conversion-macros to have space to store the temporary length, it is necessary to declare a local variable called _convert
that does this in each function that uses the conversion macros. This is done by invoking the USES_CONVERSION
macro. In VS2017 MFC code (atlconv.h) it looks like this:
#ifndef _DEBUG
#define USES_CONVERSION int _convert; (_convert); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw; (_lpw); LPCSTR _lpa; (_lpa)
#else
#define USES_CONVERSION int _convert = 0; (_convert); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw = NULL; (_lpw); LPCSTR _lpa = NULL; (_lpa)
#endif
Upload your file to Skydrive and then right click and select "Embed". They will provide iframe snippet which you can paste in your html. This works flawlessly.
Source: Office.com
If you can use .NET 4.7.1 or newer, it will use TLS 1.2 as the minimum protocol based on the operating system capabilities. Per Microsoft recommendation :
To ensure .NET Framework applications remain secure, the TLS version should not be hardcoded. .NET Framework applications should use the TLS version the operating system (OS) supports.
Cshtml files are the ones used by Razor and as stated as answer for this question, their main advantage is that they can be rendered inside unit tests. The various answers to this other topic will bring a lot of other interesting points.
for Xcode 8:
What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.
Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.
I once saved over 50GB doing this since I did so much testing on older iOS versions.
According to the website, sizeof()
is an alias of count()
, so they should be running the same code. Perhaps sizeof()
has a little bit of overhead because it needs to resolve it to count()
? It should be very minimal though.
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
I was looking for something similar and I decided to make my own version where you can also specify a different seed if wanted (list of characters) as parameter:
CREATE FUNCTION `random_string`(length SMALLINT(3), seed VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
NO SQL
BEGIN
SET @output = '';
IF seed IS NULL OR seed = '' THEN SET seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; END IF;
SET @rnd_multiplier = LENGTH(seed);
WHILE LENGTH(@output) < length DO
# Select random character and add to output
SET @output = CONCAT(@output, SUBSTRING(seed, RAND() * (@rnd_multiplier + 1), 1));
END WHILE;
RETURN @output;
END
Can be used as:
SELECT random_string(10, '')
Which would use the built-in seed of upper- and lowercase characters + digits. NULL would also be value instead of ''.
But one could specify a custom seed while calling:
SELECT random_string(10, '1234')
Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.
In addition to the other answers, note that a multidimensional array is allocated as one big chunky object on the heap. This has some implications:
<gcAllowVeryLargeObjects>
for multidimensional arrays way before the issue will ever come up if you only ever use jagged arrays.You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
In iOS 9 and watchOS 2.0 there's a new method on CLLocationManager that lets you request the current location: CLLocationManager:requestLocation(). This completes immediately and then returns the location to the CLLocationManager delegate.
You can use an NSTimer to request a location every minute with this method now and don't have to work with startUpdatingLocation and stopUpdatingLocation methods.
However if you want to capture locations based on a change of X meters from the last location, just set the distanceFilter property of CLLocationManger and to X call startUpdatingLocation().
You can use the ObjectOutputStream
class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object
back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel ... />
</ScrollViewer>
If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the
libncurses5:i386
,libstdc++6:i386
, andzlib1g:i386
packages usingapt-get
:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
There are several ways to implement it:
For ASP.NET Standard CheckBox:
.tdInputCheckBox
{
position:relative;
top:-2px;
}
<table>
<tr>
<td class="tdInputCheckBox">
<asp:CheckBox ID="chkMale" runat="server" Text="Male" />
<asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
</td>
</tr>
</table>
For DevExpress CheckBox:
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
For RadioButtonList:
<asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
For Required Field Validators:
<asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
Write this a single line of jQuery Code
$('.hyperlink').css('pointer-events','none');
if you want to write in css file
.hyperlink{
pointer-events: none;
}
Format %lf
is a perfectly correct printf
format for double
, exactly as you used it. There's nothing wrong with your code.
Format %lf
in printf
was not supported in old (pre-C99) versions of C language, which created superficial "inconsistency" between format specifiers for double
in printf
and scanf
. That superficial inconsistency has been fixed in C99.
You are not required to use %lf
with double
in printf
. You can use %f
as well, if you so prefer (%lf
and %f
are equivalent in printf
). But in modern C it makes perfect sense to prefer to use %f
with float
, %lf
with double
and %Lf
with long double
, consistently in both printf
and scanf
.
This setup solved following issues for me:
.../
to .../123
State configuration
state('training', {
abstract: true,
url: '/training',
templateUrl: 'partials/training.html',
controller: 'TrainingController'
}).
state('training.edit', {
url: '/:trainingId'
}).
state('training.new', {
url: '/{trainingId}',
// Optional Parameter
params: {
trainingId: null
}
})
Invoking the states (from any other controller)
$scope.editTraining = function (training) {
$state.go('training.edit', { trainingId: training.id });
};
$scope.newTraining = function () {
$state.go('training.new', { });
};
Training Controller
var newTraining;
if (!!!$state.params.trainingId) {
// new
newTraining = // create new training ...
// Update the URL without reloading the controller
$state.go('training.edit',
{
trainingId : newTraining.id
},
{
location: 'replace', // update url and replace
inherit: false,
notify: false
});
} else {
// edit
// load existing training ...
}
PictureBox.Image is a property, not a method. You can set it like this:
PictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
Another way -
Suppose myResult is the dataFrame that contains your data in the form of 1 col and 23 rows
# label your columns by passing a list of names
myResult.columns = ['firstCol']
# fetch the column in this way, which will return you a series
myResult = myResult['firstCol']
print(type(myResult))
In similar fashion, you can get series from Dataframe with multiple columns.
In my scenario i have make this via below code in nginx vhost configuration
server {
server_name dashboards.etilize.com;
location / {
proxy_pass http://demo.etilize.com/dashboards/;
proxy_set_header Host $http_host;
}}
$http_host will set URL in Header same as requested
Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)
I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0
or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.
Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).
gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate |
select DisplayName, InstallDate |
fl | out-file addrem.txt
You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:
new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));
If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:
new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));
It's probably easiest to use xargs
. In your case:
ls -1 | xargs -L1 echo
The -L
flag ensures the input is read properly. From the man page of xargs
:
-L number
Call utility for every number non-empty lines read.
A line ending with a space continues to the next non-empty line. [...]
Now, back to your questions:
Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?
By using the GenerationType.SEQUENCE
strategy on the @GeneratedValue
annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).
If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE
instead, which is undesirable since the TABLE generation performs badly.
So, don't use the GenerationType.SEQUENCE
strategy with MySQL.
Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?
I assume you are talking about the GenerationType.IDENTITY
when you say database auto-increment feature
.
To use an AUTO_INCREMENT
or IDENTITY
column, you need to use the GenerationType.IDENTITY
strategy on the @GeneratedValue
annotation.
Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?
The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:
These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.
To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled
or pooled-lo
instead of hi/lo
. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled
or pooled-lo
optimizers.
Q4. Please also shed some light on
sequenceName
andallocationSize
properties of@SequenceGenerator
annotation.
The sequenceName
attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE
DDL statement.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post"
)
private Long id;
Hibernate is going to use the seq_post
database object to generate the identifier values:
SELECT nextval('hibernate_sequence')
The allocationSize
defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled
optimizer, to reduce the number of database sequence calls.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post",
allocationSize = 5
)
private Long id;
Then, when you persist 5 entities:
for (int i = 1; i <= 5; i++) {
entityManager.persist(
new Post().setTitle(
String.format(
"High-Performance Java Persistence, Part %d",
i
)
)
);
}
Only 2 database sequence calls will be executed, instead of 5:
SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)
Update 3: As other answers point out as well, the npm ci
command got introduced in npm 5.7.0 as additional way to achieve fast and reproducible builds in the CI context. See the documentation and npm blog for further information.
Update 2: The issue to update and clarify the documentation is GitHub issue #18103.
Update 1: The behaviour that was described below got fixed in npm 5.4.2: the currently intended behaviour is outlined in GitHub issue #17979.
Original answer: The behaviour of package-lock.json
was changed in npm 5.1.0 as discussed in issue #16866. The behaviour that you observe is apparently intended by npm as of version 5.1.0.
That means that package.json
can override package-lock.json
whenever a newer version is found for a dependency in package.json
. If you want to pin your dependencies effectively, you now must specify the versions without a prefix, e.g., you need to write them as 1.2.0
instead of ~1.2.0
or ^1.2.0
. Then the combination of package.json
and package-lock.json
will yield reproducible builds. To be clear: package-lock.json
alone no longer locks the root level dependencies!
Whether this design decision was good or not is arguable, there is an ongoing discussion resulting from this confusion on GitHub in issue #17979. (In my eyes it is a questionable decision; at least the name lock
doesn't hold true any longer.)
One more side note: there is also a restriction for registries that don’t support immutable packages, such as when you pull packages directly from GitHub instead of npmjs.org. See this documentation of package locks for further explanation.
join -v 2 <(sort file1) <(sort file2)
By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:
Way1
names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end
Way2
names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end
Way1 uses the table index/key
, on your table names
each element has a key starting from 1, for example:
names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John
So you just make i
go from 1 to 3.
On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:
names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end
prints the following:
1 John
2 Joe
myKey myValue
>>> x = "a (b) c (d) e"
>>> re.search(r"\(.*\)", x).group()
'(b) c (d)'
>>> re.search(r"\(.*?\)", x).group()
'(b)'
The '
*
', '+
', and '?
' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE<.*>
is matched against '<H1>title</H1>
', it will match the entire string, and not just '<H1>
'. Adding '?
' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using.*?
in the previous expression will match only '<H1>
'.
<! DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="subEmail">
<script type="text/javascript">
window.onload = function(){
var subEmail = document.getElementById("subEmail");
subEmail.onchange = function(){
if(subEmail.value == "")
{
subEmail.style.backgroundColor = "red";
}
else
{
subEmail.style.backgroundColor = "yellow";
}
};
};
</script>
</body>
I had the same exact isuue with the latest Android Studio 2.3.2 and Instant Run.
here what I did : (I'll give you two ways to achive that one disable for specefic project, and second for whole android studio):
on root of your projct open gradle-->gradle-wrapper.properties then change the value
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
and on your project build.gradle change the value
classpath 'com.android.tools.build:gradle:2.2.3'
in older version of AS settings for instant run is
File -> Other Settings -> Default Settings ->Build,Execution,Deployment
However In most recent version of Android Studio i.e 2.3.2 , instant run settings is:
Edited: If for any reason the Instant-run settings is greyed out do this :
Help-> Find Action...
and then type 'enable isntant run' and click (now you should be able to change the value in Preferences... or file->Settings... , if that was the case then this is an Android Studio bug :-)
I use such method to do this
public class HttpReqRespUtils {
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getClientIpAddressIfServletRequestExist() {
if (RequestContextHolder.getRequestAttributes() == null) {
return "0.0.0.0";
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
for (String header: IP_HEADER_CANDIDATES) {
String ipList = request.getHeader(header);
if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
String ip = ipList.split(",")[0];
return ip;
}
}
return request.getRemoteAddr();
}
}
At grub screen goto boot in recovery.
As booting hold ESC
It should take you into a gui menu. Open command and fix selinux.
Also I suggest run the clean broken packages
Returning null is usually the best idea if you intend to indicate that no data is available.
An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.
WARNING
There is now an update for ADT 23.0.1, but the Windows and Linux scripts are messed up, so wait with the upgrade!
You could check for example tools/proguard/bin/*.sh in http://dl.google.com/android/android-sdk_r23.0.1-windows.zip.
I've encountered this a couple times and keep forgetting what causes it. I ran into this when I renamed the namespace on my code behind file but not in my XAML.
So check if you've done the same.
The namespace and class names need to match since they are both part of a partial class
namespace ZZZ
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
//...
}
}
<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
Nick is right. The next error is the else should be else if (you currently have a boolean expression in your else which makes no sense). Here is what it should be
ELSE IF(@Trans_type = 'subscr_cancel')
BEGIN
SET @tmpType = 'basic'
END
You currently have the following (which is wrong):
ELSE(@Trans_type = 'subscr_cancel')
BEGIN
SET @tmpType = 'basic'
END
Here's a tip for the future- double click on the error and SQL Server management Studio will go to the line where the error resides. If you think SQL Server gives cryptic errors (which I don't think it does), then you haven't worked with Oracle!
I found that there was a syntax error in the related module and it wasn't compiling - the compiler didn't tell me that though. Just gave me the error regarding the app.config stuff. VS2010. Once I had fixed the syntax error, all was good.
IF EXISTS (
SELECT * FROM sysobjects WHERE id = object_id(N'function_name')
AND xtype IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION function_name
GO
If you want to avoid the sys* tables, you could instead do (from here in example A):
IF object_id(N'function_name', N'FN') IS NOT NULL
DROP FUNCTION function_name
GO
The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):
You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes, put multiple class values into one attribute.
<div id="foo" class="bar baz bax">
is perfectly legal.
As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.
You can defeat this behavior by using an object rather than a scalar for 'count':
{% set count = [1] %}
You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):
{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}
Since you are sending the target element to your function, you could do this to get the id:
function doStuff(item){
var id = item.attributes['data-id'].value; // 345
}
php artisan config:clear
(NOT cache)
Unions allow data members which are mutually exclusive to share the same memory. This is quite important when memory is more scarce, such as in embedded systems.
In the following example:
union {
int a;
int b;
int c;
} myUnion;
This union will take up the space of a single int, rather than 3 separate int values. If the user set the value of a, and then set the value of b, it would overwrite the value of a since they are both sharing the same memory location.
I had similar issue. The fix was ensure that your ctrollers are not only defined within script tags toward the bottom of your index.html just before the closing tag for body but ALSO validating that they are in order of how your folder is structured.
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>
With the new App Launcher YOUR APPS (not chrome extensions) stored in Users/[yourusername]/Applications/Chrome Apps/
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.
repeat
functionality is supportedYou can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr)
, you have to write (1fr)[4]
. That's it.
See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/
Grid gaps are supported in all browsers except IE. So you can use the @supports
at-rule to set the grid-gaps conditionally for all new browsers:
Example:
.grid {
display: grid;
}
.item {
margin-right: 1rem;
margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
.grid {
grid-gap: 1rem;
}
.item {
margin-right: 0;
margin-bottom: 0;
}
}
It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.
I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.
If you are using dj-database-url check the schema in your DATABASES
https://github.com/kennethreitz/dj-database-url
MySQL is
'default': dj_database_url.config(default='mysql://USER:PASSWORD@localhost:PORT/NAME')
It solves the same error even without the PORT
You set the password with:
mysql -u user -p
try
sudo chown mysql:mysql -R /var/lib/mysql
then start your mysql service
systemctl start mysqld
The accepted answer works for me only for the first 30 characters. This works for me:
select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name
If openssl installation was successfull, search for "OPENSSL" in c drive to locate the config file and set the path.
set OPENSSL_CONF=<location where cnf is available>/openssl.cnf
It worked out for me.
I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.
Another way to phrase the same idea:
If speeding up the CPU doesn't speed up your program, it may be I/O bound.
If speeding up the I/O (e.g. using a faster disk) doesn't help, your program may be CPU bound.
(I used "may be" because you need to take other resources into account. Memory is one example.)
The solution by Ben Blank wouldn't work in IE8 for me.
However this did work in IE8
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
I would like to expand on Riki_tiki_tavi's answer and get the data out there. I have created a datediff function that does almost everything sql server does. So that way we can take into account any unit.
create function datediff(units character varying, start_t timestamp without time zone, end_t timestamp without time zone) returns integer
language plpgsql
as
$$
DECLARE
diff_interval INTERVAL;
diff INT = 0;
years_diff INT = 0;
BEGIN
IF units IN ('yy', 'yyyy', 'year', 'mm', 'm', 'month') THEN
years_diff = DATE_PART('year', end_t) - DATE_PART('year', start_t);
IF units IN ('yy', 'yyyy', 'year') THEN
-- SQL Server does not count full years passed (only difference between year parts)
RETURN years_diff;
ELSE
-- If end month is less than start month it will subtracted
RETURN years_diff * 12 + (DATE_PART('month', end_t) - DATE_PART('month', start_t));
END IF;
END IF;
-- Minus operator returns interval 'DDD days HH:MI:SS'
diff_interval = end_t - start_t;
diff = diff + DATE_PART('day', diff_interval);
IF units IN ('wk', 'ww', 'week') THEN
diff = diff/7;
RETURN diff;
END IF;
IF units IN ('dd', 'd', 'day') THEN
RETURN diff;
END IF;
diff = diff * 24 + DATE_PART('hour', diff_interval);
IF units IN ('hh', 'hour') THEN
RETURN diff;
END IF;
diff = diff * 60 + DATE_PART('minute', diff_interval);
IF units IN ('mi', 'n', 'minute') THEN
RETURN diff;
END IF;
diff = diff * 60 + DATE_PART('second', diff_interval);
RETURN diff;
END;
$$;
Answer:
int i = ( Integer ) yourObject;
If, your object is an integer already, it will run smoothly. ie:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
If your object is anything else, you would need to convert it ( if possible ) to an int first:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here
Failed to open stream error occurs because the given path is wrong such as:
$uploadedFile->saveAs(Yii::app()->request->baseUrl.'/images/'.$model->user_photo);
It will give an error if the images folder will not allow you to store images, be sure your folder is readable
For csv file formate data will be in below format
"column1", "column2","column3","column4"
And if we will use field terminated by ',' then each column will get values like below.
"column1" "column2" "column3" "column4"
also if any of the column value has comma
as value then it will not work at all .
So the correct way to create a table would be by using OpenCSVSerde
create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
STORED AS TEXTFILE ;
I had a similar problem and solved it wrapping the label
into a div
and setting the following styles:
<div style="display: table; vertical-align: middle">
<label style="display: table-cell;" ... > ... </label>
</div>
// On the state
constructor() {
this.state = {
email: ''
}
}
// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}
<Input
value={this.state.email ? this.state.email : ''}
onChange={event => this.setState({ email: event.target.value)}
type="text"
name="emailAddress"
placeholder="[email protected]" />
This works, but all the children of the element with this class will also become transparent, without any way of preventing that.
.css-class-name {
opacity:0.8;
}
The simplest solution I've found is:
var text = atob(byteArray);
.button:active:hover:not([disabled]) {
/*your styles*/
}
You can try this..
If you want to clean up all your gems and start over
sudo gem clean
You can override some css
body {
padding-left: 0px !important;
padding-right: 0px !important;
}
.navbar-inner {
border-radius: 0px !important;
}
The !important
is needed just in case you link the bootstrap.css
after your custom css.
And add your nav html out of a .container
For me it was also the FragmentStatePagerAdapter
, however overriding saveState()
did not work. Here's how I fixed it:
When calling the FragmentStatePagerAdapter
constructor, keep a separate list of fragments within the class, and add a method to remove the fragments:
class PagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> items;
PagerAdapter(ArrayList<Fragment> frags) {
super(getFragmentManager()); //or getChildFragmentManager() or getSupportFragmentManager()
this.items = new ArrayList<>();
this.items.addAll(frags);
}
public void removeFragments() {
Iterator<Fragment> iter = items.iterator();
while (iter.hasNext()) {
Fragment item = iter.next();
getFragmentManager().beginTransaction().remove(item).commit();
iter.remove();
}
notifyDataSetChanged();
}
}
//...getItem() and etc methods...
}
Then in the Activity
, save the ViewPager
position and call adapter.removeFragments()
in the overridden onSaveInstanceState()
method:
private int pagerPosition;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save other view state here
pagerPosition = mViewPager.getCurrentItem();
adapter.removeFragments();
}
Lastly, in the overridden onResume()
method, re-instantiate the adapter if it isn't null
. (If it's null
, then the Activity
is being opened for the first time or after the app has been killed off by Android, in which onCreate
will do the adapter creation.)
@Override
public void onResume() {
super.onResume();
if (adapter != null) {
adapter = new PagerAdapter(frags);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(currentTabPosition);
}
}
this also works, and prolly is more readable than the echo version:
printf "`date` User `whoami` started the script.\r\n" >> output.log
Yep, I had this exact same problem. It was because I specified the android:name
attribute in the application node in the manifest file.
Your Android Manifest file probably looks something like this:
<application
android:name="Novak ESC Track guide"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:description="@string/help_text" >
android:name
attribute! unless you've implemented a custom Application object.The application:name
attribute has nothing to do with the name of your app. This is the name of a specific class to load as your Application
instance. That's why you would get the ClassNotFoundException
if that class wouldn't exist.
android:label
attribute on this same application node instead.Remove it and it should work:
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:description="@string/help_text" >
The following worked for me on Excel for Mac 2011 and Windows Excel 2002:
Using iconv on Mac, convert the file to UTF-16 Little-Endian + name it *.txt (the .txt extension forces Excel to run the Text Import Wizard):
iconv -f UTF-8 -t UTF-16LE filename.csv >filename_UTF-16LE.csv.txt
Open the file in Excel and in the Text Import Wizard choose:
PS The UTF-16LE created by iconv has BOM bytes FF FE in the beginning.
PPS My original csv file was created on a Windows 7 computer, in UTF-8 format (with the BOM bytes EF BB BF in the beginning) and used CRLF line breaks. Comma was used as field delimiter and single quote as text qualifier. It contained ASCII letters plus different latin letters with tildes, umlaut etc, plus some cyrillic. All displayed properly in both Excel for Win and Mac.
PPPS Exact software versions:
* Mac OS X 10.6.8
* Excel for Mac 2011 v.14.1.3
* Windows Server 2003 SP2
* Windows Excel 2002 v.10.2701.2625
You can use HEAD request instead of GET. It will only download the header, but not the content. Then you can check the response status from the headers.
For python 2.7.x, you can use httplib
:
import httplib
c = httplib.HTTPConnection('www.example.com')
c.request("HEAD", '')
if c.getresponse().status == 200:
print('web site exists')
or urllib2
:
import urllib2
try:
urllib2.urlopen('http://www.example.com/some_page')
except urllib2.HTTPError, e:
print(e.code)
except urllib2.URLError, e:
print(e.args)
or for 2.7 and 3.x, you can install requests
import requests
request = requests.get('http://www.example.com')
if request.status_code == 200:
print('Web site exists')
else:
print('Web site does not exist')
Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:
$ adb shell logcat | grep YouTag
# just like:
$ ps -ef | grep your_proc
For debug/release flags, see the CMAKE_BUILD_TYPE
variable (you pass it as cmake -DCMAKE_BUILD_TYPE=value
). It takes values like Release
, Debug
, etc.
https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/Useful-Variables#compilers-and-tools
cmake uses the extension to choose the compiler, so just name your files .c.
You can override this with various settings:
For example:
set_source_files_properties(yourfile.c LANGUAGE CXX)
Would compile .c files with g++. The link above also shows how to select a specific compiler for C/C++.
from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
from http://api.jquery.com/scrollTop/
$(window).scrollTop() // return the number of pixels scrolled vertically
Let's create an empty list (not required, but good to know):
> mylist <- vector(mode="list")
Let's put some stuff in it - 3 components/indexes/tags (whatever you want to call it) each with differing amounts of elements:
> mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2))
If you are interested in just the number of components in a list use:
> length(mylist)
[1] 3
If you are interested in the length of elements in a specific component of a list use: (both reference the same component here)
length(mylist[[1]])
[1] 10
length(mylist[["record1"]]
[1] 10
If you are interested in the length of all elements in all components of the list use:
> sum(sapply(mylist,length))
[1] 17
I ran into this in a Web App on Azure when attempting to connect to Blob Storage. The problem turned out to be that I had missed deploying a connection string for the blob storage so it was still pointing at the storage emulator. There must be some retry logic built into the client because I saw about 3 attempts. The /devstorageaccount1
here is a dead giveaway.
Fixed by properly setting the connection string in Azure.
In general you cannot rely on a fixed pixel size for fonts, the user may be scaling the screen and the defaults are not always the same (depends on DPI settings of the screen etc.).
Maybe have a look at this (pixel to point) and this link.
But of course you can set the font size to px, so that you do know how many pixels the font actually is. This may help if you really need a fixed layout, but this practice reduces accessibility of your web site.
http://msdn.microsoft.com/en-us/library/aa691090.aspx
C# supports two forms of string literals: regular string literals and verbatim string literals.
A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.
A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.
var startDate = "06/27/2007";
startDate = new Date(startDate);
console.log(startDate);
Tail the log as a background job (&) and it will interleave with rspec output.
tail -f log/test.log &
bundle exec rspec
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
An example here:
movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()
I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.
Take a look here: Select, Insert, Delete in Flask-SQLAlchemy
In my case the problem was that I had outdated django-stronghold
installed (0.2.9). And even though in the code I had:
from django.urls import reverse
I still encountered the error. After I upgraded the version to django-stronghold==0.4.0
the problem disappeard.
In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:
<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
my-image is a binary image file. This will load just fine.
Just a little modification to @Epsicron 's answer
SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%',
string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
('Coordination005'),
('Balance1000sheet')) as a(string)
no need for a temporary variable
If this is happening in Angular 2+ application, you can just uncomment string polyfills in polyfills.ts:
import 'core-js/es6/string';
while (fscanf(input,"%s",arr) != EOF && count!=7) {
len=strlen(arr);
count++;
}
From the PHP online documentation:
To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
When converting to boolean, the following values are considered FALSE:
FALSE
itself 0.0
(zero) "0"
NULL
(including unset variables) TRUE
(including any resource). So, in most cases, it's the same.
On the other hand, the ===
and the ==
are not the same thing. Regularly, you just need the "equals" operator. To clarify:
$a == $b //Equal. TRUE if $a is equal to $b.
$a === $b //Identical. TRUE if $a is equal to $b, and they are of the same type.
For more information, check the "Comparison Operators" page in the PHP online docs.
Hope this helps.
You are halfway there. Try:
In [4]: a[a < 0] = 0
In [5]: a
Out[5]: array([1, 2, 3, 0, 5])
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
AppSettings.Set
does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);
, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0]
you will see it change from "English" to "Russian" when that line of code runs.
The following code (used in a console application) will persist the change.
class Program
{
static void Main(string[] args)
{
UpdateSetting("lang", "Russian");
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
From this post: http://vbcity.com/forums/t/152772.aspx
One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.
i was faced this issue when ever the eclipse is not closed (kill eclipse process the from task manager or computer power off), i was tried below steps, it worked for me.
1) Remove the file names start with ".fileTable" from this folder
C:\eclipse\configuration\org.eclipse.osgi.manager
2) Remove the log files like text files start with numeric names from this folder
C:\eclipse\configuration
3) Open Command prompt(cmd) navigate to this folder
C:\eclipse
type below command
eclipse clean start
var fileStream = fs.createWriteStream('/path/to/file.jpg');
var s3Stream = s3.getObject({Bucket: 'myBucket', Key: 'myImageFile.jpg'}).createReadStream();
// Listen for errors returned by the service
s3Stream.on('error', function(err) {
// NoSuchKey: The specified key does not exist
console.error(err);
});
s3Stream.pipe(fileStream).on('error', function(err) {
// capture any errors that occur when writing data to the file
console.error('File Stream:', err);
}).on('close', function() {
console.log('Done.');
});
Reference: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
HTML in line styling example:
<td style='text-align:center; vertical-align:middle'></td>
CSS file example:
td {
text-align: center;
vertical-align: middle;
}
If the datepicker is in a row of a grid, try something like
editoptions : {
dataInit : function (e) {
$(e).datepicker({
onSelect : function (ev) {
// here your code
}
});
}
}
This is a dynamic solution which works with all value types including objects :
class Session extends Map {
set(id, value) {
if (typeof value === 'object') value = JSON.stringify(value);
sessionStorage.setItem(id, value);
}
get(id) {
const value = sessionStorage.getItem(id);
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
}
Then :
const session = new Session();
session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');
$(this).attr("name")
means the name of the select tag not option name.
To get option name
$("#band_type_choices option:selected").attr('name');
Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
Not sure if this helps, but with XSL, I'd do something like:
<xsl:for-each select="a/b">
<xsl:value-of select="c"/>
<xsl:value-of select="d"/>
<xsl:value-of select="e"/>
</xsl:for-each>
and won't this XPath select all children of B nodes:
a/b/*
You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType()
method:
u.GetType().Equals(t);
or
u.GetType.Equals(typeof(User));
should do it. Obviously you could use '==' to do your comparison if you prefer.
Here is clone function that will perform deep copy of the object:
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = new obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
Now you can you use like this:
(function(x){
var obj = clone(x);
obj.foo = 'foo';
obj.bar = 'bar';
})(o)
If the array contains both positive and negative data, I'd go with:
import numpy as np
a = np.random.rand(3,2)
# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)
# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)
# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1
If the array contains nan
, one solution could be to just remove them as:
def nan_ptp(a):
return np.ptp(a[np.isfinite(a)])
b = (a - np.nanmin(a))/nan_ptp(a)
However, depending on the context you might want to treat nan
differently. E.g. interpolate the value, replacing in with e.g. 0, or raise an error.
Finally, worth mentioning even if it's not OP's question, standardization:
e = (a - np.mean(a)) / np.std(a)
You can find the execution time in second with a single function.
// ampersand is important thing here
function microSec( & $ms ) {
if (\floatval( $ms ) == 0) {
$ms = microtime( true );
}
else {
$originalMs = $ms;
$ms = 0;
return microtime( true ) - $originalMs;
}
}
// you don't have to define $ms variable. just function needs
// it to calculate the difference.
microSec($ms);
sleep(10);
echo microSec($ms) . " seconds"; // 10 seconds
for( $i = 0; $i < 10; $i++) {
// you can use same variable everytime without assign a value
microSec($ms);
sleep(1);
echo microSec($ms) . " seconds"; // 1 second
}
for( $i = 0; $i < 10; $i++) {
// also you can use temp or useless variables
microSec($xyzabc);
sleep(1);
echo microSec($xyzabc) . " seconds"; // 1 second
}
Note: This answer predates the Unicode requirement; see the comments.
Just cast it:
CString s;
const TCHAR* x = (LPCTSTR) s;
It works because CString has a cast operator to do exactly this.
Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char
instead of TCHAR
.
Hope this will help someone.
public static String getDate(
String date, String currentFormat, String expectedFormat)
throws ParseException {
// Validating if the supplied parameters is null
if (date == null || currentFormat == null || expectedFormat == null ) {
return null;
}
// Create SimpleDateFormat object with source string date format
SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
// Parse the string into Date object
Date dateObj = sourceDateFormat.parse(date);
// Create SimpleDateFormat object with desired date format
SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
// Parse the date into another format
return desiredDateFormat.format(dateObj).toString();
}
$("#frame").click(function () {
this.src="http://www.google.com/";
});
Sometimes plain JavaScript is even cooler and faster than jQuery ;-)
USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up
sudo systemctl enable postgresql
DISABLE exists as well ofc
Some DOC: freedesktop man systemctl
One can rename indexes the same way:
alter index owner.index_name rename to new_name;
Finally, got the project compiled in Xcode with a clean build. I have to run this first.
rm -rf ~/Library/Developer/Xcode/DerivedData/*
Then the building is ok. ref
Well, you could have the javascript file being built by any of the scripting languages, injecting your variables into the file on every request. You would have to tell your webserver to not dish out js-files statically (using mod_rewrite would suffice).
Be aware though that you lose any caching of these js-files as they are altered constantly.
Bye.
Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:
<root>
<level value="ALL" />
<appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
<level value="ALL" />
<appender-ref ref="File1Appender2" />
</logger>
This is how I have done it in the past. Then something like this for the other log:
private static readonly ILog otherLog = LogManager.GetLogger("SomeName");
And you can get your normal logger as follows:
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Read the loggers and appenders section of the documentation to understand how this works.
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null
and not for empty strings then you can also use ifnull()
or coalesce(field1, 'empty')
. But that is not suitable for empty strings.
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
This will work for sure I guess...
// Declare
Menu menu;
MenuItem menuDoneItem;
// Then in your onCreateOptionMenu() method write the following...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu=menu;
inflater.inflate(R.menu.secutity, menu);
}
// In your onOptionItemSelected() method write the following...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.done_item:
this.menuDoneItem=item;
someOperation();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
menuRefresh.setVisible(false); // make true to make the menu item visible.
}
//Use the above method whenever you need to make your menu item visible or invisiable
You can also refer this link for more details, it is a very useful one.
try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags
/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
public synchronized void addToList(String mapKey, Item myItem) {
List<Item> itemsList = items.get(mapKey);
// if list does not exist create it
if(itemsList == null) {
itemsList = new ArrayList<Item>();
itemsList.add(myItem);
items.put(mapKey, itemsList);
} else {
// add if item is not already in list
if(!itemsList.contains(myItem)) itemsList.add(myItem);
}
}
Don't forget to do this,
Select the Project -- > Build Settings. Search PROVISIONING_PROFILE and delete whatever nonsense is there.
If you're using xml background instead of IMG, just remove this :
<item>
<bitmap android:src="@drawable/YOURIMAGE"/>
</item>
from the 1st answer that @Ljdawson gave us.
What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.
SELECT julianday('now') - julianday(DateCreated) FROM Payment;
Hi you can do this in the following way
var username = '';
var password = ''
const token = `${username}:${password}`;
const encodedToken = Buffer.from(token).toString('base64');
const session_url = 'http://api_address/api/session_endpoint';
var config = {
method: 'get',
url: session_url,
headers: { 'Authorization': 'Basic '+ encodedToken }
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
{!! Form::text('firstname', null !!}
@if($errors->has('firstname'))
{{ $errors->first('firstname') }}
@endif
To save and load an arraylist of public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
Here is a solution that does not require functions to get an accurate count for each table:
select table_schema,
table_name,
(xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count
from (
select table_name, table_schema,
query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
from information_schema.tables
where table_schema = 'public' --<< change here for the schema you want
) t
query_to_xml
will run the passed SQL query and return an XML with the result (the row count for that table). The outer xpath()
will then extract the count information from that xml and convert it to a number
The derived table is not really necessary, but makes the xpath()
a bit easier to understand - otherwise the whole query_to_xml()
would need to be passed to the xpath()
function.
There might be more than just one php.ini file. For example, when using WAMP there are 2 php.ini files in following directories:
C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\php\php5.5.12
You need to edit the first one.
Error Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID =dbo.SubModule.subModuleID
Solution Code
FROM
dbo.Category C LEFT OUTER JOIN
dbo.SubCategory SC ON C.categoryID = SC.CategoryID AND C.IsActive = 'True' LEFT OUTER JOIN
dbo.Module M ON SC.subCategoryID = M.subCategoryID AND SC.IsActive = 'True' LEFT OUTER JOIN
dbo.SubModule SM ON M.ModuleID = SM.ModuleID AND M.IsActive = 'True' AND SM.IsActive = 'True' LEFT OUTER JOIN
dbo.trainer ON dbo.trainer.TopicID = SM.subModuleID
as you can see, in error code, dbo.SubModule
is already defined as SM, but I am using dbo.SubModule
in next line, hence there was an error.
use declared name instead of actual name. Problem solved.
Be very careful when using find
and sed
in a git repo! If you don't exclude the binary files you can end up with this error:
error: bad index file sha1 signature
fatal: index file corrupt
To solve this error you need to revert the sed
by replacing your new_string
with your old_string
. This will revert your replaced strings, so you will be back to the beginning of the problem.
The correct way to search for a string and replace it is to skip find
and use grep
instead in order to ignore the binary files:
sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")
Credits for @hobs
In IntelliJ Do as they say in eclipse "If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:
Right click your project folder and open up Properties.
From the right panel, select Java Build Path then go to Libraries tab.
Select Add External JARs to import the mysql driver.
From the right panel, select Deployment Assembly.
Select Add..., then select Java Build Path Entries and click Next.
You should see the sql driver on the list. Select it and click first.
And that's it! Try to run it again! Cheers!"
Here we have to add the jar file in Project Structure -> Libraries -> +(add)
This is a common problem with people getting started. Whenever you update your UI elements from a thread other than the main thread, you need to use:
this.Dispatcher.Invoke(() =>
{
...// your code here.
});
You can also use control.Dispatcher.CheckAccess()
to check whether the current thread owns the control. If it does own it, your code looks as normal. Otherwise, use above pattern.
You are so close!
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')
cursor = cnxn.cursor()
cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
print row
(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).