Eventually found the FontForge Windows installer package and opened the PDF through the installed program. Worked a treat, so happy.
I don't have an 11g instance available today but could you not use:
SELECT group_id,
LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
FROM (
SELECT UNIQUE
group_id,
name
FROM demotable
)
GROUP BY group_id
To unapply a specific migration(s):
dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName
To unapply all migrations:
dotnet ef database update 0
or
PM> Update-Database -Migration 0
To remove last migration:
dotnet ef migrations remove
or
PM> Remove-Migration
To remove all migrations:
just remove Migrations
folder.
To remove last few migrations (not all):
There is no a command to remove a bunch of migrations and we can't just remove these few migrations
and their *.designer.cs
files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration
above).
To unapply and remove last migration:
dotnet ef migrations remove --force
or
PM> Remove-Migration -Force
Here is a Plunk that does what you want: http://plnkr.co/edit/TTlbSv?p=preview
The idea is that you work with promises directly and their "then" functions to manipulate and access the asynchronously returned responses.
app.factory('myService', function($http) {
var myService = {
async: function() {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('test.json').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return myService;
});
app.controller('MainCtrl', function( myService,$scope) {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
});
Here is a slightly more complicated version that caches the request so you only make it first time (http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview):
app.factory('myService', function($http) {
var promise;
var myService = {
async: function() {
if ( !promise ) {
// $http returns a promise, which has a then function, which also returns a promise
promise = $http.get('test.json').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
}
// Return the promise to the controller
return promise;
}
};
return myService;
});
app.controller('MainCtrl', function( myService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
// Call the async method and then do stuff with what is returned inside our own then function
myService.async().then(function(d) {
$scope.data = d;
});
};
});
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
I have just come across this from Common Crawl.
Might be the answer we are all looking for!!
Using NLTK:
from nltk.corpus import wordnet
if not wordnet.synsets(word_to_test):
#Not an English Word
else:
#English Word
You should refer to this article if you have trouble installing wordnet or want to try other approaches.
I use this to import bootstrap.css in altervista with wordpress
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css");
and it works fine, as it would delete the html link rel code if I put it into a page
As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:
<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 26 42"
width="26px" height="42px">
if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.
(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)
A simpler but equally effective option would be:
+ theme_bw(base_size=X)
I had same problem. Try the following command. This solved my problem.
sudo apt-get install libapache2-mod-php5
// My Enumeration Class
class Enum
{
protected $m_actions = array();
public function __construct($actions)
{
$this->init($actions);
}
public function init($actions)
{
$this->m_actions = array();
for($i = 0; $i < count($actions); ++$i)
{
$this->m_actions[$actions[$i]] = ($i + 1);
define($actions[$i], ($i + 1));
}
}
public function toString($index)
{
$keys = array_keys($this->m_actions);
for($i = 0; $i < count($keys); ++$i)
{
if($this->m_actions[$keys[$i]] == $index)
{
return $keys[$i];
}
}
return "undefined";
}
public function fromString($str)
{
return $this->m_actions[$str];
}
}
// Enumeration creation
$actions = new Enum(array("CREATE", "READ", "UPDATE", "DELETE"));
// Examples
print($action_objects->toString(DELETE));
print($action_objects->fromString("DELETE"));
if($action_objects->fromString($_POST["myAction"]) == CREATE)
{
print("CREATE");
}
WITH CHECK
is indeed the default behaviour however it is good practice to include within your coding.
The alternative behaviour is of course to use WITH NOCHECK
, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.
var third = first.Except(second);
(you can also call ToList()
after Except()
, if you don't like referencing lazy collections.)
The Except()
method compares the values using the default comparer, if the values being compared are of base data types, such as int
, string
, decimal
etc.
Otherwise the comparison will be made by object address, which is probably not what you want... In that case, make your custom objects implement IComparable
(or implement a custom IEqualityComparer
and pass it to the Except()
method).
Here's how I get it to beep using HTML5: First I copy and convert the windows wav file to mp3, then I use this code:
var _beep = window.Audio("Content/Custom/Beep.mp3")
function playBeep() { _beep.play()};
It's faster to declare the sound file globally and refer to it as needed.
local function CountedTable(x)
assert(type(x) == 'table', 'bad parameter #1: must be table')
local new_t = {}
local mt = {}
-- `all` will represent the number of both
local all = 0
for k, v in pairs(x) do
all = all + 1
end
mt.__newindex = function(t, k, v)
if v == nil then
if rawget(x, k) ~= nil then
all = all - 1
end
else
if rawget(x, k) == nil then
all = all + 1
end
end
rawset(x, k, v)
end
mt.__index = function(t, k)
if k == 'totalCount' then return all
else return rawget(x, k) end
end
return setmetatable(new_t, mt)
end
local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }
assert(bar.totalCount == 4)
assert(bar.x == 23)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = 24
bar.x = 25
assert(bar.x == 25)
assert(bar.totalCount == 4)
nobody has mentioned yet, in ASP.NET 4.0 there's new syntax to do this. instead of
<%= HttpUtility.HtmlEncode(unencoded) %>
you can simply do
<%: unencoded %>
read more here: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx
Use the attr
method on your lookup. You can switch out any attribute with a new value.
$("a.mylink").attr("href", "http://cupcream.com");
@Ned Batchelder and @newacct provided the right answer, but ...
Just in case if you have comma(,) decimal(.) in your string:
import re
re.sub("[^\d\.]", "", "$1,999,888.77")
'1999888.77'
I know I'm a little late, but something I found that works (and doesn't require using csv
) is to write a for loop that writes to your file for every element in your list.
# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']
# Open File
resultFyle = open("output.csv",'w')
# Write data to file
for r in RESULTS:
resultFyle.write(r + "\n")
resultFyle.close()
I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.
If you don't have avahi installed then it's probably cups.
Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.
This isn't something you should rely on however. It's recommended you always use the correct MIME content.
PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
or not putting any arguments on the starting line, then indenting to a uniform level:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.
CTRL-W >
and
CTRL-W <
to make the window wider or narrower.
If you give default values to all the fields - empty constructor is generated automatically by Kotlin.
data class User(var id: Long = -1,
var uniqueIdentifier: String? = null)
and you can simply call:
val user = User()
The "loginVo.htmlBody(messageBodyPart);" will contain the html formatted designed information, but in mail does not receive it.
JAVA - STRUTS2
package com.action;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.opensymphony.xwork2.Action;
import com.bo.LoginBo;
import com.manager.AttendanceManager;
import com.manager.LoginManager;
import com.manager.SSLEmail;
import com.vo.AttendanceManagementVo;
import com.vo.LeaveManagementVo;
import com.vo.LoginVo;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;
public class InsertApplyLeaveAction implements Action {
private AttendanceManagementVo attendanceManagementVo;
public AttendanceManagementVo getAttendanceManagementVo() {
return attendanceManagementVo;
}
public void setAttendanceManagementVo(
AttendanceManagementVo attendanceManagementVo) {
this.attendanceManagementVo = attendanceManagementVo;
}
@Override
public String execute() throws Exception {
String empId=attendanceManagementVo.getEmpId();
String leaveType=attendanceManagementVo.getLeaveType();
String leaveStartDate=attendanceManagementVo.getLeaveStartDate();
String leaveEndDate=attendanceManagementVo.getLeaveEndDate();
String reason=attendanceManagementVo.getReason();
String employeeName=attendanceManagementVo.getEmployeeName();
String manageEmployeeId=empId;
float totalLeave=attendanceManagementVo.getTotalLeave();
String leaveStatus=attendanceManagementVo.getLeaveStatus();
// String approverId=attendanceManagementVo.getApproverId();
attendanceManagementVo.setEmpId(empId);
attendanceManagementVo.setLeaveType(leaveType);
attendanceManagementVo.setLeaveStartDate(leaveStartDate);
attendanceManagementVo.setLeaveEndDate(leaveEndDate);
attendanceManagementVo.setReason(reason);
attendanceManagementVo.setManageEmployeeId(manageEmployeeId);
attendanceManagementVo.setTotalLeave(totalLeave);
attendanceManagementVo.setLeaveStatus(leaveStatus);
attendanceManagementVo.setEmployeeName(employeeName);
AttendanceManagementVo attendanceManagementVo1=new AttendanceManagementVo();
AttendanceManager attendanceManager=new AttendanceManager();
attendanceManagementVo1=attendanceManager.insertLeaveData(attendanceManagementVo);
attendanceManagementVo1=attendanceManager.getApproverId(attendanceManagementVo);
String approverId=attendanceManagementVo1.getApproverId();
String approverEmployeeName=attendanceManagementVo1.getApproverEmployeeName();
LoginVo loginVo=new LoginVo();
LoginManager loginManager=new LoginManager();
loginVo.setEmpId(approverId);
loginVo=loginManager.getEmailAddress(loginVo);
String emailAddress=loginVo.getEmailAddress();
String subject="LEAVE IS SUBMITTED FOR AN APPROVAL BY THE - " +employeeName;
// String body = "Hi "+approverEmployeeName+" ," + "\n" + "\n" +
// leaveType+" is Applied for "+totalLeave+" days by the " +employeeName+ "\n" + "\n" +
// " Employee Name: " + employeeName +"\n" +
// " Applied Leave Type: " + leaveType +"\n" +
// " Total Days: " + totalLeave +"\n" + "\n" +
// " To view Leave History, Please visit the employee poratal or copy and paste the below link in your browser: " + "\n" +
// " NOTE : This is an automated message. Please do not reply."+ "\n" + "\n" +
Session session = null;
MimeBodyPart messageBodyPart = new MimeBodyPart();
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
String htmlText = ("<div style=\"color:red;\">BRIDGEYE</div>");
messageBodyPart.setContent(htmlText, "text/html");
loginVo.setHtmlBody(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
loginVo.setSubject(subject);
// loginVo.setBody(body);
loginVo.setEmailAddress(emailAddress);
SSLEmail sSSEmail=new SSLEmail();
sSSEmail.sendEmail(loginVo);
return "success";
}
}
You can grant system privileges with or without the admin option. The default being without admin option.
GRANT CREATE SESSION TO username
or with admin option:
GRANT CREATE SESSION TO username WITH ADMIN OPTION
The Grantee with the ADMIN OPTION
can grant and revoke privileges to other users
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
As others have suggested, you can set the username and password directly in the Ajax call:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
OR use the headers property if you would rather not store your credentials in plain text:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195
. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value)
constructor, e.g.:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0)
step in the accepted answer because the JavaScript Date(value)
constructor takes a UTC value in milliseconds (not a local time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...)
constructor that takes a string datetime representation, this is not recommended (see the link above).
You need to call CLASS in button
<button class="tim" id="rock" onClick="choose(1)">Rock</button>
<style>
.tim{
font-size: 18px;
border: 2px solid #AD235E;
border-radius: 100px;
width: 150px;
height: 150px; background-image: url(images/Sun.jpg);
}
</style>
Other possible way is:
echo "text" | tee -a filename >/dev/null
The -a
will append at the end of the file.
If needing sudo
, use:
echo "text" | sudo tee -a filename >/dev/null
You're deleting sjonObj.key
, literally. You need to use array access notation:
delete sjonObj[key];
However, that will also delete where value is equal to 0, since you're not using strict comparison. Use ===
instead:
$.each(sjonObj, function(key, value){
if (value === "" || value === null){
delete sjonObj[key];
}
});
However, this will only walk the object shallowly. To do it deeply, you can use recursion:
(function filter(obj) {
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if (Object.prototype.toString.call(value) === '[object Object]') {
filter(value);
} else if ($.isArray(value)) {
$.each(value, function (k,v) { filter(v); });
}
});
})(sjonObj);
var sjonObj = {_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"coreTEEVersion": "3.3.1.4_RC8",_x000D_
"testSuiteId": "yyy",_x000D_
"testSuiteFormatVersion": "1.0.0.0",_x000D_
"testStatus": "IDLE",_x000D_
"reportPath": "",_x000D_
"startTime": 0,_x000D_
"durationBetweenTestCases": 20,_x000D_
"endTime": 0,_x000D_
"lastExecutedTestCaseId": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"fixedTimeSyncSupported": false,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"summaryReportRequired": "true",_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "a",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
},_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
{_x000D_
"commandParameters": {_x000D_
"serverAddress": "www.ggp.com",_x000D_
"echoRequestCount": "",_x000D_
"sendPacketSize": "",_x000D_
"interval": "",_x000D_
"ttl": "",_x000D_
"addFullDataInReport": "True",_x000D_
"maxRTT": "",_x000D_
"failOnTargetHostUnreachable": "True",_x000D_
"failOnTargetHostUnreachableCount": "",_x000D_
"initialDelay": "",_x000D_
"commandTimeout": "",_x000D_
"testDuration": ""_x000D_
},_x000D_
"commandName": "Ping",_x000D_
"testStatus": "IDLE",_x000D_
"label": "",_x000D_
"reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
"endTime": 0,_x000D_
"startTime": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"detailReportRequired": "true",_x000D_
"summaryReportRequired": "true"_x000D_
}_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "dd",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "b",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
(function filter(obj) {_x000D_
$.each(obj, function(key, value){_x000D_
if (value === "" || value === null){_x000D_
delete obj[key];_x000D_
} else if (Object.prototype.toString.call(value) === '[object Object]') {_x000D_
filter(value);_x000D_
} else if (Array.isArray(value)) {_x000D_
value.forEach(function (el) { filter(el); });_x000D_
}_x000D_
});_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj)
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Note that if you're willing to use a library like lodash/underscore.js, you can use _.pick
instead. However, you will still need to use recursion to filter deeply, since neither library provides a deep filter function.
sjonObj = (function filter(obj) {
var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);
This variant has the added advantage of leaving the original object unmodified, but it does create an entirely new copy, which would be less efficient if you don't need the original object.
var sjonObj = {_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"coreTEEVersion": "3.3.1.4_RC8",_x000D_
"testSuiteId": "yyy",_x000D_
"testSuiteFormatVersion": "1.0.0.0",_x000D_
"testStatus": "IDLE",_x000D_
"reportPath": "",_x000D_
"startTime": 0,_x000D_
"durationBetweenTestCases": 20,_x000D_
"endTime": 0,_x000D_
"lastExecutedTestCaseId": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"fixedTimeSyncSupported": false,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"summaryReportRequired": "true",_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "a",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
},_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
_x000D_
],_x000D_
"testCaseList": [_x000D_
{_x000D_
"executionMode": "SEQUENTIAL",_x000D_
"commandList": [_x000D_
{_x000D_
"commandParameters": {_x000D_
"serverAddress": "www.ggp.com",_x000D_
"echoRequestCount": "",_x000D_
"sendPacketSize": "",_x000D_
"interval": "",_x000D_
"ttl": "",_x000D_
"addFullDataInReport": "True",_x000D_
"maxRTT": "",_x000D_
"failOnTargetHostUnreachable": "True",_x000D_
"failOnTargetHostUnreachableCount": "",_x000D_
"initialDelay": "",_x000D_
"commandTimeout": "",_x000D_
"testDuration": ""_x000D_
},_x000D_
"commandName": "Ping",_x000D_
"testStatus": "IDLE",_x000D_
"label": "",_x000D_
"reportFileName": "tc_2-tc_1-cmd_1_Ping",_x000D_
"endTime": 0,_x000D_
"startTime": 0,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"postConditionExecution": "ON_SUCCESS",_x000D_
"detailReportRequired": "true",_x000D_
"summaryReportRequired": "true"_x000D_
}_x000D_
],_x000D_
"testCaseList": [_x000D_
_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "dd",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
],_x000D_
"testStatus": "IDLE",_x000D_
"boundTimeDurationForExecution": 0,_x000D_
"startTime": 0,_x000D_
"endTime": 0,_x000D_
"label": null,_x000D_
"repeatCount": 0,_x000D_
"retryCount": 0,_x000D_
"totalRepeatCount": 0,_x000D_
"totalRetryCount": 0,_x000D_
"testCaseId": "b",_x000D_
"summaryReportRequired": "false",_x000D_
"postConditionExecution": "ON_SUCCESS"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
sjonObj = (function filter(obj) {_x000D_
var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });_x000D_
return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });_x000D_
})(sjonObj);_x000D_
_x000D_
console.log(sjonObj);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
_x000D_
[JAVA 8]
import java.util.Base64;
String dummy= "dummy string";
byte[] byteArray = dummy.getBytes();
byte[] salt = new byte[]{ -47, 1, 16, ... }
String encoded = Base64.getEncoder().encodeToString(salt);
Statistic plugins works fine!
Here is a quick case:
Refresh
for whole project or select your project or file and Refresh on selection
for only selection.@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).
Uses for @dynamic are e.g. with subclasses of NSManagedObject
(CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.
@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.
Super class:
@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;
Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;
Skipping Terminal setup since you mentioned applications, permanent system environment variable set up (works for macOS Sierra; should work for El Capitan too):
launchctl setenv JAVA_HOME $(/usr/libexec/java_home -v 1.8)
(this will set JAVA_HOME to the latest 1.8 JDK, chances are you have gone through serveral updates e.g. javac 1.8.0_101, javac 1.8.0_131)
Of course, change 1.8 to 1.7 or 1.6 (really?) to suit your need and your system
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
Get second, third, fourth......Nth highest salary using following query
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP N salary FROM employees ORDER BY salary DESC)
Replace N by you number i.e. N=2 for second highest salary, N=3 for third highest salary and so on. So for second highest salary use
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP 2 salary FROM employees ORDER BY salary DESC)
For large arrays or arrays that will be variable sized you should probably use:
Enumerable.Repeat(true, 1000000).ToArray();
For small array you can use the collection initialization syntax in C# 3:
bool[] vals = new bool[]{ false, false, false, false, false, false, false };
The benefit of the collection initialization syntax, is that you don't have to use the same value in each slot and you can use expressions or functions to initialize a slot. Also, I think you avoid the cost of initializing the array slot to the default value. So, for example:
bool[] vals = new bool[]{ false, true, false, !(a ||b) && c, SomeBoolMethod() };
Entity Framework detects something about the model has changed, you need to do something to the database to get this work. Solution: 1. enable-migrations 2. update-database
You cannot create a backup from a remote server to a local disk - there is just no way to do this. And there are no third-party tools to do this either, as far as I know.
All you can do is create a backup on the remote server machine, and have someone zip it up and send it to you.
Main build.gradle - /build.gradle
buildscript {
...
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
// Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
}
...
}
Module specific build.gradle - /app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
...
useLibrary 'org.apache.http.legacy'
...
}
#Edit (add explanation :) )
say you have an array you want to update your existing firestore document field with. You can use set(yourData, {merge: true} )
passing setOptions(second param in set function) with {merge: true}
is must in order to merge the changes instead of overwriting. here is what the official documentation says about it
An options object that configures the behavior of set() calls in DocumentReference, WriteBatch, and Transaction. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.
you can use this
const yourNewArray = [{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}]
collectionRef.doc(docId).set(
{
proprietary: "jhon",
sharedWith: firebase.firestore.FieldValue.arrayUnion(...yourNewArray),
},
{ merge: true },
);
hope this helps :)
A portable solution could use getc
.
#include <stdio.h>
char buffer[MAX_FILE_SIZE];
size_t i;
for (i = 0; i < MAX_FILE_SIZE; ++i)
{
int c = getc(fp);
if (c == EOF)
{
buffer[i] = 0x00;
break;
}
buffer[i] = c;
}
If you don't want to have a MAX_FILE_SIZE
macro or if it is a big number (such that buffer
would be to big to fit on the stack), use dynamic allocation.
Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.
Stating your time as HH
will give you 24h format, and hh
will give 12h format.
You can also find it here in the documentation :
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
$('#myDiv').hide();
hide function is used to edit content and show function is used to show again.
For more please click on this link.
The tutorial ANGULAR.JS: NG-SELECT AND NG-OPTIONS helped me solve the problem:
<select id="countryId"
class="form-control"
data-ng-model="entity.countryId"
ng-options="value.dataValue as value.dataText group by value.group for value in countries"></select>
You can recursively revert like this:
svn revert --recursive .
There is no way (without writing a creative script) to remove things that aren't under source control. I think the closest you could do is to iterate over all of the files, use then grep the result of svn list
, and if the grep fails, then delete it.
EDIT: The solution for the creative script is here: Automatically remove Subversion unversioned files
So you could create a script that combines a revert
with whichever answer in the linked question suits you best.
you can try implementing this ForkJoinWorkerThreadFactory and inject it to Fork-Join class.
public ForkJoinPool(int parallelism,
ForkJoinWorkerThreadFactory factory,
UncaughtExceptionHandler handler,
boolean asyncMode) {
this(checkParallelism(parallelism),
checkFactory(factory),
handler,
asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
"ForkJoinPool-" + nextPoolId() + "-worker-");
checkPermission();
}
you can use this constructor of Fork-Join pool to do this.
notes:-- 1. if you use this, take into consideration that based on your implementation of new threads, scheduling from JVM will be affected, which generally schedules fork-join threads to different cores(treated as a computational thread). 2. task scheduling by fork-join to threads won't get affected. 3. Haven't really figured out how parallel stream is picking threads from fork-join(couldn't find proper documentation on it), so try using a different threadNaming factory so as to make sure, if threads in parallel stream are being picked from customThreadFactory that you provide. 4. commonThreadPool won't use this customThreadFactory.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
you can use the views *_DEPENDENCIES
, for example:
SELECT owner, NAME
FROM dba_dependencies
WHERE referenced_owner = :table_owner
AND referenced_name = :table_name
AND TYPE IN ('PACKAGE', 'PACKAGE BODY')
You can find the answer in this video https://www.youtube.com/watch?v=SYoN-OvdZ3M&list=PLonJJ3BVjZW6CtAMbJz1XD8ELUs1KXaTD&index=19 and the next 3 videos. All the touch events are explained very well, it's very clear and full of examples.
There is one other option also .
row=(Row) sheet.getRow(i);
if (row == null || isEmptyRow(row)) {
return;
}
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext())
{}
Try using below code:
<button title="button title" class="action primary tocart" onclick=" window.open('http://www.google.com', '_blank'); return false;">Google</button>
Here, the window.open
with _blank
as second argument of window.open
function will open the link in new tab.
And by the use of return false
we can remove/cancel the default behavior of the button like submit.
For more detail and live example, click here
A 32-bit process is still limited to the same constraints in a 64-bit OS. The issue is that memory pointers are only 32-bits wide, so the program can't assign/resolve any memory address larger than 32 bits.
You have two line segments. Define one segment by endpoints A & B and the second segment by endpoints C & D. There is a nice trick to show that they must intersect, WITHIN the bounds of the segments. (Note that the lines themselves may intersect beyond the bounds of the segments, so you must be careful. Good code will also watch for parallel lines.)
The trick is to test that points A and B must line on opposite sides of line CD, AND that points C and D must lie on opposite sides of line AB.
Since this is homework, I won't give you an explicit solution. But a simple test to see which side of a line a point falls on, is to use a dot product. Thus, for a given line CD, compute the normal vector to that line (I'll call it N_C.) Now, simply test the signs of these two results:
dot(A-C,N_C)
and
dot(B-C,N_C)
If those results have opposite signs, then A and B are opposite sides of line CD. Now do the same test for the other line, AB. It has normal vector N_A. Compare the signs of
dot(C-A,N_A)
and
dot(D-A,N_A)
I'll leave it to you to figure out how to compute a normal vector. (In 2-d, that is trivial, but will your code worry about whether A and B are distinct points? Likewise, are C and D distinct?)
You still need to worry about line segments that lie along the same infinite line, or if one point actually falls on the other line segment itself. Good code will cater to every possible problem.
I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:
BufferedImage img = null;
try {
img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));
Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
a much more handy solution for your reference, it works perfect in all of my projects:
change your first line from
.navbar.navbar-fixed-top
to
.navbar.navbar-default.navbar-static-top
You have two options, a PL/SQL block or SQL*Plus bind variables:
var z number
execute my_stored_proc (-1,2,0.01,:z)
print z
Using java 8 removeIf
public int getSimilarItems(){
List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
int initial = two.size();
two.removeIf(one::contains);
return initial - two.size();
}
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
This is my method if i got your point
HTML
<label for="FileInput">
<img src="tools/img/upload2.png" style="cursor:pointer" onmouseover="this.src='tools/img/upload.png'" onmouseout="this.src='tools/img/upload2.png'" alt="Injaz Msila" style="float:right;margin:7px" />
</label>
<form action="upload.php">
<input type="file" id="FileInput" style="cursor: pointer; display: none"/>
<input type="submit" id="Up" style="display: none;" />
</form>
jQuery
<script type="text/javascript">
$( "#FileInput" ).change(function() {
$( "#Up" ).click();
});
</script>
I liked the Status Bar from this page:
https://wellsr.com/vba/2017/excel/vba-application-statusbar-to-mark-progress/
I updated it so it could be used as a called procedure. No credit to me.
showStatus Current, Total, " Process Running: "
Private Sub showStatus(Current As Integer, lastrow As Integer, Topic As String)
Dim NumberOfBars As Integer
Dim pctDone As Integer
NumberOfBars = 50
'Application.StatusBar = "[" & Space(NumberOfBars) & "]"
' Display and update Status Bar
CurrentStatus = Int((Current / lastrow) * NumberOfBars)
pctDone = Round(CurrentStatus / NumberOfBars * 100, 0)
Application.StatusBar = Topic & " [" & String(CurrentStatus, "|") & _
Space(NumberOfBars - CurrentStatus) & "]" & _
" " & pctDone & "% Complete"
' Clear the Status Bar when you're done
' If Current = Total Then Application.StatusBar = ""
End Sub
To prevent "Div parent" use margin of "div child":
In parent use these css:
I'd wrap the dictionary in another class:
public class MyListDictionary
{
private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();
public void Add(string key, string value)
{
if (this.internalDictionary.ContainsKey(key))
{
List<string> list = this.internalDictionary[key];
if (list.Contains(value) == false)
{
list.Add(value);
}
}
else
{
List<string> list = new List<string>();
list.Add(value);
this.internalDictionary.Add(key, list);
}
}
}
As some of the answers point out, createdb
is a command line utility that could be used to create database.
Assuming you have a user named dbuser
, the following command could be used to create a database and provide access to dbuser
:
createdb -h localhost -p 5432 -U dbuser testdb
Replace localhost
with your correct DB host name, 5432
with correct DB port, and testdb
with the database name you want to create.
Now psql
could be used to connect to this newly created database:
psql -h localhost -p 5432 -U dbuser -d testdb
Tested with createdb
and psql
versions 9.4.15
.
I've got the list in debug mode; first I saw the point at which the error was thrown
javax.faces.view.facelets.TagException: /showcase/partial_submit.xhtml @26,36 Event:changed is not supported. org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.applyAttachedObject(AjaxBehaviorHandler.java:179) org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.apply(AjaxBehaviorHandler.java:157)
and then I debugged AjaxBehaviorHandler
so if you want discover the right list of supported event, you can generate an error (using an event name that is wrong), and follow this way
The file extension may be case sentive...but the code works.
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Dev\"
Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "pdf" Then
Wscript.Echo objFile.Name
End If
Next
Wscript.Echo
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
Wscript.Echo
ShowSubFolders Subfolder
Next
End Sub
It is an alternative way to check equality of array lists which can contain null values:
List listA = Arrays.asList(null, "b", "c");
List listB = Arrays.asList("b", "c", null);
System.out.println(checkEquality(listA, listB)); // will return TRUE
private List<String> getSortedArrayList(List<String> arrayList)
{
String[] array = arrayList.toArray(new String[arrayList.size()]);
Arrays.sort(array, new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
if (o1 == null && o2 == null)
{
return 0;
}
if (o1 == null)
{
return 1;
}
if (o2 == null)
{
return -1;
}
return o1.compareTo(o2);
}
});
return new ArrayList(Arrays.asList(array));
}
private Boolean checkEquality(List<String> listA, List<String> listB)
{
listA = getSortedArrayList(listA);
listB = getSortedArrayList(listB);
String[] arrayA = listA.toArray(new String[listA.size()]);
String[] arrayB = listB.toArray(new String[listB.size()]);
return Arrays.deepEquals(arrayA, arrayB);
}
Below is the code which uses lock on a shared object which has the number to be printed. It guarantees the sequence also unlike the above solution.
public class MultiThreadPrintNumber {
int i = 1;
public synchronized void printNumber(String threadNm) throws InterruptedException{
if(threadNm.equals("t1")){
if(i%2 == 1){
System.out.println(Thread.currentThread().getName()+"--"+ i++);
notify();
} else {
wait();
}
} else if(threadNm.equals("t2")){
if(i%2 == 0){
System.out.println(Thread.currentThread().getName()+"--"+ i++);
notify();
} else {
wait();
}
}
}
public static void main(String[] args) {
final MultiThreadPrintNumber obj = new MultiThreadPrintNumber();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
while(obj.i <= 10){
obj.printNumber(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done t1");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
while(obj.i <=10){
obj.printNumber(Thread.currentThread().getName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done t2");
}
});
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
The output will look like: t1--1 t2--2 t1--3 t2--4 t1--5 t2--6 t1--7 t2--8 t1--9 t2--10 done t2 done t1
If you want to apply clear value to a specific number of fields, then assign id or class to them and apply empty value to them. like this:
$('.all_fields').val('');
where all_fields
is class applied to desired input fields for applying empty values.
It will protect other fields to be empty, that you don't want to change.
This might not be the simplest answer as compared to using array_values().
Try this
$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
foreach($arrays as $k => $item)
{
$array[$i]=$item;
unset($arrays[$k]);
$i++;
}
print_r($array);
It is valuable to additionally note, that PHP will populate all the $_GET
parameters even when you send a proper request of other type.
Methods in above replies are completely correct, however if you want to additionaly check for GET
parameters while handling POST
, DELETE
, PUT
, etc. request, you need to check the size of $_GET
array.
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees
in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
It is used to influence sorting in the CSS cascade when sorting by origin is done. It has nothing to do with specificity like stated here in other answers.
Here is the priority from lowest to highest:
After that specificity takes place for the rules still having a finger in the pie.
References:
The above responses are the better, but just for completeness, when you are in a component you can access the history object inside the VueRouter with: this.$router.history. That means we can listen to changes with:
this.$router.listen((newLocation) =>{console.log(newLocation);})
I think this is mainly useful when used along with this.$router.currentRoute.path
You can check what I am talking about placing a debugger
instruction in your code and begin playing with the Chrome DevTools Console.
Try this:
$results = DB::table('users')->toSql();
dd($results);
Note: get() has been replaced with toSql() to display the raw SQL query.
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
Also the error can be solved by adding several flags, like -marm -mthumb-interwork
. It was helpful for me to avoid this same error.
The to_sql method works for me.
However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:
FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)
import re
s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))
Use os.path.join to combine the path to the Documents
directory with the completeName
(filename?) supplied by the user.
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
If you want the Documents
directory to be relative to the user's home directory, you could use something like:
os.path.join(os.path.expanduser('~'),'Documents',completeName)
Others have proposed using os.path.abspath
. Note that os.path.abspath
does not resolve '~'
to the user's home directory:
In [10]: cd /tmp
/tmp
In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
I did solve this error by setting
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib:$ORACLE_HOME
yes, not only $ORACLE_HOME/lib but $ORACLE_HOME too.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
onload =function(){ _x000D_
var ele = document.querySelectorAll('.number-only')[0];_x000D_
ele.onkeypress = function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))_x000D_
return false;_x000D_
}_x000D_
ele.onpaste = function(e){_x000D_
e.preventDefault();_x000D_
}_x000D_
}
_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
$(function(){_x000D_
_x000D_
$('.number-only').keypress(function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
The above answers are for most common use case - validating input as a number.
But to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
$(function(){_x000D_
_x000D_
$('.number-only').keyup(function(e) {_x000D_
if(this.value!='-')_x000D_
while(isNaN(this.value))_x000D_
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')_x000D_
.split('').reverse().join('');_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
Here is a version that works in all modern browsers. The key is using appearance:none
which removes the default formatting. Since all of the formatting is gone, you have to add back in the arrow that visually differentiates the select from the input. Note: appearance
is not supported in IE.
Working example: https://jsfiddle.net/gs2q1c7p/
select:not([multiple]) {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
background-position: right 50%;_x000D_
background-repeat: no-repeat;_x000D_
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);_x000D_
padding: .5em;_x000D_
padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>
_x000D_
Based on Arno Tenkink's suggestion in the comments, here is an example using a svg instead of a png for the arrow icon.
select:not([multiple]) {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
background-position: right 50%;_x000D_
background-repeat: no-repeat;_x000D_
background-image: url('data:image/svg+xml;utf8,<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" version="1"><path d="M4 8L0 4h8z"/></svg>');_x000D_
padding: .5em;_x000D_
padding-right: 1.5em_x000D_
}_x000D_
_x000D_
#mySelect {_x000D_
border-radius: 0_x000D_
}
_x000D_
<select id="mySelect">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>
_x000D_
This is my code. Not perfect, but working good. I hope it helps somebody:
static System.Data.DataTable DtTbl (System.Data.DataTable[] dtToJoin)
{
System.Data.DataTable dtJoined = new System.Data.DataTable();
foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
dtJoined.Columns.Add(dc.ColumnName);
foreach (System.Data.DataTable dt in dtToJoin)
foreach (System.Data.DataRow dr1 in dt.Rows)
{
System.Data.DataRow dr = dtJoined.NewRow();
foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
dr[dc.ColumnName] = dr1[dc.ColumnName];
dtJoined.Rows.Add(dr);
}
return dtJoined;
}
Alternative way:
std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());
This has the advantage of not using .c_str()
which might cause the std::string
to copy itself in case there is no place to add the '\0'
at the end.
std::min_element(vec.begin(), vec.end())
- for std::vector
std::min_element(v, v+n)
- for array
std::min_element( std::begin(v), std::end(v) )
- added C++11 version from comment by @JamesKanze
If all you are doing is replacing the existing data, then you can do this
std::vector<int> data; // evil global :)
void CopyData(int *newData, size_t count)
{
data.assign(newData, newData + count);
}
Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.
For example:
$ echo "asd" | wc -l
Will return 1
and
$ echo -n "asd" | wc -l
Will return 0
So what I often use is grep <anything> -c
$ echo "asd" | grep "^.*$" -c
1
$ echo -n "asd" | grep "^.*$" -c
1
This is closer to reality than what wc -l
will return.
You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
You could also use file_get_contents
$url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01";
$data_a=file_get_contents($url_a);
echo $data_a;
@SC_Chupacabra has correct answer for modifying behavior.
I generally prefer CTRL + PAGE UP / DOWN for my navigation, rather than using the TAB key.
{
"key": "ctrl+pageUp",
"command": "workbench.action.nextEditor"
},
{
"key": "ctrl+pageDown",
"command": "workbench.action.previousEditor"
}
You can kill instantly doing it in that way:
private Thread _myThread = new Thread(SomeThreadMethod);
private void SomeThreadMethod()
{
// do whatever you want
}
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
_myThread.Abort();
}
I always use it and works for me:)
With safety-mirror on the classpath you get something similar to C#'s delegates and events.
Examples from the project's README:
Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();
greetingsDelegate.add(str -> "Hello " + str);
greetingsDelegate.add(str -> "Goodbye " + str);
DelegateInvocationResult<String> invocationResult =
greetingsDelegate.invokeAndAggregateExceptions("Sir");
invocationResult.getFunctionInvocationResults().forEach(funInvRes ->
System.out.println(funInvRes.getResult()));
//prints: "Hello sir" and "Goodbye Sir"
//Create a private Delegate. Make sure it is private so only *you* can invoke it.
private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();
//Create a public Event using the delegate you just created.
public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate)
See also this SO answer.
Another is RGraph: Javascript charts and graph library:
Canvas based so it's fast and there's roughly 20 different chart types. It's free for non-commercial use too!
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
How about for example https://github.com/joyent/node/wiki/modules#wiki-tcp. A very quick summary =>
To achieve this in PyCharm set 'Environment Variables' section to:
PYTHONUNBUFFERED=1;
FLASK_DEBUG=1
For Flask 'run / debug configurations'.
I think what you want might be to run the following from the command line:
ipython notebook --matplotlib=inline
If you don't like typing it at the cmd line every time then you could create an alias to do it for you.
Another, less convenient, way to do it is to use Decimal
class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
SCROLLBARS & $(window).scrollTop()
What I have discovered is that calling such functionality as in the solution thankfully provided above, (there are many more examples of this throughout this forum - which all work well) is only successful when scrollbars are actually visible and operating.
If (as I have maybe foolishly tried), you wish to implement such functionality, and you also wish to, shall we say, implement a minimalist "clean screen" free of scrollbars, such as at this discussion, then $(window).scrollTop()
will not work.
It may be a programming fundamental, but thought I'd offer the heads up to any fellow newbies, as I spent a long time figuring this out.
If anyone could offer some advice as to how to overcome this or a little more insight, feel free to reply, as I had to resort to show/hide onmouseover/mouseleave instead here
Live long and program, CollyG.
You are using:
expect(fn).toThrow(e)
But if you'll have a look on the function comment (expected is string):
294 /**
295 * Matcher that checks that the expected exception was thrown by the actual.
296 *
297 * @param {String} expected
298 */
299 jasmine.Matchers.prototype.toThrow = function(expected) {
I suppose you should probably write it like this (using lambda - anonymous function):
expect(function() { parser.parse(raw); } ).toThrow("Parsing is not possible");
This is confirmed in the following example:
expect(function () {throw new Error("Parsing is not possible")}).toThrow("Parsing is not possible");
Douglas Crockford strongly recommends this approach, instead of using "throw new Error()" (prototyping way):
throw {
name: "Error",
message: "Parsing is not possible"
}
Firstly, understand that DateTime
objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime
objects without formatting them.
To compare an input date with DateTime.Now
, you need to first parse the input into a date and then compare just the Year/Month/Day portions:
DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
throw new ArgumentException("Input string not in the correct format.");
if(inputDate.Date == DateTime.Now.Date) {
// Same date!
}
Provide random.choice() with a pre-weighted list:
Solution & Test:
import random
options = ['a', 'b', 'c', 'd']
weights = [1, 2, 5, 2]
weighted_options = [[opt]*wgt for opt, wgt in zip(options, weights)]
weighted_options = [opt for sublist in weighted_options for opt in sublist]
print(weighted_options)
# test
counts = {c: 0 for c in options}
for x in range(10000):
counts[random.choice(weighted_options)] += 1
for opt, wgt in zip(options, weights):
wgt_r = counts[opt] / 10000 * sum(weights)
print(opt, counts[opt], wgt, wgt_r)
Output:
['a', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'd', 'd']
a 1025 1 1.025
b 1948 2 1.948
c 5019 5 5.019
d 2008 2 2.008
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000
I checked out iterrows
after noticing Nick Crawford's answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the itertuples
method for my problem, which yields (index, row_value1...) tuples.
There's also iterkv
, which iterates through (column, series) tuples.
You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.
To write your own pseudo random generator is quite simple.
The suggestion of Dave Scotese is useful but, as pointed out by others, it is not quite uniformly distributed.
However, it is not because of the integer arguments of sin. It's simply because of the range of sin, which happens to be a one dimensional projection of a circle. If you would take the angle of the circle instead it would be uniform.
So instead of sin(x) use arg(exp(i * x)) / (2 * PI).
If you don't like the linear order, mix it a bit up with xor. The actual factor doesn't matter that much either.
To generate n pseudo random numbers one could use the code:
function psora(k, n) {
var r = Math.PI * (k ^ n)
return r - Math.floor(r)
}
n = 42; for(k = 0; k < n; k++) console.log(psora(k, n))
Please also note that you cannot use pseudo random sequences when real entropy is needed.
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
.+,(.+)
Explanation:
.+,
will search for everything before the comma, including the comma.
(.+)
will search for everything after the comma, and depending on your regex environment,
\1
is the reference for the first parentheses captured group that you need, in this example, everything after the comma.
var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});
console.log(a[0]);
It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.
I don't recall seeing this before, but at first glance I like it. As Ferruccio notes, it doesn't work well in the face of MI, but MI is more the exception than the rule and there's nothing that says something needs to be usable everywhere to be useful.
Another version which is simple
BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;
TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
CGRect screenBounds = [[UIScreen mainScreen] bounds];
That will give you the entire screen's resolution in points, so it would most typically be 320x480 for iPhones. Even though the iPhone4 has a much larger screen size iOS still gives back 320x480 instead of 640x960. This is mostly because of older applications breaking.
CGFloat screenScale = [[UIScreen mainScreen] scale];
This will give you the scale of the screen. For all devices that do not have Retina Displays this will return a 1.0f, while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f.
Now if you want to get the pixel width & height of the iOS device screen you just need to do one simple thing.
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
By multiplying by the screen's scale you get the actual pixel resolution.
A good read on the difference between points and pixels in iOS can be read here.
EDIT: (Version for Swift)
let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: screenBounds.size.width * screenScale, height: screenBounds.size.height * screenScale)
You really want to do this
flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))
This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
I cannot say that it is the "best" library, but I think you can try this: http://algart.net/java/AlgART/ It is an open-source Java library, supporting generalized "smart" arrays and matrices with elements of different types (from 1 bit to 64-bit floating point), including 2D-, 3D- and multidimensional image processing and other algorithms, working with arrays and matrices. Unfortunately right now it consists not enough demo and examples, but, on the other hand, it contains a lot of JavaDocs. It lay in the base of commercial software (SIMAGIS) during several years, but now it is open-source.
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
I had the same error. npm uninstall npm -g
, rm -rf node_modules
didn't help me, because when I tried I was getting Error: Cannot find module 'semver'
. But I solve my problem with these steps (this will delete other global modules you may be using):
sudo rm -rf /usr/local/lib/node_modules
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node
Hope this will help those who are getting a similar problem.
Have you start by reading the information on this on Wikipedia - Block cipher modes of operation? Then follow the reference link on Wikipedia to NIST: Recommendation for Block Cipher Modes of Operation.
I was having this problem. Things I tried:
This is what worked for me
Hope this helps someone!
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick
method if you select the previous value selected in the drop down..
I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.
In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal) Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.
API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.
If you are not using any primary key, then execute following queries at one single stroke. By replacing values:
# table_name - Your Table Name
# column_name_of_duplicates - Name of column where duplicate entries are found
create table table_name_temp like table_name;
insert into table_name_temp select distinct(column_name_of_duplicates),value,type from table_name group by column_name_of_duplicates;
delete from table_name;
insert into table_name select * from table_name_temp;
drop table table_name_temp
It is always advisable to take backup of database before you play with it.
$ find . -name \*.exe -o -name \*.dll -o -print
The first two -name options have no -print option, so they skipped. Everything else is printed.
I had the same question for macOS.
But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew
.
I fixed my issue with: $ brew uninstall python@2
Some context on here: https://bugs.swift.org/browse/SR-1061
I believe the simplest way would be this:(without stringbuilder)
string myString = "ABCDEFGHIJ";
char[] replacementChars = {'Z', 'X'};
byte j = 0;
for (byte i = 3; i <= 4; i++, j++)
{
myString = myString.Replace(myString[i], replacementChars[j]);
}
This works because a variable of type string can be treated as an array of char variables. You can, for example refer to the second character of a string variable with name "myString" as myString[1]
Here is my regex for validating numbers:
^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$
Valid numbers:
String []validNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};
Invalid numbers:
String []invalidNumbers={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};
arrList.set(5,newValue);
and if u want to update it then add this line also
youradapater.NotifyDataSetChanged();
I would like to suggest using JOOL library, it hides spliterator magic behind the Seq.seq(iterable)
call and also provides a whole bunch of additional useful functionality.
It can be found on this path (default path):
/Users/john/.ssh
john
is your Mac username.
You need
var i = $("#panel input");
or, depending on what exactly you want (see below)
var i = $("#panel :input");
the >
will restrict to children, you want all descendants.
EDIT: As Nick pointed out, there's a subtle difference between $("#panel input")
and $("#panel :input)
.
The first one will only retrieve elements of type input, that is <input type="...">
, but not <textarea>
, <button>
and <select>
elements. Thanks Nick, didn't know this myself and corrected my post accordingly. Left both options, because I guess the OP wasn't aware of that either and -technically- asked for inputs... :-)
Also, RESTful lets you get data back from a POST request.
JS (put in static/hello.html to serve via Python):
<html><head><meta charset="utf-8"/></head><body>
Hello.
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/postman", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: 'value'
}));
xhr.onload = function() {
console.log("HELLO")
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log(data);
}
</script></body></html>
Python server (for testing):
import time, threading, socket, SocketServer, BaseHTTPServer
import os, traceback, sys, json
log_lock = threading.Lock()
log_next_thread_id = 0
# Local log functiondef
def Log(module, msg):
with log_lock:
thread = threading.current_thread().__name__
msg = "%s %s: %s" % (module, thread, msg)
sys.stderr.write(msg + '\n')
def Log_Traceback():
t = traceback.format_exc().strip('\n').split('\n')
if ', in ' in t[-3]:
t[-3] = t[-3].replace(', in','\n***\n*** In') + '(...):'
t[-2] += '\n***'
err = '\n*** '.join(t[-3:]).replace('"','').replace(' File ', '')
err = err.replace(', line',':')
Log("Traceback", '\n'.join(t[:-3]) + '\n\n\n***\n*** ' + err + '\n***\n\n')
os._exit(4)
def Set_Thread_Label(s):
global log_next_thread_id
with log_lock:
threading.current_thread().__name__ = "%d%s" \
% (log_next_thread_id, s)
log_next_thread_id += 1
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
Set_Thread_Label(self.path + "[get]")
try:
Log("HTTP", "PATH='%s'" % self.path)
with open('static' + self.path) as f:
data = f.read()
Log("Static", "DATA='%s'" % data)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(data)
except:
Log_Traceback()
def do_POST(self):
Set_Thread_Label(self.path + "[post]")
try:
length = int(self.headers.getheader('content-length'))
req = self.rfile.read(length)
Log("HTTP", "PATH='%s'" % self.path)
Log("URL", "request data = %s" % req)
req = json.loads(req)
response = {'req': req}
response = json.dumps(response)
Log("URL", "response data = %s" % response)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
except:
Log_Traceback()
# Create ONE socket.
addr = ('', 8000)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(5)
# Launch 100 listener threads.
class Thread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
self.daemon = True
self.start()
def run(self):
httpd = BaseHTTPServer.HTTPServer(addr, Handler, False)
# Prevent the HTTP server from re-binding every handler.
# https://stackoverflow.com/questions/46210672/
httpd.socket = sock
httpd.server_bind = self.server_close = lambda self: None
httpd.serve_forever()
[Thread(i) for i in range(10)]
time.sleep(9e9)
Console log (chrome):
HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object
Console log (firefox):
GET
http://XXXXX:8000/hello.html [HTTP/1.0 200 OK 0ms]
POST
XHR
http://XXXXX:8000/postman [HTTP/1.0 200 OK 0ms]
HELLO hello.html:13:3
{"req": {"value": "value"}} hello.html:14:3
Object { req: Object }
Console log (Edge):
HTML1300: Navigation occurred.
hello.html
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "<!DOCTYPE html>".
hello.html (1,1)
Current window: XXXXX/hello.html
HELLO
hello.html (13,3)
{"req": {"value": "value"}}
hello.html (14,3)
[object Object]
hello.html (16,3)
{
[functions]: ,
__proto__: { },
req: {
[functions]: ,
__proto__: { },
value: "value"
}
}
Python log:
HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}
If none of the answers helps, you might need to adjust the project properties. Check this other StackOverflow answer on how to do that:
In case anyone else comes across this in a search for an answer...
The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.
Go here and get a number generated. Use any expiry date and CVV
https://ppmts.custhelp.com/app/answers/detail/a_id/750/
It's worked every time for me so far...
If you need a function try this.
First we'll create a type:
CREATE OR REPLACE TYPE T_TABLE IS OBJECT
(
Field1 int
, Field2 VARCHAR(25)
);
CREATE TYPE T_TABLE_COLL IS TABLE OF T_TABLE;
/
Then we'll create the function:
CREATE OR REPLACE FUNCTION TEST_RETURN_TABLE
RETURN T_TABLE_COLL
IS
l_res_coll T_TABLE_COLL;
l_index number;
BEGIN
l_res_coll := T_TABLE_COLL();
FOR i IN (
WITH TAB AS
(SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
UNION
SELECT '1002' ID, 'D,E,F' STR FROM DUAL
UNION
SELECT '1003' ID, 'C,E,G' STR FROM DUAL
)
SELECT id,
SUBSTR(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
FROM
( SELECT ',' || STR || ',' AS STR, id FROM TAB
),
( SELECT level AS lvl FROM dual CONNECT BY level <= 100
)
WHERE lvl <= LENGTH(STR) - LENGTH(REPLACE(STR, ',')) - 1
ORDER BY ID, NAME)
LOOP
IF i.ID = 1001 THEN
l_res_coll.extend;
l_index := l_res_coll.count;
l_res_coll(l_index):= T_TABLE(i.ID, i.name);
END IF;
END LOOP;
RETURN l_res_coll;
END;
/
Now we can select from it:
select * from table(TEST_RETURN_TABLE());
Output:
SQL> select * from table(TEST_RETURN_TABLE());
FIELD1 FIELD2
---------- -------------------------
1001 A
1001 B
1001 C
1001 D
1001 E
1001 F
6 rows selected.
Obviously you'd need to replace the WITH TAB AS...
bit with where you would be getting your actual data from.
Credit Credit
Perfect, try it:
SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";
This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.
window.location.href = window.location.origin + window.location.pathname;
Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer
press windows+R open RUN Window
services.msc
find SQL Server(SQLEXPRESS) right click on that and start the service then check
In my case I didn't add the http://
prefix. Potentially worth checking.
Like this:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
Check the docs for more info: NetworkInterface.
\tag
also works in align*
. Example:
\begin{align*}
a(x)^{2} &= bx\tag{1}\\
a(x)^{2} &= b\tag{2}\\
ax &= b\tag{3}\\
a(x)^{2}+bx &= c\tag{4}\\
a(x)^{2}+c &= bx\tag{5}\\
a(x)^{2} &= bx+c\tag{6}\\ \\
Where\quad a, b, c \, \in N
\end{align*}
Output:
Note: Disregard this answer, as I must have misunderstood the question.
select *
from Table
where len(ColName) mod 2 = 1
The exact syntax depends on what flavor of SQL you're using.
Alternative to remove branching in testing for zero:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);
Not sure if this will work in C#, should do in C/C++.
After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension
For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:
NotifyIcon1.Icon = My.Resources.Logo_square
A void*
pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc
returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
As library requires minSdkVersion 17
then you can change the same in build.gradle
(Module:Application) file:
defaultConfig {
minSdkVersion 17
targetSdkVersion 25
}
and after that building the project should not throw any build error.
if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:
!conda list cudatoolkit
!conda list cudnn
and to check if the gpu is visible to tf:
tf.test.is_gpu_available(
cuda_only=False, min_cuda_compute_capability=None
)
Previously we stored DB user/pass in a configuration file, but have since hit paranoid mode -- adopting a policy of Defence in Depth.
If your application is compromised, the user will have read access to your configuration file and so there is potential for a cracker to read this information. Configuration files can also get caught up in version control, or copied around servers.
We have switched to storing user/pass in environment variables set in the Apache VirtualHost. This configuration is only readable by root -- hopefully your Apache user is not running as root.
The con with this is that now the password is in a Global PHP variable.
To mitigate this risk we have the following precautions:
phpinfo()
is disabled. PHPInfo is an easy target to get an overview of everything, including environment variables.Mac OS X is Unix, Objective-C is C superset, so you can just use old-school fopen
and fgets
from <stdio.h>
. It's guaranteed to work.
[NSString stringWithUTF8String:buf]
will convert C string to NSString
. There are also methods for creating strings in other encodings and creating without copying.
A bit late to answer, but for who is searching. You can easily do this by using an extra property with the data annotation:
public string foo { get; set; }
public string bar { get; set; }
[MinLength(20, ErrorMessage = "too short")]
public string foobar
{
get
{
return foo + bar;
}
}
That's all that is too it really. If you really want to display in a specific place the validation error as well, you can add this in your view:
@Html.ValidationMessage("foobar", "your combined text is too short")
doing this in the view can come in handy if you want to do localization.
Hope this helps!
Well, I don't have a function in python but I have a function in C which you can easily convert to python, in the below c function extended euclidian algorithm is used to calculate inverse mod.
int imod(int a,int n){
int c,i=1;
while(1){
c = n * i + 1;
if(c%a==0){
c = c/a;
break;
}
i++;
}
return c;}
Python Function
def imod(a,n):
i=1
while True:
c = n * i + 1;
if(c%a==0):
c = c/a
break;
i = i+1
return c
Reference to the above C function is taken from the following link C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers
Please ensure that both the tables are in InnoDB format. Even if one is in MyISAM format, then, foreign key constraint wont work.
Also, another thing is that, both the fields should be of the same type. If one is INT, then the other should also be INT. If one is VARCHAR, the other should also be VARCHAR, etc.
As an alternative to rewriting history, consider using git replace
as in this article from the Pro Git book. The example discussed involves replacing a parent commit to simulate the beginning of a tree, while still keeping the full history as a separate branch for safekeeping.
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone_iOS7" bundle:nil];
AccountViewController * controller = [storyboard instantiateViewControllerWithIdentifier:@"accountView"];
// [self presentViewController:controller animated:YES completion:nil];
UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topRootViewController.presentedViewController)
{
topRootViewController = topRootViewController.presentedViewController;
}
[topRootViewController presentViewController:controller animated:YES completion:nil];
start cmd /k "your cmd command1"
start cmd /k "your cmd command2"
It works in Windows server2012 while I use these command in one batch file.
About sources (to change the access rights and thus bypass language encapsulation like java or C ++): You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.
So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.
Since "Guid" is not nullable, use "Guid.Empty" as default value.
Assume time column is in timestamp integer msec format
1 day = 86400000 ms
Here you go:
day_divider = 86400000
df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
Concurrent programming regards operations that appear to overlap and is primarily concerned with the complexity that arises due to non-deterministic control flow. The quantitative costs associated with concurrent programs are typically both throughput and latency. Concurrent programs are often IO bound but not always, e.g. concurrent garbage collectors are entirely on-CPU. The pedagogical example of a concurrent program is a web crawler. This program initiates requests for web pages and accepts the responses concurrently as the results of the downloads become available, accumulating a set of pages that have already been visited. Control flow is non-deterministic because the responses are not necessarily received in the same order each time the program is run. This characteristic can make it very hard to debug concurrent programs. Some applications are fundamentally concurrent, e.g. web servers must handle client connections concurrently. Erlang is perhaps the most promising upcoming language for highly concurrent programming.
Parallel programming concerns operations that are overlapped for the specific goal of improving throughput. The difficulties of concurrent programming are evaded by making control flow deterministic. Typically, programs spawn sets of child tasks that run in parallel and the parent task only continues once every subtask has finished. This makes parallel programs much easier to debug. The hard part of parallel programming is performance optimization with respect to issues such as granularity and communication. The latter is still an issue in the context of multicores because there is a considerable cost associated with transferring data from one cache to another. Dense matrix-matrix multiply is a pedagogical example of parallel programming and it can be solved efficiently by using Straasen's divide-and-conquer algorithm and attacking the sub-problems in parallel. Cilk is perhaps the most promising language for high-performance parallel programming on shared-memory computers (including multicores).
Copied from my answer: https://stackoverflow.com/a/3982782
Combing two of the answers above, another extension method is:
public static int ElapsedMonths(this DateTime date1, DateTime date2)
{
DateTime earlierDate = (date1 > date2) ? date2 : date1;
DateTime laterDate = (date1 > date2) ? date1 : date2;
var eMonths = (laterDate.Month - earlierDate.Month) + 12 * (laterDate.Year - earlierDate.Year) -
((earlierDate.Day > laterDate.Day) ? 1 : 0);
return eMonths;
}
Thanks to @AdamRobinson and @MarkWhittaker
Pygmentize is a killer tool. See this.
I combine python json.tool with pygmentize
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
See the link above for pygmentize installation instruction.
A demo of this is in the image below:
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
it needs to be .Row.count not Row.Number?
That's what I used and it works fine Sub TransfersToCleared() Dim ws As Worksheet Dim LastRow As Long Set ws = Application.Worksheets("Export (2)") 'Data Source LastRow = Range("A" & Rows.Count).End(xlUp).Row ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy
In Android Studio (at least since v2.3.3) you can run the command directly from the UI:
Click on the Gradle tab and then double click on :yourmodule -> Tasks -> android -> androidDependencies
The tree will be displayed in the Gradle Console tab
Instead of gdb
, run gdbtui
. Or run gdb
with the -tui
switch. Or press C-x C-a after entering gdb
. Now you're in GDB's TUI mode.
Enter layout asm
to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish
etc. are abbreviated to a single key, allowing you to walk through your program very quickly.
+---------------------------------------------------------------------------+ B+>|0x402670 <main> push %r15 | |0x402672 <main+2> mov %edi,%r15d | |0x402675 <main+5> push %r14 | |0x402677 <main+7> push %r13 | |0x402679 <main+9> mov %rsi,%r13 | |0x40267c <main+12> push %r12 | |0x40267e <main+14> push %rbp | |0x40267f <main+15> push %rbx | |0x402680 <main+16> sub $0x438,%rsp | |0x402687 <main+23> mov (%rsi),%rdi | |0x40268a <main+26> movq $0x402a10,0x400(%rsp) | |0x402696 <main+38> movq $0x0,0x408(%rsp) | |0x4026a2 <main+50> movq $0x402510,0x410(%rsp) | +---------------------------------------------------------------------------+ child process 21518 In: main Line: ?? PC: 0x402670 (gdb) file /opt/j64-602/bin/jconsole Reading symbols from /opt/j64-602/bin/jconsole...done. (no debugging symbols found)...done. (gdb) layout asm (gdb) start (gdb)
I'm lacking context, but this is working just fine:
List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...
When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com
if you used pipenv:
if you installed rest_framework thru the new pipenv, you need to run it thru the virtual environment:
1.pipenv shell
2.(env) now, run your command(for example python manage.py runserver)
A few possibilities:
You test k = M
instead of k == M
.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))
Here is a shorter version that should also work:
$('#ddlCodes').change(function() {
$('#txtEntry2').text(this.val());
});
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
This works for all types.
List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
You are right, you are creating a matrix with 2 rows, 3 columns and 4 depth. Numpy prints matrixes different to Matlab:
Numpy:
>>> import numpy as np
>>> np.zeros((2,3,2))
array([[[ 0., 0.],
[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.],
[ 0., 0.]]])
Matlab
>> zeros(2, 3, 2)
ans(:,:,1) =
0 0 0
0 0 0
ans(:,:,2) =
0 0 0
0 0 0
However you are calculating the same matrix. Take a look to Numpy for Matlab users, it will guide you converting Matlab code to Numpy.
For example if you are using OpenCV, you can build an image using numpy taking into account that OpenCV uses BGR representation:
import cv2
import numpy as np
a = np.zeros((100, 100,3))
a[:,:,0] = 255
b = np.zeros((100, 100,3))
b[:,:,1] = 255
c = np.zeros((100, 200,3))
c[:,:,2] = 255
img = np.vstack((c, np.hstack((a, b))))
cv2.imshow('image', img)
cv2.waitKey(0)
If you take a look to matrix c
you will see it is a 100x200x3 matrix which is exactly what it is shown in the image (in red as we have set the R coordinate to 255 and the other two remain at 0).
//book[title[@lang='it']]
is actually equivalent to
//book[title/@lang = 'it']
I tried it using vtd-xml, both expressions spit out the same result... what xpath processing engine did you use? I guess it has conformance issue Below is the code
import com.ximpleware.*;
public class test1 {
public static void main(String[] s) throws Exception{
VTDGen vg = new VTDGen();
if (vg.parseFile("c:/books.xml", true)){
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("//book[title[@lang='it']]");
//ap.selectXPath("//book[title/@lang='it']");
int i;
while((i=ap.evalXPath())!=-1){
System.out.println("index ==>"+i);
}
/*if (vn.endsWith(i, "< test")){
System.out.println(" good ");
}else
System.out.println(" bad ");*/
}
}
}
Casting null values is required for following construct where a method is overloaded and if null is passed to these overloaded methods then the compiler does not know how to clear up the ambiguity hence we need to typecast null in these cases:
class A {
public void foo(Long l) {
// do something with l
}
public void foo(String s) {
// do something with s
}
}
new A().foo((String)null);
new A().foo((Long)null);
Otherwise you couldn't call the method you need.
The best way to do this without more images :
public static void buttonEffect(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
I had parsing enum problem when i was trying to pass Nullable Enum that we get from Backend. Of course it was working when we get value, but it was problem when the null comes up.
java.lang.IllegalArgumentException: No enum constant
Also the problem was when we at Parcelize read moment write some short if.
My solution for this was
1.Create companion object with parsing method.
enum class CarsType {
@Json(name = "SMALL")
SMALL,
@Json(name = "BIG")
BIG;
companion object {
fun nullableValueOf(name: String?) = when (name) {
null -> null
else -> valueOf(name)
}
}
}
2. In Parcerable read place use it like this
data class CarData(
val carId: String? = null,
val carType: CarsType?,
val data: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
CarsType.nullableValueOf(parcel.readString()),
parcel.readString())
You have to use the viewWithTag
function to find the view with the given tag
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let point = touch.locationInView(self.view)
if let viewWithTag = self.view.viewWithTag(100) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}
I got the error by having multiple tables on the page and trying to initialize them all at once like this:
$('table').DataTable();
After a lot of trial and error, I initialized them separately and the error went away:
$("#table1-id").DataTable();
$("#table2-id").DataTable();