Your question isn't at all clear I'm afraid. A key doesn't have a "name"; it's not "called" anything as far as the map is concerned - it's just a key, and will be compared with other keys. If you have lots of different kinds of keys, I strongly suggest you put them in different maps for the sake of sanity.
If this doesn't help, please clarify the question - preferrably with some code to show what you mean.
You can change time() to now() for it to work
from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)
The answer to your question is that the newer SQLite 3 has improved performance, use that.
This answer Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly? by SqlAlchemy Orm Author has 100k inserts in 0.5 sec, and I have seen similar results with python-sqlite and SqlAlchemy. Which leads me to believe that performance has improved with SQLite 3.
If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:
.profile
, or whatever is appropriate, and put /usr/local/bin
at the start
of your PATH
so that Homebrew binaries are found before system binariesbrew install python
- this installs a newer version of python in /usr/local
pip install pandas
This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
I'd remove the autoplay
attribute, since if the browser encounters it, it autoplays!
autoplay
is a HTML boolean attribute, but be aware that the values true
and false
are not allowed. To represent a false
value, you must omit the attribute.
The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
Also, the type goes inside the source, like this:
<video width="640" height="480" controls preload="none">
<source src="http://example.com/mytestfile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
References:
AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.
For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.
The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.
If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.
SQL is Structured Query Language
MySQL is a relational database management system. You can submit SQL queries to the MySQL database to store, retrieve, modify or delete data.
Bubble sort is almost useless under all circumstances. In use cases when insertion sort may have too many swaps, selection sort can be used because it guarantees less than N times of swap. Because selection sort is better than bubble sort, bubble sort has no use cases.
If each pixel is assumed to be of the same area then the following article about converting distances to longitude/latitude co-ordinates may be of some help to you:
http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/
You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:
IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;
You can then access each option as an IWebElement, such as:
IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");
Easiest way to get it by using date pattern - h:mm a
, where
Code snippet :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
My problem was the wrong port number for mongoDB
server.
I had:
DATABASE_URL= "mongodb://localhost:3000/node-express-mongodb-server"
in my .env
file (my environmental variables), but I had written it before running mongoDB server
. So when I ran the mongoDB server
, it wrote a different port number and I had to change it. I changed it to the right port number (which was written on my cmd window by mongoDB
):
DATABASE_URL= "mongodb://localhost:27017/node-express-mongodb-server"
and now it works fine.
To print off_t
:
printf("%jd\n", (intmax_t)x);
To print size_t
:
printf("%zu\n", x);
To print ssize_t
:
printf("%zd\n", x);
See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html
If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.
For example if your compiler has long long
and your standard library supports %lld
, you can confidently expect that will serve in place of intmax_t
. But if it doesn't, you'll have to fall back to long
, which would fail on some other implementations because it's too small.
As @deanchiu said it may happen when you move the whole project to another path or server.
But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.
> php artisan route:clear
> php artisan config:clear
self.labelText = 'change the value'
The above sentence makes labelText change the value, but not change depositLabel's text.
To change depositLabel's text, use one of following setences:
self.depositLabel['text'] = 'change the value'
OR
self.depositLabel.config(text='change the value')
Adding a reference to this System.Runtime.dll assembly fixed the issue:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll
Though that file in that explicit path doesn't exist on the build server.
I will post back with more information once I've found some documentation on PCL and these Facades.
Update
Yeah pretty much nothing on facade assemblies on the whole internet.
Google:
(Facades OR Facade) Portable Library site:microsoft.com
You need to use ==
or ===
for comparison. =
assigns a new value.
Besides that, using ==
is pointless when dealing with booleans only. Just use if(foo)
instead of if(foo == true)
.
Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile
.
With inconsistent versions, specifically with one being Client Profile
and the other not, then it works at design time but fails at compile time. A real gotcha.
There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile
, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...
Python:
driver.get(url)
content=driver.page_source
if content.find("text_to_search"):
print("text is present in the webpage")
Download the html page and use find()
The approved answer is great, but if you're looking for a 1 minute answer try this:
MyClass.h file should look like this (add delegate lines with comments!)
#import <BlaClass/BlaClass.h>
@class MyClass; //define class, so protocol can see MyClass
@protocol MyClassDelegate <NSObject> //define delegate protocol
- (void) myClassDelegateMethod: (MyClass *) sender; //define delegate method to be implemented within another class
@end //end protocol
@interface MyClass : NSObject {
}
@property (nonatomic, weak) id <MyClassDelegate> delegate; //define MyClassDelegate as delegate
@end
MyClass.m file should look like this
#import "MyClass.h"
@implementation MyClass
@synthesize delegate; //synthesise MyClassDelegate delegate
- (void) myMethodToDoStuff {
[self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class
}
@end
To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:
#import "MyClass.h"
@interface MyVC:UIViewController <MyClassDelegate> { //make it a delegate for MyClassDelegate
}
MyVC.m:
myClass.delegate = self; //set its delegate to self somewhere
Implement delegate method
- (void) myClassDelegateMethod: (MyClass *) sender {
NSLog(@"Delegates are great!");
}
Short answer without importing matplotlib as mpl
plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))
Modified from @AlexG's answer
If possible try this one instant solution:
Intent intent =new Intent(getApplicationBaseContext,second_Act.class);
StartActivity(intent);
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
You can also use @ComponentScans annotation:
@ComponentScans(value = { @ComponentScan("com.my.package.first"),
@ComponentScan("com.my.package.second") })
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.
That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!
<style>
html, body {
height: 100%;
}
#tableContainer-1 {
height: 100%;
width: 100%;
display: table;
}
#tableContainer-2 {
vertical-align: middle;
display: table-cell;
height: 100%;
}
#myTable {
margin: 0 auto;
}
</style>
<div id="tableContainer-1">
<div id="tableContainer-2">
<table id="myTable" border>
<tr><td>Name</td><td>J W BUSH</td></tr>
<tr><td>Proficiency</td><td>PHP</td></tr>
<tr><td>Company</td><td>BLAH BLAH</td></tr>
</table>
</div>
</div>
You can also use myform.$invalid
E.g.
if($scope.myform.$invalid){return;}
I use git add --patch
quite a bit and wanted something like this to avoid having to hit d all the time through the same files. I whipped up a very hacky couple of git aliases to get the job done:
[alias]
HELPER-CHANGED-FILTERED = "!f() { git status --porcelain | cut -c4- | ( [[ \"$1\" ]] && egrep -v \"$1\" || cat ); }; f"
ap = "!git add --patch -- $(git HELPER-CHANGED-FILTERED 'min.(js|css)$' || echo 'THIS_FILE_PROBABLY_DOESNT_EXIST' )"
In my case I just wanted to ignore certain minified files all the time, but you could make it use an environment variable like $GIT_EXCLUDE_PATTERN
for a more general use case.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant
and then assigning it to Empty
. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty
.
Sub TestforEmpty()
Dim dt As Variant
dt = Empty
Dim today As Date
today = Date
If today = Date Then
dt = today
End If
If IsEmpty(dt) Then
MsgBox "It not is today"
Else
MsgBox "It is today"
End If
End Sub
Just adding another possibility as it might help someone that's trying to both iterate over an array AND maintain a count. For example, the code below goes through an array named items
and only displays the first 3 items. Notice that the each
and the if
are native jade and don't need a hyphen.
ul
- var count = 0;
each item in items
if count < 3
li= item.name
- count++;
The function call operator.
class Foo:
def __call__(self, a, b, c):
# do something
x = Foo()
x(1, 2, 3)
The __call__ method can be used to redefined/re-initialize the same object. It also facilitates the use of instances/objects of a class as functions by passing arguments to the objects.
in ts
isArray(obj: any)
{
return Array.isArray(obj)
}
in html
(photos == undefined || !(isArray(photos) && photos.length > 0) )
Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.
Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater
.
The code is the following, where this
is an Activity:
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);
landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);
You need to get the inflater for this
context, access the root view through the inflate method and finally call findViewById
on the root view of the layout.
Hope this is useful for someone! Bye
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.
String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);
Make sure you check string length is more than 10.
You can make a simple setInterval.
function someJsClass()_x000D_
{_x000D_
var _resizeInterval = null;_x000D_
var _lastHeight = 0;_x000D_
var _lastWidth = 0;_x000D_
_x000D_
this.Initialize = function(){_x000D_
var _resizeInterval = setInterval(_resizeIntervalTick, 200);_x000D_
};_x000D_
_x000D_
this.Stop = function(){_x000D_
if(_resizeInterval != null)_x000D_
clearInterval(_resizeInterval);_x000D_
};_x000D_
_x000D_
var _resizeIntervalTick = function () {_x000D_
if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {_x000D_
_lastWidth = $(contentBox).width();_x000D_
_lastHeight = $(contentBox).height();_x000D_
DoWhatYouWantWhenTheSizeChange();_x000D_
}_x000D_
};_x000D_
}_x000D_
_x000D_
var class = new someJsClass();_x000D_
class.Initialize();
_x000D_
EDIT:
This is a example with a class. But you can do something easiest.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
Contributing with a minified polyfill for window.atob
+ window.btoa
that I'm currently using.
(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();
I am assuming Basic authentication here.
$cred = Get-Credential
Invoke-WebRequest -Uri 'https://whatever' -Credential $cred
You can get your credential through other means (Import-Clixml
, etc.), but it does have to be a [PSCredential]
object.
GitHub is breaking RFC as they explain in the link you provided:
The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The main difference is that the RFC requires unauthenticated requests to be answered with 401 Unauthorized responses. In many places, this would disclose the existence of user data. Instead, the GitHub API responds with 404 Not Found. This may cause problems for HTTP libraries that assume a 401 Unauthorized response. The solution is to manually craft the Authorization header.
Powershell's Invoke-WebRequest
does to my knowledge wait for a 401 response before sending the credentials, and since GitHub never provides one, your credentials will never be sent.
Instead you'll have to create the basic auth headers yourself.
Basic authentication takes a string that consists of the username and password separated by a colon user:pass
and then sends the Base64 encoded result of that.
Code like this should work:
$user = 'user'
$pass = 'pass'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = @{
Authorization = $basicAuthValue
}
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers
You could combine some of the string concatenation but I wanted to break it out to make it clearer.
Why not just use .show()/.hide()
instead?
$("#menu").hover(function(){
$('.flyout').show();
},function(){
$('.flyout').hide();
});
PowerShell code to find all document library files modified from last 2 days.
$web = Get-SPWeb -Identity http://siteName:9090/
$list = $web.GetList("http://siteName:9090/Style Library/")
$folderquery = New-Object Microsoft.SharePoint.SPQuery
$foldercamlQuery =
'<Where> <Eq>
<FieldRef Name="ContentType" /> <Value Type="text">Folder</Value>
</Eq> </Where>'
$folderquery.Query = $foldercamlQuery
$folders = $list.GetItems($folderquery)
foreach($folderItem in $folders)
{
$folder = $folderItem.Folder
if($folder.ItemCount -gt 0){
Write-Host " find Item count " $folder.ItemCount
$oldest = $null
$files = $folder.Files
$date = (Get-Date).AddDays(-2).ToString(“MM/dd/yyyy”)
foreach ($file in $files){
if($file.Item["Modified"]-Ge $date)
{
Write-Host "Last 2 days modified folder name:" $folder " File Name: " $file.Item["Name"] " Date of midified: " $file.Item["Modified"]
}
}
}
else
{
Write-Warning "$folder['Name'] is empty"
}
}
In my case, it was UWP project present in the solution causing the issue.
When I unloaded the UWP project, tests were discovered. When I loaded it back, test disappeard again.
Try to unload all projects and keep test project only. Ten rebuild solution and test shound appear in Test Runner. Load projects one by one and rebuild solution each time to find out what project are causing the problem
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
You can find the list
of duplicate
names using the following aggregate
pipeline:
Group
all the records having similar name
.Match
those groups
having records greater than 1
.group
again to project
all the duplicate names as an array
.The Code:
db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])
o/p:
{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }
I did this with anaconda navigator. I installed anaconda navigator and created two different development environments with different python versions
and switch between different python versions by switching or activating and deactivating environments.
first install anaconda navigator and then create environments.
see help here on how to manage environments
https://docs.anaconda.com/anaconda/navigator/tutorials/manage-environments/
Here is the video to do it with conda
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
For anyone getting to this thread late, you may want to take a look back at the .Net Base Class Library (BCL). Many people missed the changes between .Net 1.1 and .Net 2.0 when the TraceSource class was introduced (circa 2005).
Using the TraceSource is analagous to other logging frameworks, with granular control of logging, configuration in app.config/web.config, and programmatic access - without the overhead of the enterprise application block.
There are also a number of comparisons floating around: "log4net vs TraceSource"
here is my code to find the next empty row for example in first row 'A'. To use it for any other row just change cells(i,2 or 3 or 4 so on)
Sheets("Sheeet1").Select
for i=1 to 5000
if cells(i,1)="" then nextEmpty=i goto 20
next i
20 'continue your code here
enter code here
a) object Class "Long" versus primitive type "long". (At least in Java)
b) There are different (even unclear) memory-sizes of the primitive types:
Java - all clear: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
C .. just mess: https://en.wikipedia.org/wiki/C_data_types
Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.
As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."
So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.
So you could have something like this:
<html>
<head>
<!-- Style sheet references and CSS definitions -->
</head>
<body>
<!-- HTML markup and other page content -->
<!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
</body>
</html>
If you want to completely wipe the database and resync it in the same go you need something like the following. I also combine adding test data in this command:
#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") # Replace with your app name.
from django.db import connection
from django.core.management import call_command
from django.conf import settings
# If you're using postgres you can't use django's sql stuff for some reason that I
# can't remember. It has to do with that autocommit thing I think.
# import psychodb2 as db
def recreateDb():
print("Wiping database")
dbinfo = settings.DATABASES['default']
# Postgres version
#conn = db.connect(host=dbinfo['HOST'], user=dbinfo['USER'],
# password=dbinfo['PASSWORD'], port=int(dbinfo['PORT'] or 5432))
#conn.autocommit = True
#cursor = conn.cursor()
#cursor.execute("DROP DATABASE " + dbinfo['NAME'])
#cursor.execute("CREATE DATABASE " + dbinfo['NAME'] + " WITH ENCODING 'UTF8'") # Default is UTF8, but can be changed so lets be sure.
# Mysql version:
print("Dropping and creating database " + dbinfo['NAME'])
cursor = connection.cursor()
cursor.execute("DROP DATABASE " + dbinfo["NAME"] + "; CREATE DATABASE " + dbinfo["NAME"] + "; USE " + dbinfo["NAME"] + ";")
print("Done")
if __name__ == "__main__":
recreateDb();
print("Syncing DB")
call_command('syncdb', interactive=False)
print("Adding test data")
addTestData() # ...
It would be nice to be able to do cursor.execute(call_command('sqlclear', 'main'))
but call_command
prints the SQL to stdout rather than returning it as a string, and I can't work out the sql_delete
code...
i know this is old, i actually just had the same issue. i was able to solve it by running npm install -g node-gyp
and fixed! npm
A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.
// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
// set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);
}
Try this:
CREATE TABLE #t(
[name] varchar NULL,
[val] [int] NULL,
[ID] [int] NULL
) ON [PRIMARY]
insert into #t (id,name,val) values
(1,'A',10), (2,'B',20), (3,'C',30)
select t1.id, t1.val, SUM(t2.val) as cumSum
from #t t1 inner join #t t2 on t1.id >= t2.id
group by t1.id, t1.val order by t1.id
I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.
Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl
implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.
Change callSoapWebService
method first line to following.
SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();
I hope it will be helpful to others.
You can call handleInputs()
add in your submit function before ajax
function handleInputs(){
$('input[type=checkbox]').each(function() {
if (!this.checked) {
$(this).attr("value","0");
}else{
$(this).attr("value","1");
}
});
}
It is perfectly working
Check this: http://jsfiddle.net/h7kRt/1/,
you should change in jsfiddle on top-left to No-wrap in <head>
Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.
Both {} and && will cause problems due to being expanded by the command line. I would suggest trying:
find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i \{} -sameq \{}.mp3 \; -exec rm \{} \;
REST is an architecture.
REST will give human-readable results.
REST is stateless.
REST services are easily cacheable.
SOAP is a protocol. It can run on top of JMS, FTP, and HTTP.
Strings are immutable. You can use the string builder class to help!:
string str = "valta is the best place in the World";
StringBuilder strB = new StringBuilder(str);
strB[0] = 'M';
Try this:
<div id="mainTable" style="width:100px; height:200px;"></div>
$(document).ready(function() {
$("#mainTable").width(100).height(200);
}) ;
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
For special characters:
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
I've continued to research this item myself, and it does appear to remain beyond us at this point.
I even tried buying a Apple Composite AV Cable, but it doesn't capture screen, just video playing like YouTube, etc.
So I decided to go with the iShowU path and that has worked out well so far.
Thanks Guys!
This example puts an asterisk symbol in front of a label to denote that particular input as a required field. I set the CSS properties using % and em to makesure my webpage is responsive. You could use px or other absolute units if you want to.
#name {_x000D_
display: inline-block;_x000D_
margin-left: 40%;_x000D_
font-size:25px;_x000D_
_x000D_
}_x000D_
.nameinput{_x000D_
margin-left: 10px;_x000D_
font-size:90%;_x000D_
width: 17em;_x000D_
_x000D_
}_x000D_
_x000D_
.nameinput::placeholder {_x000D_
font-size: 0.7em;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
#name p{_x000D_
margin:0;_x000D_
border:0;_x000D_
padding:0;_x000D_
display:inline-block;_x000D_
font-size: 40%;_x000D_
vertical-align: super;_x000D_
}
_x000D_
<label id="name" value="name">_x000D_
<p>*</p> _x000D_
Name: <input class="nameinput" type="text" placeholder="Enter your name" required>_x000D_
</label>
_x000D_
You could always do $('input[name="somename"]')
I did this with std::function and std::bind..
I wrote this EventManager class that stores a vector of handlers in an unordered_map that maps event types (which are just const unsigned int, I have a big namespace-scoped enum of them) to a vector of handlers for that event type.
In my EventManagerTests class, I set up an event handler, like this:
auto delegate = std::bind(&EventManagerTests::OnKeyDown, this, std::placeholders::_1);
event_manager.AddEventListener(kEventKeyDown, delegate);
Here's the AddEventListener function:
std::vector<EventHandler>::iterator EventManager::AddEventListener(EventType _event_type, EventHandler _handler)
{
if (listeners_.count(_event_type) == 0)
{
listeners_.emplace(_event_type, new std::vector<EventHandler>());
}
std::vector<EventHandler>::iterator it = listeners_[_event_type]->end();
listeners_[_event_type]->push_back(_handler);
return it;
}
Here's the EventHandler type definition:
typedef std::function<void(Event *)> EventHandler;
Then back in EventManagerTests::RaiseEvent, I do this:
Engine::KeyDownEvent event(39);
event_manager.RaiseEvent(1, (Engine::Event*) & event);
Here's the code for EventManager::RaiseEvent:
void EventManager::RaiseEvent(EventType _event_type, Event * _event)
{
if (listeners_.count(_event_type) > 0)
{
std::vector<EventHandler> * vec = listeners_[_event_type];
std::for_each(
begin(*vec),
end(*vec),
[_event](EventHandler handler) mutable
{
(handler)(_event);
}
);
}
}
This works. I get the call in EventManagerTests::OnKeyDown. I have to delete the vectors come clean up time, but once I do that there are no leaks. Raising an event takes about 5 microseconds on my computer, which is circa 2008. Not exactly super fast, but. Fair enough as long as I know that and I don't use it in ultra hot code.
I'd like to speed it up by rolling my own std::function and std::bind, and maybe using an array of arrays rather than an unordered_map of vectors, but I haven't quite figured out how to store a member function pointer and call it from code that knows nothing about the class being called. Eyelash's answer looks Very Interesting..
From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?
For all Windows platforms:
1) Download the .WHL package install file.
2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].
3) Make sure the latest version of pip.EXE is now installed. At this time of posting:
pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
4) Run pip.EXE in an Admin command shell.
- Open an Admin privileged command shell.
> easy_install.EXE --upgrade pip
- Check the pip.EXE version:
> pip.EXE --version
pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)
> pip.EXE install --use-wheel --no-index
--find-links="X:\path to wheel file\DownloadedWheelFile.whl"
Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.
man wget: -O file --output-document=file
wget "url" -O /tmp/cron_test/<file>
It depends what you're going for. I believe the closest thing JS has to print is:
document.write( produceMessage() );
However, it may be more prudent to place the value inside a span or a div of your choosing like:
document.getElementById("mySpanId").innerHTML = produceMessage();
"cat".split("(?!^)")
This will produce
array ["c", "a", "t"]
Found the solution as below.... posting it as it could help somebody else too :)
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
Output:
2014-04-24T11:15:00.000+02:00
The biggest draw back I've found with using ConfigureAwait(false) is that the thread culture is reverted to the system default. If you've configured a culture e.g ...
<system.web>
<globalization culture="en-AU" uiCulture="en-AU" />
...
and you're hosting on a server whose culture is set to en-US, then you will find before ConfigureAwait(false) is called CultureInfo.CurrentCulture will return en-AU and after you will get en-US. i.e.
// CultureInfo.CurrentCulture ~ {en-AU}
await xxxx.ConfigureAwait(false);
// CultureInfo.CurrentCulture ~ {en-US}
If your application is doing anything which requires culture specific formatting of data, then you'll need to be mindful of this when using ConfigureAwait(false).
Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.
Here are a couple of possibilities that I can propose:
I'd go with option 3 in most of cases. It's not hard.
Note that Ghostdriver has an API for it but it's not supported by other drivers.
I suspect that your GIT_SSH
environment variable is set to %ProgramFiles(x86)%\putty\plink.exe
.
For some reason, PLink does not use the .ssh/known_hosts
file in your user directory to store the remote hosts keys.
If this is actually your case, and it might be so on purpose if you want to use pageant, you need to use PLink to connect to the host first.
"$GIT_SSH" user@hostname
You should get a similar message
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
Once you have answered y
to the question and successfully connected to the remote host, you should be all set. Go ahead and try your push again.
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
You probably want the answer to "How to call an external command in Python".
The simplest approach is to use the os.system
function, e.g.:
import os
os.system("some_command &")
Basically, whatever you pass to the system
function will be executed the same as if you'd passed it to the shell in a script.
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent
so you don't need to wrap it with a call to Html.Raw()
.
It should be as simple as:
<script>
var json = @Json.Serialize(Model.CollegeInformationlist);
</script>
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
here is simple code
List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());
OS X doesn't use bash 4 yet, nor does it have /usr/bin/timeout, so here's a function that works on OS X without home-brew or macports that is similar to /usr/bin/timeout (based on Tino's answer). Parameter validation, help, usage, and support for other signals are an exercise for reader.
# implement /usr/bin/timeout only if it doesn't exist
[ -n "$(type -p timeout 2>&1)" ] || function timeout { (
set -m +b
sleep "$1" &
SPID=${!}
("${@:2}"; RETVAL=$?; kill ${SPID}; exit $RETVAL) &
CPID=${!}
wait %1
SLEEPRETVAL=$?
if [ $SLEEPRETVAL -eq 0 ] && kill ${CPID} >/dev/null 2>&1 ; then
RETVAL=124
# When you need to make sure it dies
#(sleep 1; kill -9 ${CPID} >/dev/null 2>&1)&
wait %2
else
wait %2
RETVAL=$?
fi
return $RETVAL
) }
Online Viewstate Viewer made by Lachlan Keown:
http://lachlankeown.blogspot.com/2008/05/online-viewstate-viewer-decoder.html
Here is how I reckon you should be doing.
Because both functions will be using amazingData, it makes sense to have them in a dedicated function. I usually do that everytime I want to reuse some data, so it is always present as a function arg.
As your example is running some code, I will suppose it is all declared inside a function. I will call it toto(). Then we will have another function which will run both afterSomething() and afterSomethingElse().
function toto() {
return somethingAsync()
.then( tata );
}
You will also notice I added a return statement as it is usually the way to go with Promises - you always return a promise so we can keep chaining if required. Here, somethingAsync() will produce amazingData and it will be available everywhere inside the new function.
Now what this new function will look like typically depends on is processAsync() also asynchronous?
No reason to overcomplicate things if processAsync() is not asynchronous. Some old good sequential code would make it.
function tata( amazingData ) {
var processed = afterSomething( amazingData );
return afterSomethingElse( amazingData, processed );
}
function afterSomething( amazingData ) {
return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}
Note that it does not matter if afterSomethingElse() is doing something async or not. If it does, a promise will be returned and the chain can continue. If it is not, then the result value will be returned. But because the function is called from a then(), the value will be wrapped into a promise anyway (at least in raw Javascript).
If processAsync() is asynchronous, the code will look slightly different. Here we consider afterSomething() and afterSomethingElse() are not going to be reused anywhere else.
function tata( amazingData ) {
return afterSomething()
.then( afterSomethingElse );
function afterSomething( /* no args */ ) {
return processAsync( amazingData );
}
function afterSomethingElse( processedData ) {
/* amazingData can be accessed here */
}
}
Same as before for afterSomethingElse(). It can be asynchronous or not. A promise will be returned, or a value wrapped into a resolved promise.
Your coding style is quite close to what I use to do, that is why I answered even after 2 years. I am not a big fan of having anonymous functions everywhere. I find it hard to read. Even if it is quite common in the community. It is as we replaced the callback-hell by a promise-purgatory.
I also like to keep the name of the functions in the then short. They will only be defined locally anyway. And most of the time they will call another function defined elsewhere - so reusable - to do the job. I even do that for functions with only 1 parameter, so I do not need to get the function in and out when I add/remove a parameter to the function signature.
Here is an example:
function goingThroughTheEatingProcess(plenty, of, args, to, match, real, life) {
return iAmAsync()
.then(chew)
.then(swallow);
function chew(result) {
return carefullyChewThis(plenty, of, args, "water", "piece of tooth", result);
}
function swallow(wine) {
return nowIsTimeToSwallow(match, real, life, wine);
}
}
function iAmAsync() {
return Promise.resolve("mooooore");
}
function carefullyChewThis(plenty, of, args, and, some, more) {
return true;
}
function nowIsTimeToSwallow(match, real, life, bobool) {
}
Do not focus too much on the Promise.resolve(). It is just a quick way to create a resolved promise. What I try to achieve by this is to have all the code I am running in a single location - just underneath the thens. All the others functions with a more descriptive name are reusable.
The drawback with this technique is that it is defining a lot of functions. But it is a necessary pain I am afraid in order to avoid having anonymous functions all over the place. And what is the risk anyway: a stack overflow? (joke!)
Using arrays or objects as defined in other answers would work too. This one in a way is the answer proposed by Kevin Reid.
You can also use bind() or Promise.all(). Note that they will still require you to split your code.
If you want to keep your functions reusable but do not really need to keep what is inside the then very short, you can use bind().
function tata( amazingData ) {
return afterSomething( amazingData )
.then( afterSomethingElse.bind(null, amazingData) );
}
function afterSomething( amazingData ) {
return processAsync( amazingData );
}
function afterSomethingElse( amazingData, processedData ) {
}
To keep it simple, bind() will prepend the list of args (except the first one) to the function when it is called.
In your post you mentionned the use of spread(). I never used the framework you are using, but here is how you should be able to use it.
Some believe Promise.all() is the solution to all problems, so it deserves to be mentioned I guess.
function tata( amazingData ) {
return Promise.all( [ amazingData, afterSomething( amazingData ) ] )
.then( afterSomethingElse );
}
function afterSomething( amazingData ) {
return processAsync( amazingData );
}
function afterSomethingElse( args ) {
var amazingData = args[0];
var processedData = args[1];
}
You can pass data to Promise.all() - note the presence of the array - as long as promises, but make sure none of the promises fail otherwise it will stop processing.
And instead of defining new variables from the args argument, you should be able to use spread() instead of then() for all sort of awesome work.
Editor issue. When you create new files that not using Angular CLI, make sure you go to File > Save All (VS Code) to let the Editor aware of your new changes. Then run "ng serve --open" again. It solved mine. Hope it helps
ALTER TABLE tablename AUTO_INCREMENT = 1
Connect to mysql
mysql -uusername -p -hhostname
show full processlist:
mysql> show full processlist;
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| 9255451 | logreg | dmin001.ops:37651 | logdata | Query | 0 | NULL | show processlist |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
Kill the specific query. Here id=9255451
mysql> kill 9255451;
If you get permission denied, try this SQL:
CALL mysql.rds_kill(9255451)
Use cURL
,
Check if you have it via phpinfo();
And for the code:
function getHtml($url, $post = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if(!empty($post)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$("#button").click(function () {
$("#frame").attr("src", "http://www.example.com/");
});
HTML:
<div id="mydiv">
<iframe id="frame" src="" width="100%" height="300">
</iframe>
</div>
<button id="button">Load</button>
I think it's local to the file you declared offset. Consider every file to be a method itself.
Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);
?
Use a regex literal with the g
modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.
var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);
zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
-x "*/\__MACOSX"
: ignore __MACOSX as you mention.-x "*/\.*"
: ignore any hidden file, such as .DS_Store .Also, you can build Automator Service to make it easily to use in Finder. Check link below to see detail if you need.
Things have changed since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.
Paul Irish put together Bulletproof @font-face syntax combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.
Snipped from his article:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
Working from that base, Font Squirrel put together a variety of useful tools including the @font-face Generator which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has Hundreds of @font-face kits.
Soma Design also put together the FontFriend Bookmarklet, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.
More recently, Google has started to provide the Google Web Fonts, an assortment of fonts available under an Open Source license and served from Google's servers.
License Restrictions
Finally, WebFonts.info has put together a nice wiki'd list of Fonts available for @font-face embedding based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. It's important to read the licenses, because there are some limitations that aren't pushed forward obviously on the font downloads.
simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.
Add .idea
and *.iml
to .gitignore
, you don't need those files to successfully import and compile the project.
You can also use the setProperty method like below
document.getElementById('divName').style.setProperty("top", "100px");
To clean up some mess, trap
can be used. It can provide a list of stuff executed when a specific signal arrives:
trap "echo hello" SIGINT
but can also be used to execute something if the shell exits:
trap "killall background" EXIT
It's a builtin, so help trap
will give you information (works with bash). If you only want to kill background jobs, you can do
trap 'kill $(jobs -p)' EXIT
Watch out to use single '
, to prevent the shell from substituting the $()
immediately.
Drawbacks of using TCP for live video:
FYI, please don't use the word "packages" when describing networks. Networks send "packets".
Just to add to this, because I was getting this error as well. Going through all these answers most seem to apply to working with the UI and storyboard stuff. I know the original poster did seem to be working with the UI but when searching for possible reasons for this error mostly all questions lead back to this question with those others being closed as duplicates or simply having issues with connecting things in a storyboard so I will add my solution.
I was working on coding a web service in Swift 2. I had built all the needed proxy objects and stubs. As I looped through the returned XML I was dynamically instantiating my objects, which all came from NSObject
and using setValue:forKey
on them. Every time setValue:forKey
tried to set a property it blew up with this error.
I had a switch statement for each type I was dealing with (e.g. Bool?
, CShort?
, String?
) and for each XML node I went through and checked what the type was on the object and then converted the value to that type and attempted to set it with setValue:forKey
.
Eventually I started commenting out all these setValue:forKey
lines and found that my default
switch statement case did work for String?
.
I finally figured out that you can't use optional swift types with setValue:forKey
unless they have a direct mapping to an Objective-C type like String?
or NSNumber?
. I ended up changing all CShort?
types to NSNumber?
since that has a direct mapping. For Bool?
in my case it was fine for me to just use Bool
and initialize it to false
. Others may not have that luxury.
Anyway what a headache that was so hopefully this helps someone else who has a similar problem and keeps getting redirected to this question and saying to themselves, "I am not doing anything in UI!!".
So lastly to reiterate one more time Key-Value Coding does not work with optionals. Below I ended up finding somewhere but I forget where so to whoever posted this I apologize and would give credit if I remembered where I found this but it saved my life:
You cannot use KVC on an Optional Int property, because KVC is Cocoa / Objective-C, and Objective-C cannot see an Optional Int - it is not bridged to Objective-C. Objective-C can only see types that are bridged to Objective-C:
class types that are derived from NSObject
class types that are exposed with @objc
Swift structs that are bridged
Given enum
public enum PublishMode { Edit, View }
you can do it like here
void MyMethod(PublishMode? mode)
{
var publishMode = mode ?? PublishMode.Edit;
//or
if (mode?? PublishMode.Edit == someValue)
....
}
To solve the problem do following:
First uninstall numpy
sudo pip uninstall numpy
Install numpy with --no-cache-dir option
sudo pip install --no-cache-dir numpy
And to specify any specific version e.g. 1.14.2
sudo pip install --no-cache-dir numpy==1.14.2
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
For python 3.7 on ubuntu I had to use sudo apt-get install python3.7-tk
to make it work
Restarting the machine worked for me but not every time.
If you are really stuck on this then follow below steps
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.
git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch
This creates a local branch named ournameforbranch
which is exactly the same as what theirbranch
was for them. For the question example, the last argument would be foo:foo
.
Note :ournameforbranch
part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD
is available. You can git log FETCH_HEAD
to see their commits then do things like cherry-picked
to cherry pick their commits.
Oftentimes, you want to fix something of theirs and push it right back. That's possible too:
git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD
# fix fix fix
git push [email protected]:theirusername/reponame.git HEAD:theirbranch
If working in detached state worries you, by all means create a branch using :ournameforbranch
and replace FETCH_HEAD
and HEAD
above with ournameforbranch
.
I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):
SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)
I had this issue with this with Azure DevOps automated builds in an on-prem TFS build agent. Removing the workspace using TFS Sidekicks did not work. And tf.exe could not even find the workspace to delete it.
This solution should work for TFS 2017, TFS 2018, Azure DevOps, and possibly other versions:
That worked in my circumstance.
I like this little plugin. It needs a bit more cross browser friendliness though.
What complex solutions!
Malloc and sprints and casts oh my. (OZ quote)
and not a single rem anywhere. Gosh
How about something like this?
main()
{
// the value
int value = 16;
// create a string array with a '\0' ending ie. 0,0,0
char hex[]= {0,0,'\0'};
char *hex_p=hex;
//a working variable
int TEMP_int=0;
// get me how many 16s are in this code
TEMP_int=value/16;
// load the first character up with
// 48+0 gives you ascii 0, 55+10 gives you ascii A
if (TEMP_int<10) {*hex_p=48+TEMP_int;}
else {*hex_p=55+TEMP_int;}
// move that pointer to the next (less significant byte)<BR>
hex_p++;
// get me the remainder after I have divied by 16
TEMP_int=value%16;
// 48+0 gives you ascii 0, 55+10 gives you ascii A
if (TEMP_int<10) {*hex_p=48+TEMP_int;}
else {*hex_p=55+TEMP_int;}
// print the result
printf("%i , 0x%s",value,hex);
}
I recently wrote a MySQL function to replace strings using regular expressions. You could find my post at the following location:
http://techras.wordpress.com/2011/06/02/regex-replace-for-mysql/
Here is the function code:
DELIMITER $$
CREATE FUNCTION `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
DECLARE temp VARCHAR(1000);
DECLARE ch VARCHAR(1);
DECLARE i INT;
SET i = 1;
SET temp = '';
IF original REGEXP pattern THEN
loop_label: LOOP
IF i>CHAR_LENGTH(original) THEN
LEAVE loop_label;
END IF;
SET ch = SUBSTRING(original,i,1);
IF NOT ch REGEXP pattern THEN
SET temp = CONCAT(temp,ch);
ELSE
SET temp = CONCAT(temp,replacement);
END IF;
SET i=i+1;
END LOOP;
ELSE
SET temp = original;
END IF;
RETURN temp;
END$$
DELIMITER ;
Example execution:
mysql> select regex_replace('[^a-zA-Z0-9\-]','','2my test3_text-to. check \\ my- sql (regular) ,expressions ._,');
Both Joda-Time and java.time (new in Java 8) offer a LocalTime
class to represent a time-of-day without any date or time zone.
Example code, identical code for both java.time and Joda-Time.
LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Yes, you very well can learn C using Visual Studio.
Visual Studio comes with its own C compiler, which is actually the C++ compiler. Just use the .c
file extension to save your source code.
You don't have to be using the IDE to compile C. You can write the source in Notepad, and compile it in command line using Developer Command Prompt which comes with Visual Studio.
Open the Developer Command Prompt, enter the directory you are working in, use the cl
command to compile your C code.
For example, cl helloworld.c
compiles a file named helloworld.c
.
Refer this for more information: Walkthrough: Compiling a C Program on the Command Line
Hope this helps
First, if you have already run the migrations generated by the scaffold
command, you have to perform a rollback first.
rake db:rollback
You can create scaffolding using:
rails generate scaffold MyFoo
(or similar), and you can destroy/undo it using
rails destroy scaffold MyFoo
That will delete all the files created by generate
, but not any additional changes you may have made manually.
public class CloseAppActivity extends AppCompatActivity
{
public static final void closeApp(Activity activity)
{
Intent intent = new Intent(activity, CloseAppActivity.class);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
finish();
}
}
and in manifest:
<activity
android:name=".presenter.activity.CloseAppActivity"
android:noHistory="true"
android:clearTaskOnLaunch="true"/>
Then you can call CloseAppActivity.closeApp(fromActivity)
and application will be closed.
How about
<button onclick="window.open('http://www.google.com','name','width=200,height=200');">Open</button>
I know this isn't a direct answer to your question but it does offer one solution to your problem. Python 2.7.9 includes PIP and SetupTools, if you update to this version you will have one solution to your problem.
See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html
"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."
(...)
It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.5.4.4, “Problems with Column Aliases”.
How can I set a transparent background on JPEG image?
If you intend to keep the image as a JPEG then you can't. As others have suggested, convert it to PNG and add an alpha channel.
Burgos has the right answer. Just to clarify, the Character Set should be changed to "Not Set".
You have found the root cause. Alternately do like this:
ser.write(bytes(b'your_commands'))
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
There are 3 approaches to this solution:
Let the sum be T and n be the size of array
Approach 1:
The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2).
Approach 2:
A better way would be to sort the array. This takes O(n log n)
Then for each x in array A,
use binary search to look for T-x. This will take O(nlogn).
So, overall search is O(n log n)
Approach 3 :
The best way
would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion.
Then for every x,
we can just look up its complement, T-x, which is O(1).
Overall the run time of this approach is O(n).
You can refer more here.Thanks.
do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.
You can also wait on a Task that returns from your void async
Look here for details.
private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
public Form1()
{
InitializeComponent();
InitialiseCPUCounter();
InitializeRAMCounter();
updateTimer.Start();
}
private void updateTimer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = "CPU Usage: " +
Convert.ToInt32(cpuCounter.NextValue()).ToString() +
"%";
this.textBox2.Text = Convert.ToInt32(ramCounter.NextValue()).ToString()+"Mb";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void InitialiseCPUCounter()
{
cpuCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
private void InitializeRAMCounter()
{
ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
}
If you get value as 0 it need to call NextValue()
twice. Then it gives the actual value of CPU usage. See more details here.
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
Just to add, I am using self object, this worked for me:
[f.name for f in self.model._meta.get_fields()]
I would put this in a comment to ghostdog74, except my rep is too low, so here goes.
more +2 file2.txt > temp
This code will actually ignore rows 1 and 2 of the file. OP wants to keep all rows from the first file (to maintain the header row), and then exclude the first row (presumably the same header row) on the second file, so to exclude only the header row OP should use more +1
.
type temp file1.txt > out.txt
It is unclear what order results from this code. Is temp
appended to file1.txt
(as desired), or is file1.txt
appended to temp
(undesired as the header row would be buried in the middle of the resulting file).
In addition, these operations take a REALLY LONG TIME with large files (e.g. 300MB)
I used file_get_contents
using stream_create_context
and it works fine:
$postdataStr = http_build_query($postdataArr);
$context_options = array (
'http' => array ( <blink> // this will allways be http!!!</blink>
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($postdataArr) . "\r\n"
. "Cookie: " . $cookies."\r\n"
'content' => $postdataStr
)
);
$context = stream_context_create($context_options);
$HTTPSReq = file_get_contents('https://www.example.com/', false, $context);
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
What worked for me on android 4.4 was to do the following: Settings -> Wireless & Networks -> Mobile networks -> Make sure both Data enabled and Data roaming is enabled.
Some times you need to add other <proxy></proxy>
tags, and specify the https in the protocol tags: <protocol>https</protocol>
Vue just warns you: you change the prop in the component, but when parent component re-renders, "list" will be overwritten and you lose all your changes. So it is dangerous to do so.
Use computed property instead like this:
Vue.component('task', {
template: '#task-template',
props: ['list'],
computed: {
listJson: function(){
return JSON.parse(this.list);
}
}
});
You can use JavaScript Timing Events to call function after certain interval of time:
This shows the alert box after 3 seconds:
setInterval(function(){alert("Hello")},3000);
You can use two method of time event in javascript.i.e.
setInterval()
: executes a function, over and over again, at
specified time intervalssetTimeout()
: executes a function, once, after waiting a
specified number of millisecondsI would rather use Last()
from LINQ to do it.
rows = rows.Remove(rows.Last());
or
rows = rows.Remove(rows.LastOrDefault());
Just add overflow:hidden
to the table with border-radius
.
.tablewithradius {
overflow:hidden ;
border-radius: 15px;
}
If your computer can't find the IP address associated with SUBDOMAIN1.example.COM
, it will not find the site.
You need to either change your hosts
file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
I know this answer is not directly related to this questions' issue but in some cases the "Uncaught ReferenceError: google is not defined" issue will occur if your js file is being called prior to the google maps api you're using...so DON'T DO this:
<script type ="text/javascript" src ="SomeJScriptfile.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
txtUsuario.Attributes.Add("placeholder", "Texto");
Use Socket.Connected
Property.
--UPDATE--
As Paul Turner answered Socket.Connected cannot be used in this situation. You need to poll connection every time to see if connection is still active. See 2
SELECT * FROM table
ORDER BY NEWID()
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
I am using Ansible 1.9.4 and this is what worked for me -
- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
When trying to compile and use class Elsewhere
(from Earwicker's answer) I get:
error LNK2001: unresolved external symbol "private: static class StaticStuff Elsewhere::staticStuff" (?staticStuff@Elsewhere@@0VStaticStuff@@A)
It seems is not possible to initialize static attributes of non-integer types without putting some code outside the class definition (CPP).
To make that compile you can use "a static method with a static local variable inside" instead. Something like this:
class Elsewhere
{
public:
static StaticStuff& GetStaticStuff()
{
static StaticStuff staticStuff; // constructor runs once, single instance
return staticStuff;
}
};
And you may also pass arguments to the constructor or initialize it with specific values, it is very flexible, powerfull and easy to implement... the only thing is you have a static method containing a static variable, not a static attribute... syntaxis changes a bit, but still useful. Hope this is useful for someone,
Hugo González Castro.
The value of hjust
and vjust
are only defined between 0 and 1:
Source: ggplot2, Hadley Wickham, page 196
(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)
hjust
controls horizontal justification and vjust
controls vertical justification.
An example should make this clear:
td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)
ggplot(td, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))
To understand what happens when you change the hjust
in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)
DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() +
ylab("Very long label for y") +
theme(axis.title.y=element_text(angle=0))
p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
To explore what happens with vjust
aligment of axis labels:
DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) +
xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) +
xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) +
xlab("X-axis labels aligned with vjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
I also encountered the same problem and passed the following way to solve this problem.
step 1:
$ npm install --save-dev http-proxy-middleware
step 2:
add a proxy when i fetch web api, if you use lite-server you can add a file bs-config.js .
//file: bs-config.js
var proxyMiddleware = require('http-proxy-middleware');
module.exports = {
server: {
middleware: {
1: proxyMiddleware('/example-api', {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: {
'^/news-at-api': '/api'
}
})
}
}
};
hope this helps.
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
Please see below:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();
//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);
// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();
// Switch driver control to focused tab window
driver.switchTo().window(oldTab);
driver.findElement(By.id("textfield")).sendKeys("bangalore");
Hope this is helpful!
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.testpoc.controller"/>
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
i would recommend you to you datagridview, for heavy stuff.. it's include a lot of auto feature listviwe does not
onkeyup, onpaste, onchange, oninput
seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'
" in your textfield to prevent browser from autofilling the textbox,
Eg,
<input id="inputDatabaseName" autocomplete='off' onchange="check();"
onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />
<script>
function check(){
alert("Input box changed");
// Things to do when the textbox changes
}
</script>
Go to Python Interpreter. type help ('module_name') , then press Enter. e.g. help('os') . Here, I've pasted one part of the output below:
class statvfs_result(__builtin__.object)
| statvfs_result: Result from statvfs or fstatvfs.
|
| This object may be accessed either as a tuple of
| (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
| or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
|
| See os.statvfs for more information.
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
The current answer is incomplete. Installing libv4l-dev
creates a /usr/include/linux/videodev2.h
but doesn't solve the stated problem of not being able to find linux/videodev.h
. The library does ship header files for compatibility, but fails to put them where applications will look for them.
sudo apt-get install libv4l-dev
cd /usr/include/linux
sudo ln -s ../libv4l1-videodev.h videodev.h
This provides a linux/videodev.h
, and of the right version (1).
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
There are several issues:
elif option == 2:
and the subsequent elif
-else
should be aligned with the second if option == 1
, not with the for
.
The for x in range(x, 1, 1):
is missing a body.
Since "option 1 (count)" requires a second input, you need to call input()
for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option
.
The comparison in the first line of your code is probably meant to be an assignment.
You'll discover more issues once you're able to run your code (you'll need a couple more input()
calls, one of the range()
calls will need attention etc).
Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:
for x in range(1, x, 1):
print x
It may work, but it is very confusing to read. Give the loop variable a different name:
for i in range(1, x, 1):
print i
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
Try using RUN /bin/sh
instead of bash.
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
It also works if we use as follows:
@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
I know this is old question, but I wanted to do the same. Update a file in zip archive. And none of the above answers really helped me.
Here is what I did. Created temp directory abc
. Copied file.zip
to abc
and extracted the file in that directory. I edited the file I wanted to edit.
Then while being in abc
, ran the following command
user@host ~/temp/abc $ zip -u file.zip
updating: content/js/ (stored 0%)
updating: content/js/moduleConfig.js (deflated 69%)
-u
switch will look for changed/new files and will add to the zip archive.
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
To rehash a couple of old jokes:
for (;;) {}
" — it makes the statement cry.#define EVER ;;
".If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.
import json
match = (json.dumps(dict1) == json.dumps(dict2))
caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable
string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");
The first parameter is the path. The second is the search pattern you want to use.
If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:
object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));
or following for synchronous code:
object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;
Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:
YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
And if you came here looking for slicing two ranges of columns and combining them together (like me) you can do something like
op = df[list(df.columns[0:899]) + list(df.columns[3593:])]
print op
This will create a new dataframe with first 900 columns and (all) columns > 3593 (assuming you have some 4000 columns in your data set).
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
$m = 250;
$extraIntH = intval($m/60);
$extraIntHs = ($m/60); // float value
$whole = floor($extraIntHs); // return int value 1
$fraction = $extraIntHs - $whole; // Total - int = . decimal value
$extraIntHss = ($fraction*60);
$TotalHoursAndMinutesString = $extraIntH."h ".$extraIntHss."m";
I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)]
to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.
Install-Package Mono.Cecil
And the code like:
static readonly string[] s_toInject = {
// alternatively "MyAssembly, PublicKey=0024000004800000... etc."
"MyAssembly"
};
static void Main(string[] args) {
const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";
var parameters = new ReaderParameters();
var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
foreach (var toInject in s_toInject) {
var ca = new CustomAttribute(
asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
typeof(string)})));
ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
asm.Assembly.CustomAttributes.Add(ca);
}
asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
// note if the assembly is strongly-signed you need to resign it like
// asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
// StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
// });
}
can check it in packages.config file.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages>
You need to use event.stopPropagation()
$('#childDiv').click(function(event){
event.stopPropagation();
alert(event.target.id);
});?
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Based on answers I found from the internet, I come to my code as following:
public static string GetTemporaryFileName()
{
string tempFilePath = Path.Combine(Path.GetTempPath(), "SnapshotTemp");
Directory.Delete(tempFilePath, true);
Directory.CreateDirectory(tempFilePath);
return Path.Combine(tempFilePath, DateTime.Now.ToString("MMddHHmm") + "-" + Guid.NewGuid().ToString() + ".png");
}
And as C# Cookbook by Jay Hilyard, Stephen Teilhet pointed in Using a Temporary File in Your Application:
you should use a temporary file whenever you need to store information temporarily for later retrieval.
The one thing you must remember is to delete this temporary file before the application that created it is terminated.
If it is not deleted, it will remain in the user’s temporary directory until the user manually deletes it.
if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
{
// code when element is disabled
}
So assuming that object is in your scope:
<div ng-controller="MyCtrl">
<select ng-model="prop.value" ng-options="v for v in prop.values">
</select>
</div>
function MyCtrl($scope) {
$scope.prop = {
"type": "select",
"name": "Service",
"value": "Service 3",
"values": [ "Service 1", "Service 2", "Service 3", "Service 4"]
};
}
Working Plunkr: http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g
I want them to cover 75% of the button area.
Use android:padding="20dp"
(adjust the padding as needed) to control how much the image takes up on the button.
but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?
Use a android:scaleType="fitCenter"
to have Android scale the images, and android:adjustViewBounds="true"
to have them adjust their bounds due to scaling.
All of these attributes can be set in code on each ImageButton
at runtime. However, it is much easier to set and preview in xml in my opinion.
Also, do not use sp
for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp
dimensions will be larger than your intended if the user has a "large" text setting. Use dp
instead, as it is not scaled by the user's text size preference.
Here's a snippet of what each button should look like:
<ImageButton
android:id="@+id/button_topleft"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="5dp"
android:layout_marginTop="0dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:padding="20dp"
android:scaleType="fitCenter" />
Reset - On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
Revert - Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.
You can have a look on this link- Reset, Checkout and Revert
In /System/Library/Frameworks/JavaVM.framework/Versions
you'll see all the installed JDKs. There is a symbolic link named CurrentJDK
pointing the active JDK.
This is what I recently did for my Data Visualization Application which has a 2008 SQL Database. In this example I am recieving a list returned from a stored procedure:
public List<CumulativeInstrumentsDataRow> GetCumulativeInstrumentLogs(RunLogFilter filter)
{
EFDbContext db = new EFDbContext();
if (filter.SystemFullName == string.Empty)
{
filter.SystemFullName = null;
}
if (filter.Reconciled == null)
{
filter.Reconciled = 1;
}
string sql = GetRunLogFilterSQLString("[dbo].[rm_sp_GetCumulativeInstrumentLogs]", filter);
return db.Database.SqlQuery<CumulativeInstrumentsDataRow>(sql).ToList();
}
And then this extension method for some formatting in my case:
public string GetRunLogFilterSQLString(string procedureName, RunLogFilter filter)
{
return string.Format("EXEC {0} {1},{2}, {3}, {4}", procedureName, filter.SystemFullName == null ? "null" : "\'" + filter.SystemFullName + "\'", filter.MinimumDate == null ? "null" : "\'" + filter.MinimumDate.Value + "\'", filter.MaximumDate == null ? "null" : "\'" + filter.MaximumDate.Value + "\'", +filter.Reconciled == null ? "null" : "\'" + filter.Reconciled + "\'");
}
None of these options show up for me. The way to paste data from Excel is as follows:
Add an extra column to the left of your spreadsheet data (if you don't have row numbers showing in PL/SQL Developer you may not have to have an extra empty column to the left).
Copy the rows of data from your spreadsheet including the empty column.
In PL/SQL Developer, open your table in edit mode. You can right-click the table name in the object browser and select Edit Data or write your own select statement that includes the rowid and click the lock icon. Be sure your columns are ordered the same as in your spreadsheet.
Here's the part that took me forever to figure out: click on the left side of the first empty row to highlight it. It will not work if you don't have the first empty row highlighted.
Paste as usual using Ctrl+V or right-click Paste.
I couldn't find this info anywhere when I needed it, so I wanted to be sure to post it.
Simply:
/^([^0-9]*)$/
That pattern matches any number of characters that is not 0
through 9
.
I recommend checking out http://regexpal.com/. It will let you easily test out a regex.
The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.
If you need to convert to Base64 you could do so using Buffer:
console.log(Buffer.from('Hello World!').toString('base64'));
Reverse (assuming the content you're decoding is a utf8 string):
console.log(Buffer.from(b64Encoded, 'base64').toString());
Note: prior to Node v4, use new Buffer
rather than Buffer.from
.
The cin.clear()
clears the error flag on cin
(so that future I/O operations will work correctly), and then cin.ignore(10000, '\n')
skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
From my answer here, thought this might be useful:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
$ mysql --version
You'll see some output like this with MySQL:
$ mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
$ sudo systemctl stop mysql
And for MariaDB with:
$ sudo systemctl stop mariadb
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
$ mysql -u root
You'll immediately see a database shell prompt instead.
MySQL Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MariaDB Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
mysql> FLUSH PRIVILEGES;
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
Make sure to replace new_password
with your new password of choice.
Note: If the ALTER USER
command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET
to reset the root password instead.
[IMPORTANT] This is the specific line that fixed my particular issue:
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
Query OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MySQL, use: $ sudo systemctl start mysql
For MariaDB, use:
$ sudo systemctl start mariadb
Now you can confirm that the new password has been applied correctly by running:
$ mysql -u root -p
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
with O(n log(n))
int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);
for (int i = 0; i < arr1.length; i++) {
arr2[i]++;
if (i+1 < arr1.length)
{
if (arr1[i] == arr1[i + 1]) {
arr2[i]++;
i++;
}
}
}
for (int i = 0; i < arr1.length; i++) {
if(arr2[i]>0)
System.out.println(arr1[i] + ":" + arr2[i]);
}
let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.date(from: String(dateString.dropLast(5)))!
formatter.dateFormat = "hh.mma"
print(formatter.string(from: date))
if You notice I have set .dateFormat = "hh.mma"
by this you will get time only.
Result:01.30PM
Here's a slightly less complicated answer:
NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex
I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program: