From PHP's manual :
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
So you have it. The error message is not really helpful, I give you that though.
PHP7 introduced more function data type declarations, and the aforementioned link has been moved to Function arguments : Type declarations. From that page :
Valid types
Warning
Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:
<?php function test(boolean $param) {} test(true); ?>
The above example will output:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
The last warning is actually significant to understand the error "Argument must of type string, string given"; since mostly only class/interface names are allowed as argument type, PHP tries to locate a class name "string", but can't find any because it is a primitive type, thus fail with this awkward error.
Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int)
doesn't result in an error until the next return...
line:
class C1:
def __init__(self):
self.idn = 1
def add(self, ic: int):
return self.idn + ic
c1 = C1()
c1.add(2)
c1.add(c1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'
From the documentation
class
typing.Union
Union type; Union[X, Y] means either X or Y.
Hence the proper way to represent more than one return data type is
from typing import Union
def foo(client_id: str) -> Union[list,bool]
But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."
>>> def foo(a:str) -> list:
... return("Works")
...
>>> foo(1)
'Works'
As you can see I am passing a int value and returning a str. However the __annotations__
will be set to the respective values.
>>> foo.__annotations__
{'return': <class 'list'>, 'a': <class 'str'>}
Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?
Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
I never had any luck with that approach. I always do this (hope this helps):
var obj = {};
obj.first_name = $("#namec").val();
obj.last_name = $("#surnamec").val();
obj.email = $("#emailc").val();
obj.mobile = $("#numberc").val();
obj.password = $("#passwordc").val();
Then in your ajax:
$.ajax({
type: "POST",
url: hb_base_url + "consumer",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(obj),
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
shift
spaces.Restrictions:
Pseudocode:
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.
Delete completely:
right mouse click ? Menu ? Delete
Delete & Keep local:
Shift + right mouse click ? Menu ? Delete
You have to create sortDescriptor and then you can sort the nsmutablearray by using sortDescriptor like below.
let sortDescriptor = NSSortDescriptor(key: "birthDate", ascending: true, selector: #selector(NSString.compare(_:)))
let array = NSMutableArray(array: self.aryExist.sortedArray(using: [sortDescriptor]))
print(array)
It might not work correctly when using a program that is not attached to the console, because that app might still be running while you think you have the exit code. A solution to do it in C++ looks like below:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"
int _tmain( int argc, TCHAR *argv[] )
{
CString cmdline(GetCommandLineW());
cmdline.TrimLeft('\"');
CString self(argv[0]);
self.Trim('\"');
CString args = cmdline.Mid(self.GetLength()+1);
args.TrimLeft(_T("\" "));
printf("Arguments passed: '%ws'\n",args);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc < 2 )
{
printf("Usage: %s arg1,arg2....\n", argv[0]);
return -1;
}
CString strCmd(args);
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
(LPTSTR)(strCmd.GetString()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d)\n", GetLastError() );
return GetLastError();
}
else
printf( "Waiting for \"%ws\" to exit.....\n", strCmd );
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
int result = -1;
if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
{
printf("GetExitCodeProcess() failed (%d)\n", GetLastError() );
}
else
printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return result;
}
You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
I would probably use set
in the following manner :
set(l).issuperset(set(['a','b']))
or the other way round :
set(['a','b']).issubset(set(l))
I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...
Principally; you can assign a value to a static readonly field to a non-constant value at runtime, whereas a const has to be assigned a constant value.
Some advantages of LINQ over sprocs:
Some disadvantages of LINQ vs sprocs:
Security and manageability are something that people argue about too.
I used to be a big sproc guy, but I'm starting to lean towards LINQ as a better alternative in general. If there are some areas where sprocs are clearly better, then I'll probably still write a sproc but access it using LINQ. :)
You should use:
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("otherpage.aspx");
}
Try Visual Studio Code. Very good support for PHP and other languages directly or via extensions. It can not replace power of Visual Studio but it is powerful addition to Visual Studio. And you can run it on all OS (Windows, Linux, Mac...).
This problem is also caused by:
If you are on a mac/linux, and are using 'ControlMaster' in your ~/.ssh/config, there may be some ssh control master processes running.
To find them, run:
ps aux | grep '\[mux\]'
And kill the relevant ones.
The following will return true if two Calendar variables have the same day of the year.
public boolean isSameDay(Calendar c1, Calendar c2){
final int DAY=1000*60*60*24;
return ((c1.getTimeInMillis()/DAY)==(c2.getTimeInMillis()/DAY));
} // end isSameDay
How to get the First and Last Record of DB in c#.
SELECT TOP 1 *
FROM ViewAttendenceReport
WHERE EmployeeId = 4
AND AttendenceDate >='1/18/2020 00:00:00'
AND AttendenceDate <='1/18/2020 23:59:59'
ORDER BY Intime ASC
UNION
SELECT TOP 1 *
FROM ViewAttendenceReport
WHERE EmployeeId = 4
AND AttendenceDate >='1/18/2020 00:00:00'
AND AttendenceDate <='1/18/2020 23:59:59'
ORDER BY OutTime DESC;
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
This is worked for me using JAVA script for chrome extension.
document.body.innerHTML = myFunction();
function myFunction()
{
var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");
var str = document.body.innerHTML;
var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});
return res;
}
This covers following numbers pattern
9883443344
8888564723
7856128945
09883443344
0 9883443344
0-9883443344
919883443344
91 8834433441
91-9883443344
91 -9883443344
91- 9883443344
91 - 9883443344
91 -9883443344
+917878525200
+91 8834433441
+91-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
+91 -9883443344
0919883443344
0091-7779015989
0091 - 8834433440
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
022-24141414
079-22892350
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
must be
$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
you can simply use :
error_log("your message");
By default, the message will be send to the php system logger.
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
You could do this using SUMIF
. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:
- A B
1 100 YES
2 100 YES
3 100 NO
Using the formula: =SUMIF(B1:B3, "YES", A1:A3)
, you will get the result of 200
.
Here's a screenshot of a working example I just did in Excel:
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:
this.sidebar = !JSON.parse(this.sidebar);
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
For Mac(High Sierra), install the virtualenv on python3 and create a virtualenv for python2:
$ python3 -m pip install virtualenv
$ python3 -m virtualenv --python=python2 vp27
$ source vp27/bin/activate
(vp27)$ python --version
Python 2.7.14
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
I've found FileFormat.info's Unicode Character Search to be most helpful in finding exact character codes.
Entering simply '
(the character to the left of the return key on my US Mac keyboard) into their search yields several results of various curls and languages.
I would presume the original question was asking for the typographically correct U+02BC '
, rather than the typewriter fascimile U+0027 '
.
The W3C recommends hex codes for HTML entities (see below). For U+02BC that would be ʼ
, rather than '
for U+0027.
http://www.w3.org/International/questions/qa-escapes
Using character escapes in markup and CSS
Hex vs. decimal. Typically when the Unicode Standard refers to or lists characters it does so using a hexadecimal value. … Given the prevalence of this convention, it is often useful, though not required, to use hexadecimal numeric values in escapes rather than decimal values…
http://www.w3.org/TR/html4/charset.html
5 HTML Document Representation … 5.4 Undisplayable characters
…If missing characters are presented using their numeric representation, use the hexadecimal (not decimal) form, since this is the form used in character set standards.
The Anderson-Darling test is also be useful.
library(nortest)
ad.test(data)
In the Trace properties, click the Events Selection tab at the top next to General. Then click Column Filters... at the bottom right. You can then select what to filter, such as TextData
or DatabaseName
.
Expand the Like node and enter your filter with the percentage %
signs like %MyDatabaseName%
or %TextDataToFilter%
. Without the %%
signs the filter will not work.
Also, make sure to check the checkbox Exclude rows that do not contain values' If you cannot find the field you are looking to filter such as DatabaseName
go to the General tab and change your Template, blank one should contain all the fields.
For me, I needed to do the following:
1- Comment out bind 127.0.0.1
2- Change protected-mode
to no
3- Protect my server with iptables
(https://www.digitalocean.com/community/tutorials/how-to-implement-a-basic-firewall-template-with-iptables-on-ubuntu-14-04)
So if you want something unique to the device itself, TM.getDeviceId()
should be sufficient.
Here is the code which shows how to get Telephony manager ID. The android Device ID that you are using can change on factory settings and also some manufacturers have issue in giving unique id.
TelephonyManager tm =
(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String androidId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
Log.d("ID", "Android ID: " + androidId);
Log.d("ID", "Device ID : " + tm.getDeviceId());
Be sure to take permissions for TelephonyManager
by using
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
git checkout filename
git reset --hard
might do the trick as well
Nick Craver's answer needs to be slightly modified to work on iOS 6 Safari Mobile and should be:
$(window).scroll(function() {
if($(window).scrollTop() + window.innerHeight == $(document).height()) {
alert("bottom!");
}
});
Changing $(window).height() to window.innerHeight should be done because when the address bar is hidden an additional 60px are added to the window's height but using $(window).height()
does not reflect this change, while using window.innerHeight
does.
Note: The window.innerHeight
property also includes the horizontal scrollbar's height (if it is rendered), unlike $(window).height()
which will not include the horizontal scrollbar's height. This is not a problem in Mobile Safari, but could cause unexpected behavior in other browsers or future versions of Mobile Safari. Changing ==
to >=
could fix this for most common use cases.
Read more about the window.innerHeight
property here
Edit the pg_hba.conf file, e.g. with sudo emacs /etc/postgresql/9.3/main/pg_hba.conf
Change all authentication methods to trust
. Change Unix Password for "postgres" user. Restart Server. Login with psql -h localhost -U postgres
and use the just set Unix password. If it works you can re-set the pg_hba.conf file to the default values.
compile ("com.android.support:support-v4:22.2.0")
compile ("com.android.support:appcompat-v7:22.2.0")
compile ("com.android.support:support-annotations:22.2.0")
compile ("com.android.support:recyclerview-v7:22.2.0")
compile ("com.android.support:design:22.2.0")
paste the above code in your app gradle.
and while setting up the project select empty activity instead of blank activity.
Disjoint Set Forests allow fast membership queries and union operations and are most famously used in Kruskal's Algorithm for minimum spanning trees.
The really cool thing is that both operations have amortized running time proportional to the inverse of the Ackermann Function, making this the "fastest" non-constant time data structure.
You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.
For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.
There is a link to downloadable code at the end of the article. Hope that helps.
Look at the length of the string after replacing the sequence
declare @s varchar(10) = 'aabaacaa'
select len(@s) - len(replace(@s, 'a', ''))
>>6
To stop the pipeline of which ForEach-Object
is part just use the statement continue
inside the script block under ForEach-Object
. continue
behaves differently when you use it in foreach(...) {...}
and in ForEach-Object {...}
and this is why it's possible. If you want to carry on producing objects in the pipeline discarding some of the original objects, then the best way to do it is to filter out using Where-Object
.
You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.
<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>
or you can put the composition as a seperate function in js file and call it
const newFunction = R.compose(fn1,fn2,fn3);
<a href="#" onclick="newFunction()">Click me To fire some functions</a>
This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp()
and getClassName()
will work. You should also do something with the possible IOException
that can be thrown when using any of the java.io.*
classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id
is of type String
- I don't know as your code doesn't explicitly define it. If it is something else like an int
, you should probably cast it to a String
before using it in the fileName as I have done here.
Also, I replaced your append
calls with concat
or +
as I saw appropriate.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the /
in the filenames. For full portability, you should probably use something like File.separator to construct your paths.
Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir()
call will return true
if it created a directory, and false
if it didn't, including the case when the directory already existed.
I think this working CodePen example that I created will show you exactly how to do what you want.
The template:
<section ng-app="app" ng-controller="MainCtrl">
<span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</section>
The JavaScript code:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.orderByField = 'firstName';
$scope.reverseSort = false;
$scope.data = {
employees: [{
firstName: 'John',
lastName: 'Doe',
age: 30
},{
firstName: 'Frank',
lastName: 'Burns',
age: 54
},{
firstName: 'Sue',
lastName: 'Banter',
age: 21
}]
};
});
You use the same thing that is used for regular web. The console
command also works in this case. For example, you can use console.log()
, console.warn()
,
console.clear()
etc.
You can use Chrome Developer to use the console
command when you're logging while you are running your React Native app.
For those who are on SunOS which is non-GNU, the following code will help:
sed '1d' test.dat > tmp.dat
rows.RemoveAt(rows.Count - 1);
in Bootstrap 3 class="affix"
works, but in Bootstrap 4 it does not.
I solved this problem in Bootstrap 4 with class="sticky-top"
(using position: fixed
in CSS has its own problems)
code will be something like this:
<div class="row">
<div class="col-lg-3">
<div class="sticky-top">
Fixed content
</div>
</div>
<div class="col-lg-9">
Normal scrollable content
</div>
</div>
I have used in this way.. Working fine!
$inputs = request()->validate([
'name' => 'required | min:6 | max: 20',
'email' => 'required',
'password' => 'required| min:4| max:7 |confirmed',
'password_confirmation' => 'required| min:4'
]);
You can use methods from http://docs.python.org/2/library/msvcrt.html if you are on Windows.
import msvcrt
....
while True:
print "Doing a function"
if msvcrt.kbhit():
print "Key pressed: %s" % msvcrt.getch()
Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data
curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
// $output contains the output string
$output = curl_exec($ch);
$lines = explode("\n",$output);
$out = array();
$headers = true;
foreach ($lines as $l){
$l = trim($l);
if ($headers && !empty($l)){
if (strpos($l,'HTTP') !== false){
$p = explode(' ',$l);
$out['Headers']['Status'] = trim($p[1]);
} else {
$p = explode(':',$l);
$out['Headers'][$p[0]] = trim($p[1]);
}
} elseif (!empty($l)) {
$out['Data'] = $l;
}
if (empty($l)){
$headers = false;
}
}
Adminer (formerly phpMinAdmin), the web application for managing MySQL databases, draws simple diagram.
The software itself is similiar to phpMyAdmin, but has more features, its lightweight and it comes in single PHP file.
you put resource-ref in the description tag in web.xml
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
First off: My problem isn't the exact same as yours, but this post is the first thing that comes up in google for the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error at the time I wrote this. The solution may be useful to people searching for this error as I did not find this specific solution anywhere online.
In my case, I used Xampp/Apache and PHP sqlsrv to try to connect to an MSSQL database using Windows Authentication and received the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error you described. I finally found the problem to be the Apache service itself running under the user "LOCAL SERVICE" instead of the user account I was logged in as. In other words, it literally was using an anonymous account. The solution was to go into services.msc, right click the Apache service, go to Properties, go to the Log On tab, and enter the credentials for the user. This falls in line with your problem related to SPN's as your SPN's are set up to run from a specific user on the domain. So if the correct SPN is not running, windows authentication will default to the wrong user (likely the "LOCAL SERVICE" user) and give you the Anonymous error.
Here's where it's different from your problem. None of the computers on the local network are on a Domain, they are only on a Workgroup. To use Windows Authentication with a Workgroup, both the computer with the server (in my case MSSQL Server) and the computer with the service requesting data (in my case Apache) needed to have a user with an identical name and identical password.
To summarize, The Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error in both our cases seems to be caused by a service not running and/or not on the right user. Ensuring the right SPN or other Service is running and under the correct user should solve the anonymous part of the problem.
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Generally...
Hibernate is used for handling database operations. There is a rich set of database utility functionality, which reduces your number of lines of code. Especially you have to read @Annotation of hibernate. It is an ORM framework and persistence layer.
Spring provides a rich set of the Injection based working mechanism. Currently, Spring is well-known. You have to also read about Spring AOP. There is a bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.
Struts2 provides action based programming. There are a rich set of Struts tags. Struts prove action based programming so you have to maintain all the relevant control of your view.
In Addition, Tapestry is a different framework for Java. In which you have to handle only .tml
(template file). You have to create two main files for any class. One is JAVA class and another one is its template. Both names are same. Tapestry automatically calls related classes.
Java8
Stream.of(Direction.values()).forEach(System.out::println);
from Java5+
for ( Direction d: Direction.values()){
System.out.println(d);
}
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip() cut spaces in before and after string...
You can use the Series.to_list
method.
For example:
import pandas as pd
df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})
print(df['a'].to_list())
Output:
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
To drop duplicates you can do one of the following:
>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt
. Such termination functions may (though inevitably in the main thread!) call any stop
function you require; together with the possibility of setting a thread as daemon
, that gives you the tools to properly design the system functionality you need.
Go to File > Settings > Appearance & Behavior > Appearance > Show tool window bars
There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.
The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip
that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.
Unzipping is easier - just treat it as a directory.
In case the web pages are lost again, here are a few of the relevant code snippets:
Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
If Len(Dir(sPath)) > 0 Then Kill sPath
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub
Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
Split97 = Evaluate("{""" & _
Application.Substitute(sStr, sdelim, """,""") & """}")
End Function
Sub Zip_File_Or_Files()
Dim strDate As String, DefPath As String, sFName As String
Dim oApp As Object, iCtr As Long, I As Integer
Dim FName, vArr, FileNameZip
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
strDate = Format(Now, " dd-mmm-yy h-mm-ss")
FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"
'Browse to the file(s), use the Ctrl key to select more files
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True, Title:="Select the files you want to zip")
If IsArray(FName) = False Then
'do nothing
Else
'Create empty Zip File
NewZip (FileNameZip)
Set oApp = CreateObject("Shell.Application")
I = 0
For iCtr = LBound(FName) To UBound(FName)
vArr = Split97(FName(iCtr), "\")
sFName = vArr(UBound(vArr))
If bIsBookOpen(sFName) Then
MsgBox "You can't zip a file that is open!" & vbLf & _
"Please close it and try again: " & FName(iCtr)
Else
'Copy the file to the compressed folder
I = I + 1
oApp.Namespace(FileNameZip).CopyHere FName(iCtr)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.Namespace(FileNameZip).items.Count = I
Application.Wait (Now + TimeValue("0:00:01"))
Loop
On Error GoTo 0
End If
Next iCtr
MsgBox "You find the zipfile here: " & FileNameZip
End If
End Sub
Sub Unzip1()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create the folder name
strDate = Format(Now, " dd-mm-yy h-mm-ss")
FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
'If you want to extract only one file you can use this:
'oApp.Namespace(FileNameFolder).CopyHere _
'oApp.Namespace(Fname).items.Item("test.txt")
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
The general theory can be found in wikipedia's article on Kademlia. The specific protocol specification used in bittorrent is here: http://wiki.theory.org/BitTorrentDraftDHTProtocol
How are other people doing?
I am the only full-time dev at our company and have written 500,000 lines of OCaml and F# code over the past 7 years, which equates to about 200 lines of code per day. However, the vast majority of that code is tutorial examples consisting of hundreds of separate projects each a few hundred lines long. Also, there is a lot of duplication between the OCaml and the F#. We are not maintaining any in-house code bases larger than 50kLOC.
In addition to developing and maintaining our own software, I have also consulted for many clients in industry over the past 7 years. For the first client, I wrote 2,000 lines of OCaml over 3 months which is 20 lines of code per day. For the next client, four of us wrote a compiler that generated millions of lines of C/C++/Python/Java/OCaml code as well as documentation in 6 months which is 2,000 lines of code per day per developer. For another client, I replaced 50kLOC of C++ with 6kLOC of F# in 6 months which is -352 lines of code per day. For yet another client, I am rewriting 15kLOC of OCaml in F# which will be the same size so 0 lines of code per day.
For our current client, I will replace 1,600,000 lines of C++ and Mathematica code with ~160kLOC of F# in 1 year (by writing a bespoke compiler) which will be -6,000 lines of code per day. This will be my most successful project to date and will save our client millions of dollars a year in on-going costs. I think everyone should aim to write -6,000 lines of code per day.
There is a far easier solution (IMO) in Bootstrap 3 that does not require you to compile any custom LESS. You just have to leverage the cascade in "Cascading Style Sheets."
Set up your CSS loading like so...
<link type="text/css" rel="stylesheet" href="/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/css/custom.css" />
Where /css/custom.css
is your unique style definitions. Inside that file, add the following definition...
@media (min-width: 1200px) {
.container {
width: 970px;
}
}
This will override Bootstrap's default width: 1170px
setting when the viewport is 1200px or bigger.
Tested in Bootstrap 3.0.2
You better use Twitter Bootstrap which contains all of this nice stuff inside. Particularly here is exactly what you want.
In addition, you can use different themes built for Twitter Bootstrap from this website
There are no post/pre increment/decrement operators in python like in languages like C.
We can see ++
or --
as multiple signs getting multiplied, like we do in maths (-1) * (-1) = (+1).
E.g.
---count
Parses as
-(-(-count)))
Which translates to
-(+count)
Because, multiplication of -
sign with -
sign is +
And finally,
-count
Specifying the content type on the AJAX-call solved my problems on a Norwegian site.
$.ajax({
data: parameters,
type: "POST",
url: ajax_url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
dataType: 'json',
success: callback
});
You would also have to specify the charset on the server.
<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>
Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx
In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.
<form method="post" action="ServerFileToExecute.php">
<input type="submit" name="save" value="Click here to save" />
<input type="submit" name="delete" value="Click here to delete" />
</form>
The server side could look something like this if you use php:
<?php
if(isset($_POST['save']))
echo "Stored!";
else if(isset($_POST['delete']))
echo "Deleted!";
else
echo "Action is missing!";
?>
Try this:
Create A Macro with the following thing inside:
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.
This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.
Just put it inside a For loop statement to do it x number of times. like:
For i = 1 to 100 'Do this 100 times
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
Next i
Diagnose
Look up the following inside your script file
phpinfo();
If you can't find Soap Client
set to enabled
like so:
Fix
Do the following:
php.ini
in your apache bin folder, I.e Apache/bin/php.ini
;
from the beginning of extension=php_soap.dll
phpinfo();
again and check if you see a similar picture to the one aboveOn the other hand if this doesn't solve your issue, you may want to check the requirements for SOAP here. Also in the comment section you can find good advice on connecting to https.
// This works on Android Lollipop 5.0.2
public static boolean launchApp(Context context, String packageName) {
final PackageManager manager = context.getPackageManager();
final Intent appLauncherIntent = new Intent(Intent.ACTION_MAIN);
appLauncherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = manager.queryIntentActivities(appLauncherIntent, 0);
if ((null != resolveInfos) && (!resolveInfos.isEmpty())) {
for (ResolveInfo rInfo : resolveInfos) {
String className = rInfo.activityInfo.name.trim();
String targetPackageName = rInfo.activityInfo.packageName.trim();
Log.d("AppsLauncher", "Class Name = " + className + " Target Package Name = " + targetPackageName + " Package Name = " + packageName);
if (packageName.trim().equals(targetPackageName)) {
Intent intent = new Intent();
intent.setClassName(targetPackageName, className);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Log.d("AppsLauncher", "Launching Package '" + packageName + "' with Activity '" + className + "'");
return true;
}
}
}
return false;
}
You can run PHP as with any web-server, using the SPHP module for node.
It's compatible but not dependent on express.
It also supports websockets requests on the HTTP port.
Its biased for speed under small load, rather then saving resources.
To install in node:
npm install sphp
in you app:
var express = require('express');
var sphp = require('sphp');
var app = express();
var server = app.listen(8080);
app.use(sphp.express('public/'));
app.use(express.static('public/'));
For more information, look at https://github.com/paragi/sphp
I'm slightly biased too because I'm the author :)
If you still have problems with Eclipse finding your files, you might try the following:
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
Run following command
# ssh-add
If it gives following error: Could not open a connection to your authentication agent
To remove this error, Run following command:
# eval `ssh-agent`
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
try this, hope it will help you to get the current location, every time the location changes.
public class MyClass implements LocationListener {
double currentLatitude, currentLongitude;
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
}
Here a CSS animation fork of jezzipin's Solution, to seperate code from styling.
JS:
$(window).on("scroll touchmove", function () {
$('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0);
});
CSS:
.header {
width:100%;
height:100px;
background: #26b;
color: #fff;
position:fixed;
top:0;
left:0;
transition: height 500ms, background 500ms;
}
.header.tiny {
height:40px;
background: #aaa;
}
http://jsfiddle.net/sinky/S8Fnq/
On scroll/touchmove the css class "tiny" is set to "#header_nav" if "$(document).scrollTop()" is greater than 0.
CSS transition attribute animates the "height" and "background" attribute nicely.
Finally found the answer.
@using MyNamespace
For VB.Net:
@Imports Mynamespace
Take a look at @ravy amiry's answer if you want to include a namespace across the app.
The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.
git 2.7.1 (February 2016) clarifies that in commit b2c150d (05 Jan 2016) by David A. Wheeler (david-a-wheeler
).
(Merged by Junio C Hamano -- gitster
-- in commit 7aae9ba, 05 Feb 2016)
git commit
man page now includes:
-s::
--signoff::
Add
Signed-off-by
line by the committer at the end of the commit log message.
The meaning of a signoff depends on the project, but it typically certifies that committer has the rights to submit this work under the same license and agrees to a Developer Certificate of Origin (see https://developercertificate.org for more information).
Expand documentation describing
--signoff
Modify various document (man page) files to explain in more detail what
--signoff
means.This was inspired by "lwn article 'Bottomley: A modest proposal on the DCO'" (Developer Certificate of Origin) where paulj noted:
The issue I have with DCO is that there adding a "
-s
" argument to git commit doesn't really mean you have even heard of the DCO (thegit commit
man page makes no mention of the DCO anywhere), never mind actually seen it.So how can the presence of "
signed-off-by
" in any way imply the sender is agreeing to and committing to the DCO? Combined with fact I've seen replies on lists to patches without SOBs that say nothing more than "Resend this withsigned-off-by
so I can commit it".Extending git's documentation will make it easier to argue that developers understood
--signoff
when they use it.
Note that this signoff is now (for Git 2.15.x/2.16, Q1 2018) available for git pull
as well.
See commit 3a4d2c7 (12 Oct 2017) by W. Trevor King (wking
).
(Merged by Junio C Hamano -- gitster
-- in commit fb4cd88, 06 Nov 2017)
pull
: pass--signoff/--no-signoff
to "git merge
"merge can take
--signoff
, but without pull passing--signoff
down, it is inconvenient to use; allow 'pull
' to take the option and pass it through.
you can also overwrite bootstrap.css by simply removing "top:-25%;"
once removed, the modal will simply fade in and out without the slide animation.
Eclipse expects the declared package to match the directory hierarchy - so it's expecting your Java file to be in a directory called "Devices" under your source root. At the moment it looks like the file is directly in your source root. So create the appropriate directory, and move the file in there.
Note that conventionally, packages are in lower case and include your organization name in reverse DNS order, e.g.
com.foo.devices;
The method has been renamed to findById(…)
returning an Optional
so that you have to handle absence yourself:
Optional<Foo> result = repository.findById(…);
result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before
The compiler isn't smart enough to know that <
, >
, and ==
are a "complete set". You can let it know that by removing the condition "if(val == sorted[mid])" -- it's redundant. Jut say "else return mid;
"
You can use like this
let nsRange = NSRange(location: someInt, length: someInt)
as in
let myNSString = bigTOTPCode as NSString //12345678
let firstDigit = myNSString.substringWithRange(NSRange(location: 0, length: 1)) //1
let secondDigit = myNSString.substringWithRange(NSRange(location: 1, length: 1)) //2
let thirdDigit = myNSString.substringWithRange(NSRange(location: 2, length: 4)) //3456
// Step 1, update your constraint
self.myOutletToConstraint.constant = 50; // New height (for example)
// Step 2, trigger animation
[UIView animateWithDuration:2.0 animations:^{
// Step 3, call layoutIfNeeded on your animated view's parent
[self.view layoutIfNeeded];
}];
The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).
Now I'm settled with Fiddler (Inspectors > WebView)
This is probably what you want
var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);
var var2 = query.Get("var2");
Do not use the ToList()
method as in the accepted answer !
Running SQL profiler, I verified and found that ToList()
function gets all the records from the database. It is really bad performance !!
I would have run this query by pure sql command as follows:
string query = "Update YourTable Set ... Where ...";
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));
This would operate the update in one-shot without selecting even one row.
Here is an example of the working code.
template<typename T>
using toStringFn = decltype(std::declval<const T>().toString());
template <class T, toStringFn<T>* = nullptr>
std::string optionalToString(const T* obj, int)
{
return obj->toString();
}
template <class T>
std::string optionalToString(const T* obj, long)
{
return "toString not defined";
}
int main()
{
A* a;
B* b;
std::cout << optionalToString(a, 0) << std::endl; // This is A
std::cout << optionalToString(b, 0) << std::endl; // toString not defined
}
toStringFn<T>* = nullptr
will enable the function which takes extra int
argument which has a priority over function which takes long
when called with 0
.
You can use the same principle for the functions which returns true
if function is implemented.
template <typename T>
constexpr bool toStringExists(long)
{
return false;
}
template <typename T, toStringFn<T>* = nullptr>
constexpr bool toStringExists(int)
{
return true;
}
int main()
{
A* a;
B* b;
std::cout << toStringExists<A>(0) << std::endl; // true
std::cout << toStringExists<B>(0) << std::endl; // false
}
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
You do this using the modulus operator, %
n % k == 0
evaluates true if and only if n
is an exact multiple of k
. In elementary maths this is known as the remainder from a division.
In your current approach you perform a division and the result will be either
It's just the wrong way to go about testing divisibility.
I was looking for the same solution and Pawel gave me 99% of the answer. The only thing that was missing that I needed for the Extension to display was adding the following Razor Code into the cshtml(view) page:
@using programname.Models.Extensions
I was looking for the FirstName, to display in the top right of my NavBar after the user logged in.
I thought I would post this incase it helps someone else, So here is my code:
I created a new folder called Extensions(Under my Models Folder) and created the new class as Pawel specified above: IdentityExtensions.cs
using System.Security.Claims;
using System.Security.Principal;
namespace ProgramName.Models.Extensions
{
public static class IdentityExtensions
{
public static string GetUserFirstname(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
IdentityModels.cs
:
public class ApplicationUser : IdentityUser
{
//Extended Properties
public string FirstName { get; internal set; }
public string Surname { get; internal set; }
public bool isAuthorized { get; set; }
public bool isActive { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FirstName", this.FirstName));
return userIdentity;
}
}
Then in my _LoginPartial.cshtml
(Under Views/Shared
Folders) I added @using.ProgramName.Models.Extensions
I then added the change to the folling line of code that was going to use the Users First name after Logging in :
@Html.ActionLink("Hello " + User.Identity.GetUserFirstname() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
Perhaps this helps someone else down the line.
Unfortunately, np.polynomial.polynomial.polyfit
returns the coefficients in the opposite order of that for np.polyfit
and np.polyval
(or, as you used np.poly1d
). To illustrate:
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
0.65459882])
In [41]: np.polyfit(x, y, 4)
Out[41]:
array([ 0.65459882, -8.859311 , 44.83281407, -100.53595375,
84.29340846])
In general: np.polynomial.polynomial.polyfit
returns coefficients [A, B, C]
to A + Bx + Cx^2 + ...
, while np.polyfit
returns: ... + Ax^2 + Bx + C
.
So if you want to use this combination of functions, you must reverse the order of coefficients, as in:
ffit = np.polyval(coefs[::-1], x_new)
However, the documentation states clearly to avoid np.polyfit
, np.polyval
, and np.poly1d
, and instead to use only the new(er) package.
You're safest to use only the polynomial package:
import numpy.polynomial.polynomial as poly
coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)
Or, to create the polynomial function:
ffit = poly.Polynomial(coefs) # instead of np.poly1d
plt.plot(x_new, ffit(x_new))
If you control the back end, then use something like response.redirect
instead of response.send
.
You can create custom HTML pages for this or just redirect to something you already have.
In Express.js:
const handler = (req, res) => {
const { body } = req
handleResponse(body)
.then(data => {
console.log(data)
res.redirect('https://yoursite.com/ok.html')
})
.catch(err => {
console.log(err)
res.redirect('https://yoursite.com/err.html')
})
}
...
app.post('/endpoint', handler)
As of API 24, sending a file://
URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content://
URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION
flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
Download Spring STS (SpringSource Tool Suite) and choose Spring Template Project from the Dashboard. This is the easiest way to get a preconfigured spring mvc project, ready to go.
There is one interesting option in this scenario I haven`t found in answers here.
You can Nack messages with "requeue" feature in one consumer to process them in another. Generally speaking it is not a right way, but maybe it will be good enough for someone.
https://www.rabbitmq.com/nack.html
And beware of loops (when all concumers nack+requeue message)!
Jexecutable can create Windows exe for Java programs. It embeds the jars into exe file and you can run it like a Windows program.
This should remove the first element, and then you can return the remaining:
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
_x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
As others have suggested, you could also use slice(1);
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
_x000D_
alert(myarray.slice(1));
_x000D_
Probably best to change the className:
document.getElementById("button").className = 'button_color';
Then you add a buton style to the CSS where you can set the background color and anything else.
If you are trying to install matplotlib in order to work with graphs on python. Try this link. https://github.com/jbmohler/matplotlib-winbuild. This is a set of scripts to build matplotlib from source on the MS Windows platform.
To build & install matplotlib in your Python, do:
git clone https://github.com/matplotlib/matplotlib
git clone https://github.com/jbmohler/matplotlib-winbuild
$ python matplotlib-winbuild\buildall.py
The build script will auto-detect Python version & 32/64 bit automatically.
If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.
The only way I though of to do that was to create a temporary vector3
and pretend to do a set_intersection
by adding all elements of vector1
to it, then doing a search for each individual element of vector2
in vector3
and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.
Really, though, just sort them first.
I found a neat little hack to set the left padding for this exact situation.
Basically, you set the leftView property of the UITextField
to be an empty view of the size of the padding you want:
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
Worked like a charm for me!
In Swift 3/ Swift 4, it can be done by doing that
let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
textField.leftView = paddingView
textField.leftViewMode = .always
This can also help you by showing full details of the error on a client's browser.
<system.web>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
set environment variable
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_24
classpath=C:\Program Files\Java\jdk1.6.0_24\lib\tools.jar
path=C:\Program Files\Java\jdk1.6.0_24\bin
This error might be also for plugin versions. You can fix it in the .POM file like the followings:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
This worked for me:
step 1) Removing the interpreter, auto configuring it again
step 2) Window - Preferences - PyDev - Interpreters - Python Interpreter Go to the Forced builtins tab Click on New... Type the name of the module (curses in my case) and click OK
step 3) Right click in the project explorer on whichever module is giving errors. Go to PyDev->Code analysis.
One thing not mentioned in answers is inline element can break among lines while inline-block can't (and obviously block)! So inline elements can be useful to style sentences of text and blocks inside them, but as they can't be padded you can use line-height instead.
<div style="width: 350px">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
<div style="display: inline; background: #F00; color: #FFF">_x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<hr/>_x000D_
<div style="width: 350px">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
<div style="display: inline-block; background: #F00; color: #FFF">_x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>
_x000D_
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
The trick is to visit the original page using the 64-bit version of Internet Explorer. The site will then offer you the appropriate download options.
I personally like to do it this way:
<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">
I think this is better for two reasons:
As an alternative, I would suggest looking at your conda config file.
Reason
Sometimes for creating a virtual env at a specified location other than the pre-defined path at ~/anaconda3/envs
we append the conda config file using: conda config --append envs_dirs /path/to/envs
where envs_dirs
is a specified function in config file for allocating different paths where conda can find your virtual envs. Removing a recently added path in this config file may solve the problem.
Solution
$:> conda config --show envs_dirs
envs_dirs:
- /home/some_recent_path # remove this
- /home/.../anaconda3/envs
Note the value specifing a different directory other than the predefined location, and remove it using
$:> conda config --remove envs_dirs /home/some_recent_path
Now the config file envs_dirs
is set to default location of envs. Try creating a new env now.
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
In case the target page is on the same domain (i.e. shares the same origin with your page) and you don't mind creation of new tabs (1), you can (ab)use some JavaScript:
<a href="javascript:void(window.open('./target.html').onload=function(){this.document.querySelector('p:nth-child(10)').scrollIntoView()})">see tenth paragraph on another page</a>
Trivia:
var w = window.open('some URL of the same origin');
w.onload = function(){
// do whatever you want with `this.document`, like
this.document.querySelecotor('footer').scrollIntoView()
}
Working example of such 'exploit' you can try right now could be:
javascript:(function(url,sel,w,el){w=window.open(url);w.addEventListener('load',function(){w.setTimeout(function(){el=w.document.querySelector(sel);el.scrollIntoView();el.style.backgroundColor='red'},1000)})})('https://stackoverflow.com/questions/45014240/link-to-a-specific-spot-on-a-page-i-cant-edit','footer')
If you enter this into location bar (mind that Chrome removes javascript:
prefix when pasted from clipboard) or make it a href
value of any link on this page (using Developer Tools) and click it, you will get another (duplicate) SO question page scrolled to the footer and footer painted red. (Delay added as a workaround for ajax-loaded content pushing footer down after load.)
Notes
window.open(url,'_self')
seems to be breaking the load
event; basically makes the window.open
behave like a normal a href=""
click navigation; haven't researched more yet.Check you PATH environment variable once. Make sure the correct location of your JDK is specified there.
you can get filename by uri with simple way
fun get_filename_by_uri(uri : Uri) : String{
contentResolver.query(uri, null, null, null, null).use { cursor ->
cursor?.let {
val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
it.moveToFirst()
return it.getString(nameIndex)
}
}
return ""
}
and easy to read it by using
contentResolver.openInputStream(uri)
I found the easiest way is using str(timedelta)
. It will return a sting formatted like 3 days, 21:06:40.001000
, and you can parse hours and minutes using simple string operations or regular expression.
Not sure if there any disadvantages to this approach but even more minimal, in views.py:
entry = form.save()
# save uploaded file
if request.FILES['myfile']:
entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)
I experienced this when missing an export statement for the JSX class.
For example:
class MyComponent extends React.Component {
}
export default MyComponent // <- add me
I had the same problem. The bar had the same background color. Try:
android:scrollbarThumbVertical="@android:color/black"
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
You can use a BinaryWriter
object.
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
string Name = @"C:\temp\yourfile.name";
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.OpenWrite(Name));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
//...
return false;
}
return true;
}
Edit: Oops, forgot the finally
part... lets say it is left as an exercise for the reader ;-)
If you change the classes and load the content within the same function you should be fine.
$(document).ready(function(){
$('.nav li').click(function(event){
//remove all pre-existing active classes
$('.active').removeClass('active');
//add the active class to the link we clicked
$(this).addClass('active');
//Load the content
//e.g.
//load the page that the link was pointing to
//$('#content').load($(this).find(a).attr('href'));
event.preventDefault();
});
});
SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
Kill our own processes started from a common PPID is quite frequently, pkill associated to the –P
flag is a winner for me. Using @ghostdog74 example :
# sleep 30 &
[1] 68849
# sleep 30 &
[2] 68879
# sleep 30 &
[3] 68897
# sleep 30 &
[4] 68900
# pkill -P $$
[1] Terminated sleep 30
[2] Terminated sleep 30
[3]- Terminated sleep 30
[4]+ Terminated sleep 30
Mutability Difference:
String
is immutable, if you try to alter their values, another object gets created, whereas StringBuffer
and StringBuilder
are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer
and StringBuilder
is that StringBuffer
is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder
. StringBuilder
is more efficient than StringBuffer
.
Situations:
String
object is immutable.StringBuilder
is good enough.StringBuffer
because StringBuffer
is synchronous so you have thread-safety.You could use method
javax.crypto.Cipher.getMaxAllowedKeyLength(String transformation)
to test the available key length, use that and inform the user about what is going on. Something stating that your application is falling back to 128 bit keys due to the policy files not being installed, for example. Security conscious users will install the policy files, others will continue using weaker keys.
Let i have the following checkboxes
<input type="checkbox" name="vehicle" value="select All" id="chk_selall">Select ALL<br>
<input type="checkbox" name="vehicle" value="Bike" id="chk_byk">bike<br>
<input type="checkbox" name="vehicle" value="Car" id="chk_car">car
<input type="checkbox" name="vehicle" value="Bike" id="chk_bus">Bus<br>
<input type="checkbox" name="vehicle" value="scooty" id="chk_scooty">scooty
Here is the simple code to select all and diselect all when the selectall check box will click
<script type="text/javascript">
$(document).ready(function () {
$("#chk_selall").on("click", function () {
$("#chk_byk").prop("checked", true);
$("#chk_car").prop("checked", true);
$("#chk_bus").prop("checked", true);
$("#chk_scooty").prop("checked", true);
})
$("#chk_selall").on("click", function () {
if (!$(this).prop("checked"))
{
$("#chk_byk").prop("checked", false);
$("#chk_car").prop("checked", false);
$("#chk_bus").prop("checked", false);
$("#chk_scooty").prop("checked", false);
}
});
});
</script>
Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.
Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)
SQLAlchemy supports ON CONFLICT
now with two methods on_conflict_do_update()
and on_conflict_do_nothing()
:
Copying from the documentation:
from sqlalchemy.dialects.postgresql import insert
stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
index_elements=[my_table.c.user_email],
index_where=my_table.c.user_email.like('%@gmail.com'),
set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)
To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.
set "var=%cd%"
cd var
ipython notebook
public static void getSnapShot(WebDriver driver, String event) {
try {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
jpeg.setAlignment(Image.MIDDLE);
PdfPTable table = new PdfPTable(1);
PdfPCell cell1 = new PdfPCell(new Paragraph("\n"+event+"\n"));
PdfPCell cell2 = new PdfPCell(jpeg, false);
table.addCell(cell1);
table.addCell(cell2);
document.add(table);
document.add(new Phrase("\n\n"));
//document.add(new Phrase("\n\n" + event + "\n\n"));
//document.add(jpeg);
fileWriter.write("<pre> " + event + "</pre><br>");
fileWriter.write("<pre> " + Calendar.getInstance().getTime() + "</pre><br><br>");
fileWriter.write("<img src=\".\\img\\" + index + ".jpg\" height=\"460\" width=\"300\" align=\"middle\"><br><hr><br>");
++index;
}
catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
The trick is with the textView width, try to make it dedicated number like:
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"/>
I've tried many solutions without any result, I've tried:
android:ellipsize="none"
android:scrollHorizontally="false"
the only one thing triggred the wrap option is the dedicated width
One way is to use Kivy:
Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps.
Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.
Add this to your gradle.properties
file
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx2048M
Why dont you match the OK SYS row and not return it.
for item in output:
matchObj = re.search("(OK SYS|\\.).*", item)
if not matchObj:
print "got item " + item
Using routerLinkActive
is good in simple cases, when there is a link and you want to apply some classes. But in more complex cases where you may not have a routerLink or where you need something more you can create and use a pipe:
@Pipe({
name: "isRouteActive",
pure: false
})
export class IsRouteActivePipe implements PipeTransform {
constructor(private router: Router,
private activatedRoute: ActivatedRoute) {
}
transform(route: any[], options?: { queryParams?: any[], fragment?: any, exact?: boolean }) {
if (!options) options = {};
if (options.exact === undefined) options.exact = true;
const currentUrlTree = this.router.parseUrl(this.router.url);
const urlTree = this.router.createUrlTree(route, {
relativeTo: this.activatedRoute,
queryParams: options.queryParams,
fragment: options.fragment
});
return containsTree(currentUrlTree, urlTree, options.exact);
}
}
then:
<div *ngIf="['/some-route'] | isRouteActive">...</div>
and don't forget to include pipe in the pipes dependencies ;)
How do you express binary literals in Python?
They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a 0
followed by a B
or b
followed by a series of zeros and ones, for example:
>>> 0b0010101010
170
>>> 0B010101
21
From the Python 3 docs, these are the ways of providing integer literals in Python:
Integer literals are described by the following lexical definitions:
integer ::= decinteger | bininteger | octinteger | hexinteger decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")* bininteger ::= "0" ("b" | "B") (["_"] bindigit)+ octinteger ::= "0" ("o" | "O") (["_"] octdigit)+ hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+ nonzerodigit ::= "1"..."9" digit ::= "0"..."9" bindigit ::= "0" | "1" octdigit ::= "0"..."7" hexdigit ::= digit | "a"..."f" | "A"..."F"
There is no limit for the length of integer literals apart from what can be stored in available memory.
Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.
Some examples of integer literals:
7 2147483647 0o177 0b100110111 3 79228162514264337593543950336 0o377 0xdeadbeef 100_000_000_000 0b_1110_0101
Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.
You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):
>>> int('010101', 2)
21
You can optionally have the 0b
or 0B
prefix:
>>> int('0b0010101010', 2)
170
If you pass it 0
as the base, it will assume base 10 if the string doesn't specify with a prefix:
>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21
You can pass an integer to bin to see the string representation of a binary literal:
>>> bin(21)
'0b10101'
And you can combine bin
and int
to go back and forth:
>>> bin(int('010101', 2))
'0b10101'
You can use a format specification as well, if you want to have minimum width with preceding zeros:
>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'
Just as I was thinking that it would be fun to write a streaming JSON parser, I also thought that maybe I should do a quick search to see if there's one already available.
Turns out there is.
Since I just found it, I've obviously not used it, so I can't comment on its quality, but I'll be interested to hear if it works.
It does work consider the following Javascript and _.isString
:
stream.pipe(JSONStream.parse('*'))
.on('data', (d) => {
console.log(typeof d);
console.log("isString: " + _.isString(d))
});
This will log objects as they come in if the stream is an array of objects. Therefore the only thing being buffered is one object at a time.
The question asked specifically on shell script
and the question tag mentioning only about sendmail
package. So, if someone is looking for this, here is the simple script with sendmail usage that is working for me on CentOS 8:
#!/bin/sh
TOEMAIL="[email protected]"
REPORT_FILE_HTML="$REPORT_FILE.html"
echo "Subject: EMAIL SUBJECT" >> "${REPORT_FILE_HTML}"
echo "MIME-Version: 1.0" >> "${REPORT_FILE_HTML}"
echo "Content-Type: text/html" >> "${REPORT_FILE_HTML}"
echo "<html>" >> "${REPORT_FILE_HTML}"
echo "<head>" >> "${REPORT_FILE_HTML}"
echo "<title>Best practice to include title to view online email</title>" >> "${REPORT_FILE_HTML}"
echo "</head>" >> "${REPORT_FILE_HTML}"
echo "<body>" >> "${REPORT_FILE_HTML}"
echo "<p>Hello there, you can put email html body here</p>" >> "${REPORT_FILE_HTML}"
echo "</body>" >> "${REPORT_FILE_HTML}"
echo "</html>" >> "${REPORT_FILE_HTML}"
sendmail $TOEMAIL < $REPORT_FILE_HTML
In short:
Install WAMP
Put this file to C:\wamp\www\ProjectName\filename.php
Go to browser: http://localhost/ProjectName/filename.php
A starter bash script to list and run a tool against the DBs...
#!/bin/bash
declare -a dbs
unset opt
for each in $(echo "show databases;" | mysql -u root) ;do
dbs+=($each)
done
echo " The system found [ ${#dbs[@]} ] databases." ;sleep 2
echo
echo "press 1 to run a check"
echo "press 2 to run an optimization"
echo "press 3 to run a repair"
echo "press 4 to run check,repair, and optimization"
echo "press q to quit"
read input
case $input in
1) opt="-c"
;;
2) opt="-o"
;;
3) opt="-r"
;;
4) opt="--auto-repair -c -o"
;;
*) echo "Quitting Application .."; exit 7
;;
esac
[[ -z $opt ]] && exit 7;
echo " running option: mysqlcheck $opt in 5 seconds on all Dbs... "; sleep 5
for ((i=0; i<${#dbs[@]}; i++)) ;do
echo "${dbs[$i]} : "
mysqlcheck $opt ${dbs[$i]} -u root
done
I did install git and tried again and got the same error. But running 'npm install' in a new command prompt window worked for me. Restarting the machine is not required.
This post asked a similar question and used LINQ to solve it, maybe it will help you out too.
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
Something like this:
var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
Above code will sort your unordered list with id 'myUL'.
OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort
Apart from a database, you can also have following options to save user related settings
registry under HKEY_CURRENT_USER
in a file in AppData
folder
using Settings
file in WPF and by setting its scope as User
Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
Not looking for rep--I just researched this question myself and thought I'd share.
Assuming a modern release, find -newermt
is powerful:
find -newermt '10 minutes ago' ## other units work too, see `Date input formats`
or, if you want to specify a time_t
(seconds since epoch):
find -newermt @1568670245
For reference, -newermt
is not directly listed in the man page for find. Instead, it is shown as -newerXY
, where XY
are placeholders for mt
. Other replacements are legal, but not applicable for this solution.
From man find -newerXY
:
Time specifications are interpreted as for the argument to the -d option of GNU date.
So the following are equivalent to the initial example:
find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'
The date -d
(and find -newermt
) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
If it suits anyone, here are some brief guidelines for adding environment variables permanently.
vi ~/.bash_profile
Add the variables to the file:
export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11
Immediately apply all changes:
source ~/.bash_profile
For Kibana 4 go to this answer
This is easy to do with a terms panel:
If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip
, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:
You cannot identify the (hardware) version of an iPhone by user agent.
It's only possible to recognize that it's an iPhone and which software versions it's running.
Using the Safari User Agent String
Not even WURLF can.
You could use the following snippet:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
{
MessageBox.Show("This textbox accepts only alphabetical characters");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Here's my solution based on the OP's suggestion, and the examples given by everyone else. Since most everyone was looking for it to handle negative numbers, this solution does just that, without the use of any special functions, i.e. abs, and the like.
By avoiding the modulus and using division instead, the negative number is a natural result, although it's rounded down. After the rounded down version is calculated, then it does the required math to round up, either in the negative or positive direction.
Also note that no special functions are used to calculate anything, so there is a small speed boost there.
int RoundUp(int n, int multiple)
{
// prevent divide by 0 by returning n
if (multiple == 0) return n;
// calculate the rounded down version
int roundedDown = n / multiple * multiple;
// if the rounded version and original are the same, then return the original
if (roundedDown == n) return n;
// handle negative number and round up according to the sign
// NOTE: if n is < 0 then subtract the multiple, otherwise add it
return (n < 0) ? roundedDown - multiple : roundedDown + multiple;
}
Faced the same problem as OP:
Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.
What you probably want is for...of
, a relatively new construct built for the express purpose of enumerating the values of iterable objects:
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
console.log(item);_x000D_
}
_x000D_
... as distinct from for...in
, which enumerates property names (presumably1 numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:
let myArray = ["a","b","c","d"];_x000D_
for (let key in myArray) {_x000D_
let value = myArray[key]; // get the value by key_x000D_
console.log("key: %o, value: %o", key, value);_x000D_
}
_x000D_
1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0
to array.length - 1
rather than using for...in
.
So, this is not (as I'd originally thought) an academic question, i.e.:
Without regard for practicality, is it possible to avoid
length
when iterating over an array?
According to your comment (emphasis mine):
[...] why do I need to calculate the size of an array whereas the interpreter can know it.
You have a misguided aversion to Array.length
. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):
Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.
You can save generated diagram for future use.
Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:
$scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'}, {category:'freshwater', id:'2', name:'bass', more:'false'}];
And this is your function:
$scope.showdetails = function(fish_id){
var found = $scope.fishes.filter({id : fish_id});
return found;
};
You can also use expression:
$scope.showdetails = function(fish_id){
var found = $scope.fishes.filter(function(fish){ return fish.id === fish_id });
return found;
};
More about this function: LINK
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
You can use \D
which means non digits.
var removedText = self.val().replace(/\D+/g, '');
You could also use the HTML5 number input.
<input type="number" name="digit" />
You can also try another library - https://github.com/wikimedia/jquery.i18n .
In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.
This error happens when you have a ViewBag Non-Existent in your razor code calling a method.
Controller
public ActionResult Accept(int id)
{
return View();
}
razor:
<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>
For some reason, the .net aren't able to show the error in the correct line.
Normally this causes a lot of wasted time.
If you are willing to part with some money, JNIWrapper is a useful library with a Winpack, you will be able to get file system events on certain files. Unfortunately windows only.
See https://www.teamdev.com/jniwrapper.
Otherwise, resorting to native code is not always a bad thing especially when the best on offer is a polling mechanism as against a native event.
I've noticed that Java file system operations can be slow on some computers and can easily affect the application's performance if not handled well.
You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a CI server
<dependency>
<groupId>com.stackoverflow</groupId>
<artifactId>commons-utils</artifactId>
<version>1.3</version>
<scope>system</scope>
<systemPath>${basedir}/lib/commons-utils.jar</systemPath>
</dependency>
Two alternative strategies to get consistent about line-endings in mixed environments (Microsoft + Linux + Mac):
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) Set core.autocrlf
to input
on Linux/UNIX or true
on MS Windows (repository or global)
git config --global core.autocrlf input
3) [ Optional ] set core.safecrlf
to true
(to stop) or warn
(to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file
git config --global core.safecrlf true
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) add .gitattributes
file to your repository
echo "* text=auto" > .gitattributes
git add .gitattributes
git commit -m 'adding .gitattributes for unified line-ending'
Don't worry about your binary files - Git should be smart enough about them.
Even after changing the compiler compliance setting to 1.6 or 1.7 from windows tab, then prefernces, then java, then compiler and setting the compiler compliance, I was still having this issue. The idea is that we need to go the the project folder, right click, Java and set compiler compliance to 1.6 or higer. This worked for me.
From the UIExplorer sample app:
Static assets should be required by prefixing with
image!
and are located in the app bundle.
So like this:
render: function() {
return (
<View style={styles.horizontal}>
<Image source={require('image!uie_thumb_normal')} style={styles.icon} />
<Image source={require('image!uie_thumb_selected')} style={styles.icon} />
<Image source={require('image!uie_comment_normal')} style={styles.icon} />
<Image source={require('image!uie_comment_highlighted')} style={styles.icon} />
</View>
);
}
This is not a direct answer to OP's question, this is more of the stuffs (experiments) I tried so far to solve the same problem and obtained some results and have some observations that I want to share, I am curious if we can have some further insights from this.
I just tried my minimax implementation with alpha-beta pruning with search-tree depth cutoff at 3 and 5. I was trying to solve the same problem for a 4x4 grid as a project assignment for the edX course ColumbiaX: CSMM.101x Artificial Intelligence (AI).
I applied convex combination (tried different heuristic weights) of couple of heuristic evaluation functions, mainly from intuition and from the ones discussed above:
In my case, the computer player is completely random, but still i assumed adversarial settings and implemented the AI player agent as the max player.
I have 4x4 grid for playing the game.
If I assign too much weights to the first heuristic function or the second heuristic function, both the cases the scores the AI player gets are low. I played with many possible weight assignments to the heuristic functions and take a convex combination, but very rarely the AI player is able to score 2048. Most of the times it either stops at 1024 or 512.
I also tried the corner heuristic, but for some reason it makes the results worse, any intuition why?
Also, I tried to increase the search depth cut-off from 3 to 5 (I can't increase it more since searching that space exceeds allowed time even with pruning) and added one more heuristic that looks at the values of adjacent tiles and gives more points if they are merge-able, but still I am not able to get 2048.
I think it will be better to use Expectimax instead of minimax, but still I want to solve this problem with minimax only and obtain high scores such as 2048 or 4096. I am not sure whether I am missing anything.
Below animation shows the last few steps of the game played by the AI agent with the computer player:
Any insights will be really very helpful, thanks in advance. (This is the link of my blog post for the article: https://sandipanweb.wordpress.com/2017/03/06/using-minimax-with-alpha-beta-pruning-and-heuristic-evaluation-to-solve-2048-game-with-computer/ and the youtube video: https://www.youtube.com/watch?v=VnVFilfZ0r4)
The following animation shows the last few steps of the game played where the AI player agent could get 2048 scores, this time adding the absolute value heuristic too:
The following figures show the game tree explored by the player AI agent assuming the computer as adversary for just a single step:
The simplest way is,
C:\data\db
C:\data\db\log.txt
Open command prompt as "Run as Administrator" and make sure the mogodb bin directory path is correct and write
C:\Program Files\MongoDB\Server\3.4\bin> mongod.exe --install mongod --dbpath="c:\data\db" --logpath="c:\data\db\log.txt"
Start mongodb service:
net run MongoDB
You need to set index=False
in to_excel
in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html
I found this query which helped me find my locked table and query causing the issue.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
tar -cf my_archive `find ./ | grep '.php\|.html'`
Use "find" and "grep" to get all path of .php and .html files in all directory and its sub-directories. Then pass those path information to tar to compress.
Please be careful with those symbol ` and '. Note also that this will hit the limit of how many characters your shell will allow on the command line, unlike some of the other answers.
On OpenWRT the only way to reliably do this, at least for me, is by running these commands:
# Get switch name
swconfig list
# assuming switch name is "switch0"
swconfig dev switch0 show | grep link:
# Possible output
root@OpenWrt:~# swconfig dev switch0 show | grep link:
link: port:0 link:up speed:1000baseT full-duplex txflow rxflow
link: port:1 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
link: port:2 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
link: port:3 link:down
link: port:4 link:up speed:1000baseT full-duplex eee100 eee1000 auto
link: port:5 link:down
link: port:6 link:up speed:1000baseT full-duplex txflow rxflow
This will show either "link:down" or "link:up" on every port of your switch.
// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention
function submit()
{
var userPass = document.getElementById("pass").value;
var userName = document.getElementById("user").value;
this.pass = userPass;
this.name = userName;
alert("whatever you want to display");
}
I would suggest checking the drivers and updating them if required.
This is a bug. Currently you either have to set a timeStyle
as well or use one of the alternatives described in the other answers.
Tools -> options -> git and selecting 'use system git' did the magic for me.
Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%"
- but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.
It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.
To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%"
.
Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.
I say that doing a WHERE field LIKE "%value%"
is slower than WHERE field LIKE "value%"
if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:
1/ If you do SELECT field FROM table WHERE field LIKE "%value%"
, MySQL will scan the entire table, and only send the fields containing "value".
2/ If you do SELECT field FROM table
and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.
Solution: Please do use the WHERE
clause, and use EXPLAIN
to see the performance.
The SqlDataReader
is a valid data source for the DataTable
. As such, all you need to do its this:
public DataTable GetData()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne]";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
}
Actually, there are two foreign_key_checks
variables: a global variable and a local (per session) variable. Upon connection, the session variable is initialized to the value of the global variable.
The command SET foreign_key_checks
modifies the session variable.
To modify the global variable, use SET GLOBAL foreign_key_checks
or SET @@global.foreign_key_checks
.
Consult the following manual sections:
http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html
I found this plain JavaScript code very handy!
#<script type="text/javascript">
function toggle_visibility(id)
{
var e = document.getElementById(id);
if ( e.style.display == 'block' )
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
I read a lot of answers but none seems to correctly explain where the word double comes from. I remember a very good explanation given by a University professor I had some years ago.
Recalling the style of VonC's answer, a single precision floating point representation uses a word of 32 bit.
Representation:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
bits: 31 30 23 22 0
(Just to point out, the sign bit is the last, not the first.)
A double precision floating point representation uses a word of 64 bit.
Representation:
S EEEEEEEEEEE MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
bits: 63 62 52 51 0
As you may notice, I wrote that the mantissa has, in both types, one bit more of information compared to its representation. In fact, the mantissa is a number represented without all its non-significative 0
. For example,
This means that the mantissa will always be in the form
0.a1a2...at × ßp
where ß is the base of representation. But since the fraction is a binary number, a1 will always be equal to 1, thus the fraction can be rewritten as 1.a2a3...at+1 × 2p and the initial 1 can be implicitly assumed, making room for an extra bit (at+1).
Now, it's obviously true that the double of 32 is 64, but that's not where the word comes from.
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
With that said, it's easy to estimate the number of decimal digits which can be safely used:
You need to use the method equals()
when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:
if (!statusCheck.equals("success")) {
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
itemgetter
(see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get
wins. And it does not require an extra import
.
>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
... k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Note that alternatively you can set d.__getitem__
as key
function which may provide a small performance boost over d.get
.
You need to READ ALL data from input, before send another command!
And you can't ask to READ if no data is avaliable... little bit suck isn't?
My solutions... when ask to read... ask to read a big buffer... like 1 MEGA...
And you will need wait a min 100 milliseconds... sample code...
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("cmd.exe", "")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oStartInfo.RedirectStandardInput = True
oStartInfo.CreateNoWindow = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim Response As String = String.Empty
Dim BuffSize As Integer = 1024 * 1024
Dim x As Char() = New Char(BuffSize - 1) {}
Dim bytesRead As Integer = 0
oProcess.StandardInput.WriteLine("dir")
Threading.Thread.Sleep(100)
bytesRead = oProcess.StandardOutput.Read(x, 0, BuffSize)
Response = String.Concat(Response, String.Join("", x).Substring(0, bytesRead))
MsgBox(Response)
Response = String.Empty
oProcess.StandardInput.WriteLine("dir c:\")
Threading.Thread.Sleep(100)
bytesRead = 0
bytesRead = oProcess.StandardOutput.Read(x, 0, BuffSize)
Response = String.Concat(Response, String.Join("", x).Substring(0, bytesRead))
MsgBox(Response)
End Sub
End Class
return
should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.
print
should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.
The following code shows how to use return
and print
properly:
def fact(x):
if x < 2:
return 1
return x * fact(x - 1)
print(fact(5))
This explanation is true for all of the programming languages not just python.
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));
String content;
while ((content = in.readLine()) != null)
System.out.println(content);
If an element has multiples classes "[class^='apple-']" dosen't work, e.g.
<div class="fruits apple-monkey"></div>
public static void GetSection()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];
}
The correct way of using post variables is
<?php
$department = $_POST['department'];
?>
Use single quotation(')
First I thank you. # 57ar7up and I will add the following code it helps in finding the return phone number.
function index(){
// $keyword = "0946664869";
$sql = "SELECT * FROM phone_find LIMIT 10";
$result = $this->GlobalMD->query_global($sql);
$fb = array();
foreach($result as $value){
$keyword = $value['phone'];
$fb[] = $this->facebook_search($keyword);
}
var_dump($fb);
}
function facebook_search($query, $type = 'all'){
$url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
$user_agent = $this->loaduserAgent();
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE
));
$data = curl_exec($c);
preg_match('/\{"id":(?P<fbUserId>\d+)\,/', $data, $matches);
if(isset($matches["fbUserId"]) && $matches["fbUserId"] != ""){
$fbUserId = $matches["fbUserId"];
$params = array($query,$fbUserId);
}else{
$fbUserId = "";
$params = array($query,$fbUserId);
}
return $params;
}