I had been facing similar problem in downloading big files this works fine for me now:
safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On
Hope this helps.
You can try
grep -f file1 file2
or
grep -v -F -x -f file1 file2
I was able to do this for the JDK14 binding by first requesting the SLF4J Logger instance and then setting the level on the binding -- you may try this for the Log4J binding.
private void setLevel(Class loggerClass, java.util.logging.Level level) {
org.slf4j.LoggerFactory.getLogger(loggerClass);
java.util.logging.Logger.getLogger(loggerClass.getName()).setLevel(level);
}
First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True
to the .drop
parameters as well.
df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)
I accept @Rocket hazmat's answer as it lead me to the solution. It was indeed on the GAE server I needed to set the header. I had to set these
"Access-Control-Allow-Origin" -> "*"
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept"
setting only "Access-Control-Allow-Origin"
gave error
Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Also, if auth token needs to be sent, add this too
"Access-Control-Allow-Credentials" -> "true"
Also, at client, set withCredentials
this causes 2 requests to sent to the server, one with OPTIONS
. Auth cookie is not send with it, hence need to treat outside auth.
In WSDL definition, bindings contain operations, here comes style for each operation.
Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.
In WSDL types element looks as follows:
<types>
<xsd:schema>
<xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
</xsd:schema>
</types>
The schema is importing from external reference.
RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.
<types/>
<message name="getHelloWorldAsString">
<part name="arg0" type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return" type="xsd:string"/>
</message>
RPC : No types in WSDL
Document: Types section would be available in WSDL
/* iPad */
@media screen and (min-device-width: 768px) {
/* ipad-portrait */
@media screen and (max-width: 896px) {
.logo{
display: none !important;
}
}
/* ipad-landscape */
@media screen and (min-width: 897px) {
}
}
/* iPhone */
@media screen and (max-device-width: 480px) {
/* iphone-portrait */
@media screen and (max-width: 400px) {
}
/* iphone-landscape */
@media screen and (min-width: 401px) {
}
}
@Manish Jain, I suggest to implement the method with boolean return:
public class UserManager
{
// Additional code here...
public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
{
// Additional code here...
// Here the real authentication against a DB or Web Services or whatever
if (user.Email != null)
return false;
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
// This is for give the authentication cookie to the user when authentication condition was met
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return true;
}
}
When applying patches using TortoiseSVN, I typically save the path in the root of the checked out repository. You should then be able to right click on the patch, go to the TortoiseSVN menu, and click ApplyPatch. ApplyPatch should automatically figure out which level in the directory hierarchy the patch was created.
I have, however, had issues in the past with applying patches that contain new files, or which involve renames to files. Whatever algorithm Tortoise uses for this doesn't seem to handle those scenarios very well. Unicode can give you similar issues.
we have to find label tag for attribute value based on that.we have replace label text.
Script:
<script type="text/javascript">
$(document).ready(function()
{
$("label[for*='test']").html("others");
});
</script>
Html
<label for="test_992918d5-a2f4-4962-b644-bd7294cbf2e6_FillInButton">others</label>
I came up with a simple solution.
I have a model.cs class with:
private int _isSuccess;
public int IsSuccess { get { return _isSuccess; } set { _isSuccess = value; } }
I have Window1.xaml.cs file with DataContext set to model.cs. The xaml contains the radiobuttons:
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=1}" Content="one" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=2}" Content="two" />
<RadioButton IsChecked="{Binding Path=IsSuccess, Converter={StaticResource radioBoolToIntConverter}, ConverterParameter=3}" Content="three" />
Here is my converter:
public class RadioBoolToIntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int integer = (int)value;
if (integer==int.Parse(parameter.ToString()))
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter;
}
}
And of course, in Window1's resources:
<Window.Resources>
<local:RadioBoolToIntConverter x:Key="radioBoolToIntConverter" />
</Window.Resources>
This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:
private static void Main(string[] args)
{
var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
var whereClause =
new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");
string[] values = {"1", "2", "3", "4", "5", "6"};
query["WhereClauses"] = NestEq(whereClause, andClause, values);
Console.WriteLine(query);
}
And here's the code:
private static string MakeExpression(PropertyString nestClause, string value)
{
var expr = nestClause.New();
expr["NestClauseValue"] = value;
return expr.ToString();
}
/// <summary>
/// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
/// </summary>
/// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
/// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
/// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
{
if (pos > nestClauseValues.Length)
{
return "";
}
if (nestClauseValues.Length == 1)
{
return MakeExpression(whereClause, nestClauseValues[0]);
}
var expr = nestingExpression.New();
if (pos == nestClauseValues.Length - 2)
{
expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
return expr.ToString();
}
else
{
expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
return expr.ToString();
}
}
public class PropertyString
{
private string _propStr;
public PropertyString New()
{
return new PropertyString(_propStr );
}
public PropertyString(string propStr)
{
_propStr = propStr;
_properties = new Dictionary<string, string>();
}
private Dictionary<string, string> _properties;
public string this[string key]
{
get
{
return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
}
set
{
if (_properties.ContainsKey(key))
{
_properties[key] = value;
}
else
{
_properties.Add(key, value);
}
}
}
/// <summary>
/// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you
/// </summary>
/// <param name="originalStr"></param>
/// <param name="keyValuePairPropertiesDictionary"></param>
/// <returns></returns>
public override string ToString()
{
string modifiedStr = _propStr;
foreach (var keyvaluePair in _properties)
{
modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
}
return modifiedStr;
}
}
You can use boost::lexical_cast:
#include <iostream>
#include <boost/lexical_cast.hpp>
int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;
try {
i = boost::lexical_cast<int>( s1 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
try {
i = boost::lexical_cast<int>( s2 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
return 0;
}
This is for the total beginner... like me:
HTML:
<ul>
<li>
<a href="#"> Home </a>
</li>
<li>
<a href="#Info"> Info </a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Home information</p>"
})
.when("/Info", {
template: "<p>Basic information</p>"
//templateUrl: "/content/views/Info.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeStart', function () {
console.log("routeChangeStart");
//Place code here:....
});
});
Hope this helps a total beginner like me. Here is the full working sample:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>_x000D_
<a href="#"> Home </a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#Info"> Info </a>_x000D_
</li>_x000D_
</ul>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MainCtrl">_x000D_
<div ng-view>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<script>_x000D_
//Create App_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
_x000D_
//Configure routes_x000D_
app.config(function ($routeProvider) {_x000D_
$routeProvider_x000D_
.otherwise({ template: "<p>Coming soon</p>" })_x000D_
.when("/", {_x000D_
template: "<p>Home information</p>"_x000D_
})_x000D_
.when("/Info", {_x000D_
template: "<p>Basic information</p>"_x000D_
//templateUrl: "/content/views/Info.html"_x000D_
});_x000D_
});_x000D_
_x000D_
//Controller_x000D_
app.controller('MainCtrl', function ($scope, $rootScope, $location) {_x000D_
$scope.location = $location.path();_x000D_
$rootScope.$on('$routeChangeStart', function () {_x000D_
console.log("routeChangeStart");_x000D_
//Place code here:...._x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:
Step 1: Close Android Studio
Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)
Step 3: Open Android Studio as Administrator
Step 4: If you are currently in an opened project, close current project by select File > Close Project.
Step 5: Now you seeing this Quick Start GUI:
Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)
If it has not worked till now, you could restart your computer. Do step 1 again.
This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
You should see Sublime Column Selection:
Using the Mouse
Different mouse buttons are used on each platform:
OS X
- Left Mouse Button + ?
OR: Middle Mouse Button
Add to selection: ?
- Subtract from selection: ?+?
Windows
- Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
- Subtract from selection: Alt
Linux
Right Mouse Button + Shift
Add to selection: Ctrl
- Subtract from selection: Alt
Using the Keyboard
OS X
- Ctrl + Shift + ?
- Ctrl + Shift + ?
Windows
- Ctrl + Alt + ?
- Ctrl + Alt + ?
Linux
- Ctrl + Alt + ?
- Ctrl + Alt + ?
You can debug Cordova Android Applications which are installed on your phone remotely from your computer via the USB cable (you can also remotely click on the web application as if you were viewing the web application from your compueter) with "Chrome Remote Debugging". You can also debug web application viewed in the Stock Android browser or Chrome on Android this way.
Enable developer mode on your Android device (go to settings -> about phone -> tap 7x on the build number).
Connect your computer with your phone via USB cable.
Lunch Chrome on your computer and navigate to chrome://inspect and click the "Inspect" button next to the remote device which you want to debug (under the "Devices" tab). OR right click inside Chrome on your computer -> Inspect -> Costumize and control DevTools (3 vertical dots - top right corner of the developer tools) -> More tools -> Remote Devices -> under Devices on the left side, click on your device to which you are connected via USB -> click on the Inspect button for the application you want.
Then click on "Console" and you can debug JavaScript the same way, as you would on a normal web application with Chrome developer tools.
I agree that Amazon appears to be intentionally obfuscating even how to find the API documentation, as well as use it. I'm just speculating though.
Renaming the services from "ECS" to "Product Advertising API" was probably also not the best move, it essentially invalidated all that Google mojo they had built up over time.
It took me quite a while to 'discover' this updated link for the Product Advertising API. I don't remember being able to easily discover it through the typical 'Developer' link on the Amazon webpage. This documentation appears to valid and what I've worked from recently.
The change to authentication procedures also seems to add further complexity, but I'm sure they have a reason for it.
I use SOAP via C# to communicate with Amazon Product API.
With the REST API you have to encrypt the whole URL in a fairly specific way. The params have to be sorted, etc. There is just more to do. With the SOAP API, you just encrypt the operation+timestamp, and thats it.
Adam O'Neil's post here, How to get album, dvd, and blueray cover art from Amazon, walks through the SOAP with C# method. Its not the original sample I pulled down, and contrary to his comment, it was not an official Amazon sample I stumbled on, though the code looks identical. However, Adam does a good job at presenting all the necessary steps. I wish I could credit the original author.
If you can't rework your app to do what @blesh suggests (pull JSON data down with $http or $resource and populate $scope), you can use ng-init instead:
<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">
See also AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?
using ByteArrayOutputStream and System.setXXX is simple:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
sample test cases:
@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}
@Test
public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}
I used this code to test the command line option (asserting that -version outputs the version string, etc etc)
Edit:
Prior versions of this answer called System.setOut(null)
after the tests; This is the cause of NullPointerExceptions commenters refer to.
If you are working on Root Directory then you can use this approach
res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');
but if you are using Routes which is inside a folder lets say /Routes/someRoute.js
then you will need to do something like this
const path = require("path");
...
route.get("/some_route", (req, res) => {
res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
From a real device:
Mozilla/5.0 (iPad; U; CPU OS OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10
You can do like:
a="""xyz"""
g="abcd " & a
Or:
a=chr(34) & "xyz" & chr(34)
g="abcd " & a
In my case (Windows 10) the reason was that I dared to unzip the android sdk into non default folder. When I moved it to the default one c:/Users/[username]/AppData/Local/Android/Sdk and changed the paths in Android Studio and System Variables, it started to work.
This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at
-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.
Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.
Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.
SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.
$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on
create table if not exists example (
id integer primary key autoincrement
,data text not null unique
,created_at integer(4) not null default (strftime('%s','now'))
);
insert into example(data) values
('foo')
,('bar')
;
select
id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;
id|data|epoch |utc |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
Localtime is correct as I'm located at UTC+2 DST at the moment of the query.
More information than you would want to know:
http://wiki.secondlife.com/wiki/Message_Queue_Evaluation_Notes
Just elaborating what Paul added in comment. The page mentioned above is dead after 2010, so read with a pinch of salt. Lot of stuff has been been changed in 3 years.
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
My activity calls finish() (which doesn't make it finish immediately, but will do eventually) and calls Google Street Viewer. When I debug it on Eclipse, my connection to the app breaks when Street Viewer is called, which I understand as the (whole) application being closed, supposedly to free up memory (as a single activity being finished shouldn't cause this behavior). Nevertheless, I'm able to save state in a Bundle via onSaveInstanceState() and restore it in the onCreate() method of the next activity in the stack. Either by using a static singleton or subclassing Application I face the application closing and losing state (unless I save it in a Bundle). So from my experience they are the same with regards to state preservation. I noticed that the connection is lost in Android 4.1.2 and 4.2.2 but not on 4.0.7 or 3.2.4, which in my understanding suggests that the memory recovery mechanism has changed at some point.
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.
Windows does not have (need?) this.
Run the command with the sudo removed from the start.
Recursively add subfolders,
for i in `find . -name "*.java" -type f`; do
echo "$i"
done
You need to make sure images come first and put in a comma after the background image call. then it actually does work:
background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "@doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
Try h.264 in an mp4 container. I've had much success with it on my Droid X. I've been using zencoder.com for format conversions.
As far as I'm aware you have to still write the application using a form, but have no controls on the form and never set it visible. Use the NotifyIcon (an MSDN sample of which can be found here) to write your application.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
<script>
function initMap() {
//echo hiii;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(8.5241, 76.9366),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('package');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
// var name = markerElem.getAttribute('name');
// var address = markerElem.getAttribute('address');
// var type = markerElem.getAttribute('type');
// var latitude = results[0].geometry.location.lat();
// var longitude = results[0].geometry.location.lng();
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('latitude')),
parseFloat(markerElem.getAttribute('longitude'))
);
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var package = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
package.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, package);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
In your example, performance probalby isn't too different but there are other issues to consider: namely memory fragmentation. Even concatenate operation is creating a new string, even if its temporary (it takes time to GC it and it's more work). String.format() is just more readable and it involves less fragmentation.
Also, if you're using a particular format a lot, don't forget you can use the Formatter() class directly (all String.format() does is instantiate a one use Formatter instance).
Also, something else you should be aware of: be careful of using substring(). For example:
String getSmallString() {
String largeString = // load from file; say 2M in size
return largeString.substring(100, 300);
}
That large string is still in memory because that's just how Java substrings work. A better version is:
return new String(largeString.substring(100, 300));
or
return String.format("%s", largeString.substring(100, 300));
The second form is probably more useful if you're doing other stuff at the same time.
Yes, there is better. Check the stat
or the fstat
function
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
My take on this, as a good exercise - vparse, which has a tiny source, with a simple function:
function parseVersion(v) {
var m = v.match(/\d*\.|\d+/g) || [];
v = {
major: +m[0] || 0,
minor: +m[1] || 0,
patch: +m[2] || 0,
build: +m[3] || 0
};
v.isEmpty = !v.major && !v.minor && !v.patch && !v.build;
v.parsed = [v.major, v.minor, v.patch, v.build];
v.text = v.parsed.join('.');
return v;
}
Another alternative is to use sdkman. An advantage of sdkman over brew is that many versions of gradle are supported. (brew only supports the latest version and 2.14.) To install sdkman execute:
curl -s "https://get.sdkman.io" | bash
Then follow the instructions. Go here for more installation information. Once sdkman is installed use the command:
sdk install gradle
Or to install a specific version:
sdk install gradle 2.2
Or use to use a specific installed version:
sdk use gradle 2.2
To see which versions are installed and available:
sdk list gradle
For more information go here.
I'd say you're only limited by the total amount of RAM available. Obviously the larger the array the longer operations on it will take.
I hope i am understanding your question correctly, as the above comment says you need to provide more information.
In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.
<div *ngFor="let student of students">
{{student.id}}
{{student.name}}
<img [src]="student.image">
</div>
The correct way to get the integer value of an Enum such as DayOfWeek as a string is:
DayOfWeek.ToString("d")
Lists both local and remote branches:
$ git branch -ra
Output:
feature/feature1
feature/feature2
hotfix/hotfix1
* master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/master
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
Latest version of Express already has body-parser built-in. So you can use:
const express = require('express);
...
app.use(express.urlencoded({ extended: false }))
.use(express.json());
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
In Net Core 3.0:
I was not able to find a way to Reset Migrations.
I also ran into problems with broken migrations, and the answers provided here didn't work for me. I have a .Net Core 3.0 web API, and somewhere in the last month I edited the database directly. Yes, I did a bad, bad thing.
Strategies suggested here resulted in a number of errors in Package Manager Console:
Granted, I may have missed a step or missed clearing out the correct files, but I found that there are ways to clean this up without as much brute force:
Now when the web API is started with an empty database, it correctly creates all the tables and properties to match the entity models.
HTH!
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context.
Nothing from this examples , works for me
for (var i = 0; i < res.results.length; i++) {
$('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}
$('.dd-item').click(function () {
console.log($(this).attr('id'));
});
This is a more general answer meant to be a quick reference for future viewers.
Example
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Explanation from the documentation
table
String: The table name to compile the query against.columns
String: A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.selection
String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.selectionArgs
String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.groupBy
String: A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.having
String: A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.orderBy
String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.limit
String: Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.
I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.
As others have said, you can't have an implicit conversion, and that's by-design.
If you want you can avoid the need to specify the underlying type in the cast.
template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) noexcept {
return static_cast<typename std::underlying_type<E>::type>(e);
}
std::cout << foo(to_underlying(b::B2)) << std::endl;
I tried most of the things on this page and none of them worked for my Samsung S5. However, when I switched the cable to a USB-C type the problem seemed to be solved...until next time.
Regarding a previous answer
if (B) y = offset + slope*x
then (C) offset = y/(slope*x) is wrong
(C) should be:
offset = y-(slope*x)
After you commit your object into the db the object receives a value in its ID field.
So:
myObject.Field1 = "value";
// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();
// You can retrieve the id from the object
int id = myObject.ID;
Reduce() is..
It was ..
let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6
Change to
let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);
Also you can use in
let array=[5,4,19,2,7];
function findMax(acc,val)
{
if(val>acc){
acc=val;
}
}
let biggest=arrays.reduce(findMax); // 19
arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
v = 0
for i in range(len(arr)):
v = v ^ arr[i]
print(value) //6
The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.
$("#tableOfData").DataTable({
"pageLength": 50,
"ajax":{
url: someurl,
dataType : "json",
type: "post",
"data": {data to be sent}
},
"initComplete":function( settings, json){
console.log(json);
// call your function here
}
});
If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.
Three Answers :
Simple :
<img>
<xsl:attribute name="src">
<xsl:value-of select="//your/xquery/path"/>
<xsl:value-of select="'vmLogo.gif'"/>
</xsl:attribute>
</img>
Using 'concat' :
<img>
<xsl:attribute name="src">
<xsl:value-of select="concat(//your/xquery/path,'vmLogo.gif')"/>
</xsl:attribute>
</img>
Attribute shortcut as suggested by @TimC
<img src="{concat(//your/xquery/path,'vmLogo.gif')}" />
You don't put a component in directives
You register it in @NgModule
declarations:
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyChildComponent ],
bootstrap: [ App ]
})
and then You just put it in the Parent's Template HTML as : <my-child></my-child>
That's it.
I just went through the character map to get these. They are all in Calibri.
Number Name HTML Code Appearance ------ -------------------- --------- ---------- U+2000 En Quad   " " U+2001 Em Quad   " " U+2002 En Space   " " U+2003 Em Space   " " U+2004 Three-Per-Em Space   " " U+2005 Four-Per-Em Space   " " U+2006 Six-Per-Em Space   " " U+2007 Figure Space   " " U+2008 Punctuation Space   " " U+2009 Thin Space   " " U+200A Hair Space   " " U+200B Zero-Width Space ​ "" U+200C Zero Width Non-Joiner ‌ "" U+200D Zero Width Joiner ‍ "" U+200E Left-To-Right Mark ‎ "" U+200F Right-To-Left Mark ‏ "" U+202F Narrow No-Break Space   " "
I know this is an old thread, but I like my own plugin that can cycle through whitespace modes (none, selection, and all) via a single shortcut. It also provides menu items under a View | Whitespace menu.
Hopefully people will find this useful - it is used by a lot of people :)
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
import array
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]
Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.
You can try this
var scroll=$('#scroll');
scroll.animate({scrollTop: scroll.prop("scrollHeight")});
If it's errors you want to hide you can do it like this
$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on
I have had suspicions Chrome is starting to get stupid and bulky for a while, and my problems started after updating it. Since Ampps worked better when connected to Internet I put 1 + 1 together. Under Chrome Advanced settings try to dig into the Preload webpages for better performance feature. And kill it.
Ironic, but not unexpected, as it seems to get confused about preloading Localhost. In my case it was the instant fix after hours of wasted config fiddling and weeks of suffering.
Thank you Google devs.
No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.
Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.
While most answers are a copy of SolutionYogi's answer, they all miss an important check to see if 'cell' is not null which will return an error if clicking on the headers. So, here is the answer with the check included:
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
// check if not null
if(!cell) return; // no errors!
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
If the variables are being generated and not saved to a file you cannot pipe them in into source
. The deceptively simple way to do it is this:
some command | xargs
You can easily enable debugging support using an option for the @EnableWebSecurity
annotation:
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
The best solution is to reconfigure the XAMPP Apache server to listen and use different port numbers. Here is how you do it:
1) First, you need to open the Apache “httpd.conf” file and configure it to use/listen on a new port no. To open httpd.conf file, click the “Config” button next to Apache “Start” and “Admin” buttons. In the popup menu that opens, click and open httpd.conf
2) Within the httpd.conf file search for “listen”. You’ll find two rows with something like:
#Listen 12.34.56.78:80
Listen 80
Change the port no to a port no. of your choice (e.g. port 1234) like below
#Listen 12.34.56.78:1234
Listen 1234
3) Next, in the same httpd.conf file look for “ServerName localhost:” Set it to the new port no.
ServerName localhost:1234
4) Save and close the httpd.conf file.
5) Now click the Apache config button again and open the “httpd-ssl.conf” file.
6) In the httpd-ssl.conf file, look for “Listen” again. You may find:
Listen 443
Change it to listen on a new port no of your choice. Say like:
Listen 1443
7) In the same httpd-ssl.conf file find another line that says <VirtualHost _default_:443>
. Change this to your new port no. (like 1443)
8) Also in the same httpd-ssl.conf you can find another line defining the port no. For that look for “ServerName”. you might find something like:
ServerName www.example.com:443 or ServerName localhost:433
Change this ServerName to your new port no.
8) Save and close the httpd-ssl.conf file.
9) Finally, there’s just one more place you should change the port no. For that, click and open the “Config” button of your XAMPP Control Panel. Then click the, “Service and Port Settings” button. Within it, click the “Apache” tab and enter and save the new port nos in the “main port” and “SSL port” boxes. Click save and close the config boxes.
That should do the trick. Now “Start” Apache and if everything goes well, your Apache server should start up.
You will also see the Apache Port/s no in the XAMPP control panel has change to the new port IDs you set.
I feel many of the answers here are lacking a creative component, very much needed for time travel computations. I present my solution for a temporal translation of 30 minutes.
(jsfiddle here)
function fluxCapacitor(n) {
var delta,sigma=0,beta="ge";
(function(K,z){
(function(a,b,c){
beta=beta+"tT";
switch(b.shift()) {
case'3':return z('0',a,c,b.shift(),1);
case'0':return z('3',a,c,b.pop());
case'5':return z('2',a,c,b[0],1);
case'1':return z('4',a,c,b.shift());
case'2':return z('5',a,c,b.pop());
case'4':return z('1',a,c,b.pop(),1);
}
})(K.pop(),K.pop().split(''),K.pop());
})(n.toString().split(':'),function(b,a,c,b1,gamma){
delta=[c,b+b1,a];sigma+=gamma?3600000:0;
beta=beta+"im";
});
beta=beta+"e";
return new Date (sigma+(new Date( delta.join(':')))[beta]());
}
One option is to make two plots side by side. ggplot2
provides a nice option for this with facet_wrap()
:
dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
, y = c(rnorm(100), rlnorm(100, 9, 2))
, index = rep(1:2, each = 100)
)
require(ggplot2)
ggplot(dat, aes(x,y)) +
geom_point() +
facet_wrap(~ index, scales = "free_y")
You could read the entire file with dynamic memory allocation, but isn't a good idea because if the file is too big, you could have memory problems.
So is better read short parts of the file and print it.
#include <stdio.h>
#define BLOCK 1000
int main() {
FILE *f=fopen("teste.txt","r");
int size;
char buffer[BLOCK];
// ...
while((size=fread(buffer,BLOCK,sizeof(char),f)>0)
fwrite(buffer,size,sizeof(char),stdout);
fclose(f);
// ...
return 0;
}
If you are still looking to use Google Finance for your data you can check this out.
I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)
Remove the spaces from the original string and split on semicolon
$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')
$addresses
becomes:
@('[email protected]','[email protected]','[email protected]')
For existing ssh keys, I think that it's a bug in Eclipse Juno 3.8.
What I did:
1) Load the existing key by going to: Window > Preferences > "Search ssh" > Key Management Tab > Load Existing Key > Select the private key which you already have
2) Save that key by clicking the button Save Private Key. Let's name it id_dsa_github
3) Now check if push and pull are working or not. It should be.
4) Now in the general tab, remove the private key id_dsa_github and add your previous private key by clicking the button Add private key
Now you are good to go. It's taking at least one time to do all the things from EGit to register, I guess.
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.
In Keras (v2.1.5)
from keras.models import Sequential
from keras.layers import Dense
def get_model(n_x, n_h1, n_h2):
model = Sequential()
model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
model.add(Dense(n_h2, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
return model
In tf.keras (v1.9)
import tensorflow as tf
def get_model(n_x, n_h1, n_h2):
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(4, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
return model
or it can be imported the following way instead of the above-mentioned way
from tensorflow.keras.layers import Dense
The official documentation of tf.keras
Note: TensorFlow Version is 1.9
If there are only two variables to check and you're using Guava, you can use MoreObjects.firstNonNull(T first, T second).
NOTE this answer is now incorrect. I may get back to it at a later time.
As others have pointed out, you can't set the height of a table unless you set its display to block
, but then you get a scrolling header. So what you're looking for is to set the height
and display:block
on the tbody
alone:
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Here's the fiddle.
Use onKeyDown
event, and inside that check the key code of the key pressed by user. Key code of Enter
key is 13, check the code and put the logic there.
Check this example:
class CartridgeShell extends React.Component {_x000D_
_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = {value:''}_x000D_
_x000D_
this.handleChange = this.handleChange.bind(this);_x000D_
this.keyPress = this.keyPress.bind(this);_x000D_
} _x000D_
_x000D_
handleChange(e) {_x000D_
this.setState({ value: e.target.value });_x000D_
}_x000D_
_x000D_
keyPress(e){_x000D_
if(e.keyCode == 13){_x000D_
console.log('value', e.target.value);_x000D_
// put the login here_x000D_
}_x000D_
}_x000D_
_x000D_
render(){_x000D_
return(_x000D_
<input value={this.state.value} onKeyDown={this.keyPress} onChange={this.handleChange} fullWidth={true} />_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<CartridgeShell/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id = 'app' />
_x000D_
Note: Replace the input
element by Material-Ui TextField
and define the other properties also.
for python3 use subprocess
import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)
As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog: Basic Auth with custom middleware
I referred the same blog but had to do 2 adaptations:
While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public static string UserNameFromAppSettings { get; private set; }
public static string PasswordFromAppSettings { get; private set; }
//set username and password from appsettings.json
UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
}
If you are talking about sed
, this works:
sed -e "s/ /,/g" < a.txt
In vim
, use same regex to replace:
s/ /,/g
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
Your static method should go from:
public static class SimpleUsing
{
public static void DoUsing(Action<MyDataContext> action)
{
using (MyDataContext db = new MyDataContext())
action(db);
}
}
To:
public static class SimpleUsing
{
public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
{
using (MyDataContext db = new MyDataContext())
return action(db);
}
}
This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.
Try using the below command:
ng update @angular/cli --migrate-only --from=1.7.4
It will perform the below
Updating karma configuration
Updating configuration
Removing old config file (.angular-cli.json)
Writing config file (angular.json)
Pls note that the above command should be run in the folder where you have file .angular-cli.json
and it will be then replaced by angular.json
.
Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi
) to store one of the local variables where the slow version doesn't.
The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.
In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.
For example, consider the following two methods. They were adapted from a real-life example:
interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed {
public int[] Array;
public int this[int index] {
get { return Array[index]; }
set { Array[index] = value; }
}
}
static int Generic<T>(int length, T a, T b) where T : IIndexed {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
One is a generic version of the other. Replacing the generic type with StructArray
would make the methods identical. Because StructArray
is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.
On Windows they get installed to separate folders, "C:\python26" and "C:\python31", but the executables have the same "python.exe" name.
I created another "C:\python" folder that contains "python.bat" and "python3.bat" that serve as wrappers to "python26" and "python31" respectively, and added "C:\python" to the PATH
environment variable.
This allows me to type python
or python3
in my .bat Python wrappers to start the one I desire.
On Linux, you can use the #!
trick to specify which version you want a script to use.
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
To catch Guzzle errors you can do something like this:
try {
$response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
echo 'Uh oh! ' . $e->getMessage();
}
... but, to be able to "log" or "resend" your request try something like this:
// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
'request.error',
function(Event $event) {
//write log here ...
if ($event['response']->getStatusCode() == 401) {
// create new token and resend your request...
$newRequest = $event['request']->clone();
$newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
$newResponse = $newRequest->send();
// Set the response object of the request without firing more events
$event['response'] = $newResponse;
// You can also change the response and fire the normal chain of
// events by calling $event['request']->setResponse($newResponse);
// Stop other events from firing when you override 401 responses
$event->stopPropagation();
}
});
... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
// Stop other events from firing when you get stytus-code != 200
$event->stopPropagation();
}
});
thats a good idea to prevent guzzle errors like:
request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response
in your application.
divToUpdate.innerHTML = "";
You need to use [[
, the programmatic equivalent of $
. Otherwise, for example, when i
is col1
, R will look for df$i
instead of df$col1
.
for(i in names(df)){
df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
A Kotlin Extension to observe on the global layout and perform a given task when height is ready dynamically.
Usage:
view.height { Log.i("Info", "Here is your height:" + it) }
Implementation:
fun <T : View> T.height(function: (Int) -> Unit) {
if (height == 0)
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
function(height)
}
})
else function(height)
}
You could just use string division
require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'
Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.
You need to check one if you have two
if(rbMale.Checked)
{
}
else
{
}
You need to check all the checkboxes if more then two
if(rb1.Checked)
{
}
else if(rb2.Checked)
{
}
else if(rb3.Checked)
{
}
The properties that can be set for a figure
is referenced here.
You could then use:
figure_number = 1;
x = 0; % Screen position
y = 0; % Screen position
width = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)
figure(figure_number, 'Position', [x y width height]);
Suppose we have a generator:
def gen():
for i in range(10):
yield i
We can wrap the generator, along with the known length, in an object:
import itertools
class LenGen(object):
def __init__(self,gen,length):
self.gen=gen
self.length=length
def __call__(self):
return itertools.islice(self.gen(),self.length)
def __len__(self):
return self.length
lgen=LenGen(gen,10)
Instances of LenGen
are generators themselves, since calling them returns an iterator.
Now we can use the lgen
generator in place of gen
, and access len(lgen)
as well:
def new_gen():
for i in lgen():
yield float(i)/len(lgen)
for i in new_gen():
print(i)
You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:
var baseAddress = "http://www.example.com/1.0/service/action";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
hope it helps,
import React, { Component } from 'react';
import { Image, StyleSheet } from 'react-native';
export default class App extends Component {
render() {
return (
<Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
);
}
}
const s = StyleSheet.create({
backgroundImage: {
flex: 1,
width: null,
height: null,
}
});
You can try it at: https://sketch.expo.io/B1EAShDie (from: github.com/Dorian/sketch-reactive-native-apps)
Docs: https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting
int64_t
is guaranteed by the C99 standard to be exactly 64 bits wide on platforms that implement it, there's no such guarantee for a long
which is at least 32 bits so it could be more.
§7.18.1.3 Exact-width integer types 1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.
The worst language I "worked" with, was "karol, the robot" — which was a programming language in German. And could do nothing more than move a robot on screen xD
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
A jQuery solution: Add this button inside any element you want to be able to close:
<button type='button' class='close' onclick='$(this).parent().remove();'>×</button>
or to 'just' hide it:
<button type='button' class='close' onclick='$(this).parent().hide();'>×</button>
I was having the same problem. That's what i tried and it works. I am sharing my xml and java code. Hope this will help someone.
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
< NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_thumbnail"
android:layout_width="match_parent"
android:layout_height="200dp" />
<TextView
android:id="@+id/tv_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Description" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Buy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reviews" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rc_reviews"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</NestedScrollView >
Here is the related java code. It works like a charm.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setNestedScrollingEnabled(false);
Please
[XAMPP Installation Directory]\php\php.ini
(e.g. C:\xampp\php\php.ini
)php.ini
in Notepad or any Text editormax_execution_time
andmax_execution_time = 90
)If there will still be the same error after that, try to increase the value for the max_execution_time
further more.
The following are other solutions offered elsewhere:
If on a Windows Host:
<?
$f = 'f:/www/docs';
$obj = new COM ( 'scripting.filesystemobject' );
if ( is_object ( $obj ) )
{
$ref = $obj->getfolder ( $f );
echo 'Directory: ' . $f . ' => Size: ' . $ref->size;
$obj = null;
}
else
{
echo 'can not create object';
}
?>
Else, if on a Linux Host:
<?
$f = './path/directory';
$io = popen ( '/usr/bin/du -sk ' . $f, 'r' );
$size = fgets ( $io, 4096);
$size = substr ( $size, 0, strpos ( $size, "\t" ) );
pclose ( $io );
echo 'Directory: ' . $f . ' => Size: ' . $size;
?>
You should use <span>
, because as specified by the spec, <font>
has been deprecated and probably won't display as you intend.
Using Java 8 parallelStream would be faster. Below is my code for finding Nth prime number
public static Integer findNthPrimeNumber(Integer nthNumber) {
List<Integer> primeList = new ArrayList<>();
primeList.addAll(Arrays.asList(2, 3));
Integer initializer = 4;
while (primeList.size() < nthNumber) {
if (isPrime(initializer, primeList)) {
primeList.add(initializer);
}
initializer++;
}
return primeList.get(primeList.size() - 1);
}
public static Boolean isPrime(Integer input, List<Integer> primeList) {
return !(primeList.parallelStream().anyMatch(i -> input % i == 0));
}
@Test
public void findNthPrimeTest() {
Problem7 inputObj = new Problem7();
Integer methodOutput = inputObj.findNthPrimeNumber(100);
Assert.assertEquals((Integer) 541, methodOutput);
Assert.assertEquals((Integer) 104743, inputObj.findNthPrimeNumber(10001));
}
I found this quite frustrating given that my timezone is Australian and that strtotime()
hates UK dates.
If the current day is a Sunday, then strtotime("monday this week")
will return the day after.
To overcome this:
Caution: This is only valid for Australian/UK dates
$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
No, it's not possible.
It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".
I tried these steps: https://developers.facebook.com/docs/marketing-api/access#graph-api-explorer
Get Permanent Page Access Token
One Tip, it only worked for me when the page language is english.
In my case this error came for the script which was running fine before. So I figured out that this might be due to my JAVA update. Before I was using java 1.8 but I had accidentally updated to java 1.9. When I switched back to java 1.8 the error disappeared and everything is running fine. For those, who get this error for the same reason but do not know how to switch back to older java version on ubuntu: run
sudo update-alternatives --config java
and make the selection for java version
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
It is called a type parameter constraint. Effectively it constraints what type T can be.
The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
I have found a simple solution: http://andwise.net/?p=403
(with slight adjustments for better readability)
This is for all who want to unpack and modify the original system.img that you can flash using recovery. system.img (which you get from the google factory images for example) represents a sparse ext4 loop mounted file system. It is mounted into /system of your device. Note that this tutorial is for ext4 file system. You may have system image which is yaffs2, for example.
The way it is mounted on Galaxy Nexus:
/dev/block/platform/omap/omap_hsmmc.0/by-name/system /system ext4 ro,relatime,barrier=1,data=ordered 0 0
Prerequisites:
- Linux box or virtual machine
- simg2img and make_ext4fs binaries, which can be downloaded from the linux package android-tools-fsutils
Procedure:
Place your system.img and the 2 binaries in one directory, and make sure the binaries have exec permission.
Part 1 – mount the file-system
mkdir sys
./simg2img system.img sys.raw
sudo mount -t ext4 -o loop sys.raw sys/
Then you have your system partition mounted in ‘sys/’ and you can modify whatever you want in ‘sys/’. For example de-odex apks and framework jars.
Part 2 – create a new flashable system image
sudo ./make_ext4fs -s -l 512M -a system new.img sys/
sudo umount sys
rm -fr sys
Now you can simply type:
fastboot flash system new.img
here is a great article of how to vetical align.. I like the float way.
http://www.vanseodesign.com/css/vertical-centering/
The HTML:
<div id="main">
<div id="floater"></div>
<div id="inner">Content here</div>
</div>
And the corresponding style:
#main {
height: 250px;
}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#inner {
clear: both;
height: 100px;
}
Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.
spring:
servlet:
multipart:max-file-size: 10MB
multipart:max-request-size: 100MB
server:
tomcat:
max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version
You might need to add this for the latest sprintboot version ->
server: tomcat: max-http-form-post-size: 10MB
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
if you choose the style of UITableViewStyleGrouped,you need to implement the Header
and Footer
height delegate method,and the return value need greater than 0; like this:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return CGFLOAT_MIN;
}
HashMap compatible Pair class:
public class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
(( this.first == otherPair.first ||
( this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
( this.second == otherPair.second ||
( this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))) );
}
return false;
}
public String toString()
{
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}
GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g
switch, like this:
gcc program.c -g
Then use gdb:
$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>
Here is a nice tutorial to get you started with GDB.
Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
I've been using vzczc's answer using recursive cte's for some time, but have wanted to update it to handle a variable length separator and also to handle strings with leading and lagging "separators" such as when you have a csv file with records such as:
"Bob","Smith","Sunnyvale","CA"
or when you are dealing with six part fqn's as shown below. I use these extensively for logging of the subject_fqn for auditing, error handling, etc. and parsename only handles four parts:
[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]
Here is my updated version, and thanks to vzczc's for his original post!
select * from [utility].[split_string](N'"this"."string"."gets"."split"."and"."removes"."leading"."and"."trailing"."quotes"', N'"."', N'"', N'"');
select * from [utility].[split_string](N'"this"."string"."gets"."split"."but"."leaves"."leading"."and"."trailing"."quotes"', N'"."', null, null);
select * from [utility].[split_string](N'[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]', N'].[', N'[', N']');
create function [utility].[split_string] (
@input [nvarchar](max)
, @separator [sysname]
, @lead [sysname]
, @lag [sysname])
returns @node_list table (
[index] [int]
, [node] [nvarchar](max))
begin
declare @separator_length [int]= len(@separator)
, @lead_length [int] = isnull(len(@lead), 0)
, @lag_length [int] = isnull(len(@lag), 0);
--
set @input = right(@input, len(@input) - @lead_length);
set @input = left(@input, len(@input) - @lag_length);
--
with [splitter]([index], [starting_position], [start_location])
as (select cast(@separator_length as [bigint])
, cast(1 as [bigint])
, charindex(@separator, @input)
union all
select [index] + 1
, [start_location] + @separator_length
, charindex(@separator, @input, [start_location] + @separator_length)
from [splitter]
where [start_location] > 0)
--
insert into @node_list
([index],[node])
select [index] - @separator_length as [index]
, substring(@input, [starting_position], case
when [start_location] > 0
then
[start_location] - [starting_position]
else
len(@input)
end) as [node]
from [splitter];
--
return;
end;
go
I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>
When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey
instead of ControlBrushKey
:
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>
Hope this helps someone out.
<<
is a binary shift, shifting 1 to the left 8 places.
4'b0001 << 1 => 4'b0010
>>
is a binary right shift adding 0's to the MSB.
>>>
is a signed shift which maintains the value of the MSB if the left input is signed.
4'sb1011 >> 1 => 0101
4'sb1011 >>> 1 => 1101
Three ways to indicate left operand is signed:
module shift;
logic [3:0] test1 = 4'b1000;
logic signed [3:0] test2 = 4'b1000;
initial begin
$display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
$display("%b", test2 >>> 1 ); //Declared as signed type
$display("%b", 4'sb1000 >>> 1 ); //Signed constant
$finish;
end
endmodule
if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
or
if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
:)
$ pip install django-tables2
settings.py
INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'
models.py
class hotel(models.Model):
name = models.CharField(max_length=20)
views.py
from django.shortcuts import render
def people(request):
istekler = hotel.objects.all()
return render(request, 'list.html', locals())
list.html
{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="{% static
'ticket/static/css/screen.css' %}" />
</head>
<body>
{% render_table istekler %}
</body>
</html>
The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.
It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.
Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.
What is the difference between char array vs char pointer in C?
C99 N1256 draft
There are two different uses of character string literals:
Initialize char[]
:
char c[] = "abc";
This is "more magic", and described at 6.7.8/14 "Initialization":
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So this is just a shortcut for:
char c[] = {'a', 'b', 'c', '\0'};
Like any other regular array, c
can be modified.
Everywhere else: it generates an:
So when you write:
char *c = "abc";
This is similar to:
/* __unnamed is magic because modifying it gives UB. */
static char __unnamed[] = "abc";
char *c = __unnamed;
Note the implicit cast from char[]
to char *
, which is always legal.
Then if you modify c[0]
, you also modify __unnamed
, which is UB.
This is documented at 6.4.5 "String literals":
5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]
6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
6.7.8/32 "Initialization" gives a direct example:
EXAMPLE 8: The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects
s
andt
whose elements are initialized with character string literals.This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
GCC 4.8 x86-64 ELF implementation
Program:
#include <stdio.h>
int main(void) {
char *s = "abc";
printf("%s\n", s);
return 0;
}
Compile and decompile:
gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o
Output contains:
char *s = "abc";
8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)
f: 00
c: R_X86_64_32S .rodata
Conclusion: GCC stores char*
it in .rodata
section, not in .text
.
If we do the same for char[]
:
char s[] = "abc";
we obtain:
17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)
so it gets stored in the stack (relative to %rbp
).
Note however that the default linker script puts .rodata
and .text
in the same segment, which has execute but no write permission. This can be observed with:
readelf -l a.out
which contains:
Section to Segment mapping:
Segment Sections...
02 .text .rodata
The other difference between divide and conquer and dynamic programming could be:
Divide and conquer:
Dynamic programming:
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
Asymptotic upper bound means that a given algorithm executes during the maximum amount of time, depending on the number of inputs.
Let's take a sorting algorithm as an example. If all the elements of an array are in descending order, then to sort them, it will take a running time of O(n)
, showing upper bound complexity. If the array is already sorted, the value will be O(1)
.
Generally, O-notation
is used for the upper bound complexity.
Asymptotically tight bound (c1g(n) ≤ f(n) ≤ c2g(n)) shows the average bound complexity for a function, having a value between bound limits (upper bound and lower bound), where c1 and c2 are constants.
echo is alias to Write-Output although it looks the same as Write-Host.
It isn't What is the difference between echo and Write-Host in PowerShell?.
echo is an alias for Write-Output, which writes to the Success output stream. This allows output to be processed through pipelines or redirected into files. Write-Host writes directly to the console, so the output can't be redirected/processed any further.
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.
If we have 3 parameters (t0, a0, a1)
for Relu, that is we want to implement
if x > t0:
x = x * a1
else:
x = x * a0
We can use the following code:
X = X * (X > t0) * a1 + X * (X < t0) * a0
X
there is a matrix.
I got it working using:
$('#id-of-table').on('draw.dt', function() {
// do action here
});
<img style="float: right;" alt="" src="http://example.com/image.png" />
<div style="clear: right">
...text...
</div>
I found this approach useful. This way you do not need a class nor final
btnInsert.addMouseListener(new MouseAdapter() {
private Statement _statement;
public MouseAdapter setStatement(Statement _stmnt)
{
_statement = _stmnt;
return this;
}
@Override
public void mouseDown(MouseEvent e) {
String name = text.getText();
String from = text_1.getText();
String to = text_2.getText();
String price = text_3.getText();
String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
try {
_statement.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}.setStatement(statement));
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
You can also "prepend" the environment variable setting by using 'environment' command:
run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh"
You can use Collections.swap(List<?> list, int i, int j);
The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:
import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')
np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
i know it is a controversial topic, and likely i get burned now. but here are my thoughts.
For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.
If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.
Watch Video or Follow the step
Install bootstrap 4 in angular 2 / angular 4 / angular 5 / angular 6
There is three way to include bootstrap in your project
1) Add CDN Link in index.html file
2) Install bootstrap using npm and set path in angular.json Recommended
3) Install bootstrap using npm and set path in index.html file
I recommended you following 2 methods that are installed bootstrap using npm because its installed in your project directory and you can easily access it
Method 1
Add Bootstrap, Jquery and popper.js CDN path to you angular project index.html file
Bootstrap.css
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
Bootstrap.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
Jquery.js
https://code.jquery.com/jquery-3.2.1.slim.min.js
Popper.js
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js
Method 2
1) Install bootstrap using npm
npm install bootstrap --save
after the installation of Bootstrap 4, we Need two More javascript Package that is Jquery and Popper.js without these two package bootstrap is not complete because Bootstrap 4 is using Jquery and popper.js package so we have to install as well
2) Install JQUERY
npm install jquery --save
3) Install Popper.js
npm install popper.js --save
Now Bootstrap is Install on you Project Directory inside node_modules Folder
open angular.json this file are available on you angular directory open that file and add the path of bootstrap, jquery, and popper.js files inside styles[] and scripts[] path see the below example
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
Note: Don't change a sequence of js file it should be like this
Method 3
Install bootstrap using npm follow Method 2 in method 3 we just set path inside index.html file instead of angular.json file
bootstrap.css
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css">
Jquery.js
<script src="node_modules/jquery/dist/jquery.min.js"><br>
Bootstrap.js
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"><br>
Popper.js
<script src="node_modules/popper.js/dist/umd/popper.min.js"><br>
Now Bootstrap Working fine Now
A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:
since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:
WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value
You need to implement your own Comparator
, and then use it: for example
Arrays.sort(persons, new PersonComparator());
Your Comparator could look a bit like this:
public class PersonComparator implements Comparator<? extends Person> {
public int compare(Person p1, Person p2) {
int nameCompare = p1.name.compareToIgnoreCase(p2.name);
if (nameCompare != 0) {
return nameCompare;
} else {
return Integer.valueOf(p1.age).compareTo(Integer.valueOf(p2.age));
}
}
}
The comparator first compares the names, if they are not equals it returns the result from comparing them, else it returns the compare result when comparing the ages of both persons.
This code is only a draft: because the class is immutable you could think of building an singleton of it, instead creating a new instance for each sorting.
You can use:
start "windowTitle" fullPath/file.exe
Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:
start "" fullPath/file.exe
use:
std::vector <Acard> playerHand;
everywhere qualify it by std::
or do:
using std::vector;
in your cpp file.
You have to do this because vector
is defined in the std
namespace and you do not tell your program to find it in std
namespace, you need to tell that.
I wrote a little script to see my log files better, it's nothing special, but might help a lot of the people who are learning perl. It does DNS lookups on the IP addresses after it extracts them.
You can use DataFrame.values
to get an numpy array of the data and then use NumPy functions such as argsort()
to get the most correlated pairs.
But if you want to do this in pandas, you can unstack
and sort the DataFrame:
import pandas as pd
import numpy as np
shape = (50, 4460)
data = np.random.normal(size=shape)
data[:, 1000] += data[:, 2000]
df = pd.DataFrame(data)
c = df.corr().abs()
s = c.unstack()
so = s.sort_values(kind="quicksort")
print so[-4470:-4460]
Here is the output:
2192 1522 0.636198
1522 2192 0.636198
3677 2027 0.641817
2027 3677 0.641817
242 130 0.646760
130 242 0.646760
1171 2733 0.670048
2733 1171 0.670048
1000 2000 0.742340
2000 1000 0.742340
dtype: float64
select status, timeplaced
from orders
where TIMEPLACED>'2017-06-12 00:00:00'
var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");
resulting_list = list(first_list)
resulting_list.extend(x for x in second_list if x not in resulting_list)
This warning comes when you don't add a key to your list items.As per react js Docs -
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
);
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
Question: Where is application-specific cache located on Android?
Answer: /data/data
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):
Source: developer.android.com
Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.
Because of this, you should use the onPause()
method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle)
is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle
, to be later received in onCreate(Bundle)
if the activity needs to be re-created.
Note that it is important to save persistent data in onPause()
instead of onSaveInstanceState(Bundle)
because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.
onPostCreate(Bundle savedInstanceState)
Called when activity start-up is complete (after
onStart()
andonRestoreInstanceState(Bundle)
have been called).
onPostResume()
Called when activity resume is complete (after
onResume()
has been called).
onSaveInstanceState(Bundle outState)
Called to retrieve per-instance state from an activity before being killed so that the state can be restored in
onCreate(Bundle)
oronRestoreInstanceState(Bundle)
(the Bundle populated by this method will be passed to both).
onRestoreInstanceState(Bundle savedInstanceState)
This method is called after
onStart()
when the activity is being re-initialized from a previously saved state, given here insavedInstanceState
.
My application code using all these methods:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText txtUserName;
private EditText txtPassword;
Button loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Ravi","Main OnCreate");
txtUserName=(EditText) findViewById(R.id.username);
txtPassword=(EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.login);
loginButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Log.d("Ravi", "Login processing initiated");
Intent intent = new Intent(this,LoginActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userName",txtUserName.getText().toString());
bundle.putString("password",txtPassword.getText().toString());
intent.putExtras(bundle);
startActivityForResult(intent,1);
// IntentFilter
}
public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
Log.d("Ravi back result:", "start");
String result = resIntent.getStringExtra("result");
Log.d("Ravi back result:", result);
TextView txtView = (TextView)findViewById(R.id.txtView);
txtView.setText(result);
Intent sendIntent = new Intent();
//sendIntent.setPackage("com.whatsapp");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
@Override
protected void onStart() {
super.onStart();
Log.d("Ravi","Main Start");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("Ravi","Main ReStart");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Ravi","Main Pause");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Ravi","Main Resume");
}
@Override
protected void onStop() {
super.onStop();
Log.d("Ravi","Main Stop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Ravi","Main OnDestroy");
}
@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
Log.d("Ravi","Main onPostCreate");
}
@Override
protected void onPostResume() {
super.onPostResume();
Log.d("Ravi","Main PostResume");
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Login Activity:
public class LoginActivity extends AppCompatActivity {
private TextView txtView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtView = (TextView) findViewById(R.id.Result);
Log.d("Ravi","Login OnCreate");
Bundle bundle = getIntent().getExtras();
txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
//Intent intent = new Intent(this,MainActivity.class);
Intent intent = new Intent();
intent.putExtra("result","Success");
setResult(1,intent);
// finish();
}
}
output: ( Before pause)
D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume
output: ( After resume from pause)
D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume
Note that onPostResume()
is invoked even though it's not quoted as life cycle method.
Thanks @Joey. It's what I am looking for.
I just bring some improvements:
function Stop-Processes {
param(
[parameter(Mandatory=$true)] $processName,
$timeout = 5
)
$processList = Get-Process $processName -ErrorAction SilentlyContinue
if ($processList) {
# Try gracefully first
$processList.CloseMainWindow() | Out-Null
# Wait until all processes have terminated or until timeout
for ($i = 0 ; $i -le $timeout; $i ++){
$AllHaveExited = $True
$processList | % {
$process = $_
If (!$process.HasExited){
$AllHaveExited = $False
}
}
If ($AllHaveExited){
Return
}
sleep 1
}
# Else: kill
$processList | Stop-Process -Force
}
}
For the things that you are suggesting you can just change the levels using the levels
:
levels(iris$Species)[3] <- 'new'
Under the hood BeautifulSoup now uses lxml. Requests, lxml & list comprehensions makes a killer combo.
import requests
import lxml.html
dom = lxml.html.fromstring(requests.get('http://www.nytimes.com').content)
[x for x in dom.xpath('//a/@href') if '//' in x and 'nytimes.com' not in x]
In the list comp, the "if '//' and 'url.com' not in x" is a simple method to scrub the url list of the sites 'internal' navigation urls, etc.
string result = Path.GetTempPath();
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath
Use the Take(int n)
method:
var q = query.Take(10);
Compiling with -source 1.5 -target 1.5 (in a JDK 6 environment) will honor only language elements that were in 1.5 and prior. Great. But there were no language changes in 6 anyway. Problem with this approach (on Mac with 1.6) is that using classes that came AFTER 1.5 will still compile because they exist in the rt.jar. So one could run in a 1.5 env and get a class not found exception with no prior warning when compiling. I found this out the hard way with javax.swing.event.RowSorterEvent/Listener. Both entered "Since 1.6" but are not caught with -source 1.5
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
Assume you were:
There are many more examples, but these are the most common, in my experience.
$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");
this work if you move to previous or next field by mouse, but by enter key, this is not work !!!
@Presto Thanks! Yours worked perfectly for me, but I came up with a simpler version to save changing everything around.
Add a <span>
tag around the desired link text, specifying class within. (e.g. home tag)
<nav id="top-menu">
<ul>
<li> <a href="home.html"><span class="currentLink">Home</span></a> </li>
<li> <a href="about.html">About</a> </li>
<li> <a href="cv.html">CV</a> </li>
<li> <a href="photos.html">Photos</a> </li>
<li> <a href="archive.html">Archive</a> </li>
<li> <a href="contact.html">Contact</a></li>
</ul>
</nav>
Then edit your CSS accordingly:
.currentLink {
color:#baada7;
}
If you use C++, it is best to use C++ interface:
using namespace cv;
// Capture the Image from the webcam
VideoCapture cap(0);
// Get the frame
Mat save_img; cap >> save_img;
if(save_img.empty())
{
std::cerr << "Something is wrong with the webcam, could not get frame." << std::endl;
}
// Save the frame into a file
imwrite("test.jpg", save_img); // A JPG FILE IS BEING SAVED
The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.
The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.
A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.
So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.
Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)
But, specifically, you don't need an offsite service to handle this.
I think you should first define all your routes and as the last route add
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('what???');
});
An example app which does work:
var express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('hello world');
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000, '127.0.0.1');
alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt
.
./app.js
./public
./public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?
If you just need the name of the current directory, you could do something like this:
((Get-Location) | Get-Item).Name
Assuming you are working from C:\Temp\Location\MyWorkingDirectory>
Output
MyWorkingDirectory
in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.
In Wordpress hide Warnings and Notices add following code in wp-config.php file
ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Combining @comte's answer and dmdip's answer in Get index of a row of a pandas dataframe as an integer
df.tail(1).index.item()
gives you the value of the index.
Note that indices are not always well defined not matter they are multi-indexed or single indexed. Modifying dataframes using indices might result in unexpected behavior. We will have an example with a multi-indexed case but note this is also true in a single-indexed case.
Say we have
df = pd.DataFrame({'x':[1,1,3,3], 'y':[3,3,5,5]}, index=[11,11,12,12]).stack()
11 x 1
y 3
x 1
y 3
12 x 3
y 5 # the index is (12, 'y')
x 3
y 5 # the index is also (12, 'y')
df.tail(1).index.item() # gives (12, 'y')
Trying to access the last element with the index df[12, "y"]
yields
(12, y) 5
(12, y) 5
dtype: int64
If you attempt to modify the dataframe based on the index (12, y)
, you will modify two rows rather than one. Thus, even though we learned to access the value of last row's index, it might not be a good idea if you want to change the values of last row based on its index as there could be many that share the same index. You should use df.iloc[-1]
to access last row in this case though.
Reference
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.item.html
EDIT: The Numpy project now provides pre-compiled packages in the wheel format (package format enabling compiled code as binary in packages), so the installation is now as easy as with other packages.
Numpy (as also some other packages like Scipy, Pandas etc.) includes lot's of C-, Cython, and Fortran code that needs to be compiled properly, before you can use it. This is, btw, also the reason why these Python-packages provide such fast Linear Algebra.
To get precompiled packages for Windows, have a look at Gohlke's Unofficial Windows Binaries or use a distribution like Winpython (just works) or Anaconda (more complex) which provide an entire preconfigured environment with lots of packages from the scientific python stack.
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
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;
}
Using Moment, Underscore and jQuery, to iterate an array of dates.
Sample JSON:
"workerList": [{
"shift_start_dttm": "13/06/2017 20:21",
"shift_end_dttm": "13/06/2017 23:59"
}, {
"shift_start_dttm": "03/04/2018 00:00",
"shift_end_dttm": "03/05/2018 00:00"
}]
Javascript:
function getMinStartDttm(workerList) {
if(!_.isEmpty(workerList)) {
var startDtArr = [];
$.each(d.workerList, function(index,value) {
startDtArr.push(moment(value.shift_start_dttm.trim(), 'DD/MM/YYYY HH:mm'));
});
var startDt = _.min(startDtArr);
return start.format('DD/MM/YYYY HH:mm');
} else {
return '';
}
}
Hope it helps.
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'