Angular5 and 6:
angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property
remove host and add @HostListener
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io
Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask
Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events
Angular2 and 4:
original
One way you could do it is using a directive that injects NgControl
and manipulates the value
(for details see inline comments)
@Directive({
selector: '[ngModel][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(keydown.backspace)': 'onInputChange($event.target.value, true)'
}
})
export class PhoneMask {
constructor(public model: NgControl) {}
onInputChange(event, backspace) {
// remove all mask characters (keep only numeric)
var newVal = event.replace(/\D/g, '');
// special handling of backspace necessary otherwise
// deleting of non-numeric characters is not recognized
// this laves room for improvement for example if you delete in the
// middle of the string
if (backspace) {
newVal = newVal.substring(0, newVal.length - 1);
}
// don't show braces for empty value
if (newVal.length == 0) {
newVal = '';
}
// don't show braces for empty groups at the end
else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
} else {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<form [ngFormModel]="form">
<input type="text" phone [(ngModel)]="data" ngControl="phone">
</form>
`,
directives: [PhoneMask]
})
export class App {
constructor(fb: FormBuilder) {
this.form = fb.group({
phone: ['']
})
}
}
When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.
It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.
Another answer for this would be
^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$
This will match a string of:
Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)
The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb")
. Returning a promise from an onFulfilled()
handler kicks off promise resolution. That's how promise chaining works.
From MSDN:
A
String
object is a sequential collection ofSystem.Char
objects that represent a string.
So you can use this:
var howManyBytes = yourString.Length * sizeof(Char);
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
for anyone who get blank page even after making storage accessible for displaying errors put these two lines at first lines of public/index.php to see what is happening at least. for me this error was there :Class 'PDO' not found in /var/www/***/config/database.php on line 16
error_reporting(E_ALL);
ini_set('display_errors', 1);
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
@Matthew's solution is the simplest and will perform well enough in most cases.
If you need high performance, AtomicInteger is a better solution ala @BalusC.
However, a faster solution (provided thread safety is not an issue) is to use TObjectIntHashMap which provides a increment(key) method and uses primitives and less objects than creating AtomicIntegers. e.g.
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>()
map.increment("aaa");
This usually appears when you want to use UIActivityViewController
in iPad.
Add below, before you present the controller to mark the arrow.
activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC
I assume you already have below, if not, add together:
activityViewController.popoverPresentationController?.sourceView = self.view
This should work (where enquiryId
is the id you need to match against):
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);
What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId
), then the current vehicle will be removed from the list.
If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":
The following works for me:
python -m http.server [<portNo>]
Because I am using Python 3 the module SimpleHTTPServer
has been replaced by http.server
, at least in Windows.
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));
kk.getText().toString();
System.out.println(+kk.getText().toString());
Another, more concise way:
node {
echo sh(returnStdout: true, script: 'env')
// ...
}
cf. https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#code-sh-code-shell-script
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :
ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...
maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.
Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.
For all browsers:
I perform 4 tests cases:
Below snippet presents differences between solutions A B C D E F G H I
function A(arr, name) {
let idx = arr.findIndex(o => o.name==name);
if(idx>=0) arr.splice(idx, 1);
return arr;
}
function B(arr, name) {
let idx = arr.findIndex(o => o.name==name);
return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}
function C(arr, name) {
let idx = arr.findIndex(o => o.name==name);
delete arr[idx];
return arr;
}
function D(arr, name) {
return arr.filter(el => el.name != name);
}
function E(arr, name) {
let result = [];
arr.forEach(o => o.name==name || result.push(o));
return result;
}
function F(arr, name) {
return _.reject(arr, el => el.name == name);
}
function G(arr, name) {
let o = arr.find(o => o.name==name);
return _.without(arr,o);
}
function H(arr, name) {
$.each(arr, function(i){
if(arr[i].name === 'Kristian') {
arr.splice(i,1);
return false;
}
});
return arr;
}
function I(arr, name) {
return $.grep(arr,o => o.name!=name);
}
// Test
let test1 = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
];
let test2 = [
{name:"John3", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
let test3 = [
{name:"John3", lines:"1,19,26,96"},
{name:"John", lines:"1,19,26,96"},
{name:"Joh2", lines:"1,19,26,96"},
];
console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);
[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders.
I think a better replacement could be log.error("errors happend in XXX", e)
This will also print out whole information which is easy reading than e.printStackTrace()
In controller:
function innerItem($scope, $element){
var jQueryInnerItem = $($element);
}
adb kill-server
and adb start-server
only control the adb
daemon on the PC side. You need to restart adbd
daemon on the device itself after reverting the service.adb.root
property change done by adb root
:
~$ adb shell id
uid=2000(shell) gid=2000(shell)
~$ adb root
restarting adbd as root
~$ adb shell id
uid=0(root) gid=0(root)
~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'
~$ adb shell id
uid=2000(shell) gid=2000(shell)
Make sure you have all the SDK's you need installed and Gradle is targeting the right version.
I was having the same issue, but it was caused by me updating my device to Android 5.0 and then forgetting to change all my builds to target it.
You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.
If you feel comfortable with using the extension you can use grep to see if it matches.
You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
StringBuilder SqlScript = new StringBuilder();
foreach (var file in lstScripts)
{
var input = File.ReadAllText(file.FilePath);
SqlScript.AppendFormat(input, Environment.NewLine);
}
I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.
Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.
You can use the readonly
property in your input field
<input type="text" readonly="readonly" />
One common misunderstanding withwhile
/for
loops I've seen is that their efficiency differs. While
loops and for
loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.
For
loops are simply syntactically sugared while
loops, and make iteration code faster to write.
When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while
and for
syntaxes are lost, and they become exactly the same.
Add this Script
<script type = "text/javascript">
function SetTarget() {
document.forms[0].target = "_blank";
}
</script>
and
<asp:Button ID="BTNpRINT" runat="server" Text="PRINT" CssClass="btn btn-primary" OnClick="BTNpRINT_Click" OnClientClick = "SetTarget();"/>
and
protected void BTNpRINT_Click(object sender, EventArgs e)
{
Response.Redirect(string.Format("~/Print.aspx?ID={0}",txtInv.Text));
}
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
Solved by adding the following dependency into pom.xml file :
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
I had very similar problem today and solution was as it is..
$email = Array("Zaffar Saffee" => "[email protected]");
$schedule->command('cmd:mycmd')
->everyMinute()
->sendOutputTo("/home/forge/dev.mysite.com/storage/logs/cron.log")
->emailWrittenOutputTo($email);
It laravel 5.2 though...
my basic problem was , I was passing string instead of array so, error was
->emailWrittenOutputTo('[email protected]'); // string, we need an array
` Adding the following to pom.xml will resolve the issue. <pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories> `
the data you have entered a table(tbldomare) aren't match a data you have assigned primary key table. write between tbldomare and add this word (with nocheck) then execute your code.
for example you entered a table tbldomar this data
INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);
and you assigned a foreign key
table to accept only 1,2,3
.
you have two solutions one is delete the data you have entered a table then execute the code. another is write this word (with nocheck) put it between your table name and add like this
ALTER TABLE tblDomare with nocheck
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
As static_rtti said above, change
https://github.com/username/repo.git
git://github.com/username/repo.git
to
ssh://[email protected]/username/repo.git
I myself changed the https
in the .git/config file to ssh
, but it still wasn't working. Then I saw that you must change github.com
to [email protected]
. A good way to get the actual correct URL is to go to your project page and click this:
Change HTTPS to SSH to get the right URL
Then add this URL to the configuration file.
One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader
module. If you have used create-react-app
to scaffold your project, the module is already included, you just need to import your json:
import Profile from './components/profile';
This answer explains more.
In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:
StratifiedShuffleSplit most closely resembles train_test_split(stratify = y) with added features of:
You can use the data type point
- combines (x,y)
which can be your lat / long. Occupies 16 bytes: 2 float8
numbers internally.
Or make it two columns of type float
(= float8
or double precision
). 8 bytes each.
Or real
(= float4
) if additional precision is not needed. 4 bytes each.
Or even numeric
if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.
Read the fine manual about numeric types and geometric types.
The geometry
and geography
data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).
Start reading the PostGIS manual here.
Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.
For server/protocol errors I would try to be as REST/HTTP as possible (Compare this with you typing in URL's in your browser):
For domain/business logic specific errors I would say the protocol is used in the right way and there's no server internal error, so respond with an error JSON/XML object or whatever you prefer to describe your data with (Compare this with you filling in forms on a website):
$ which pip
or
$ pip -V
execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.
<html>
<head>
<script type="text/javascript">
function GetTimeZoneOffset() {
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
</head>
<body onload="GetTimeZoneOffset()">
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSet" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</body>
</html>
key point to notice here is,body has an attribute onload
. Just give it a function name and that function will be called on page load.
Alternatively, you can also call the function on page load event like this
<html>
<head>
<script type="text/javascript">
window.onload = load();
function load() {
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
</head>
<body >
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSet" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></body>
</body>
</html>
While running react-native In case you have installed 23.0.3 and it is asking for 23.0.1 simply in your application project directory. Open anroid/app/build.gradle
and change buildToolsVersion "23.0.3"
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.
You can use CSS alone to center like so:
.center{_x000D_
position: absolute;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
background:red;_x000D_
top:calc(50% - 50px/2); /* height divided by 2*/_x000D_
left:calc(50% - 50px/2); /* width divided by 2*/_x000D_
}
_x000D_
<div class="center"></div>
_x000D_
calc()
allows you to do basic calculations in css.
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
Just regex out null bytes:
s/\x00//g;
An alternative to the already provided ways is to simply filter on the column like so
df = df.where(F.col('columnNameHere').isNull())
This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.
mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
| 4.000 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
| 4.500 |
+------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
| 0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)
You can try this:
$('#studentTypeCheck').is(":checked");
git show <commit>
To show what a commit did with stats:
git show <commit> --stat
To show commit log with differences introduced for each commit in a range:
git log -p <commit1> <commit2>
<commit>
?Each commit has a unique id we reference here as <commit>
. The unique id is an SHA-1 hash – a checksum of the content you’re storing plus a header. #TMI
If you don't know your <commit>
:
git log
to view the commit history
Find the commit you care about.
Have you tried DATENAME(MONTH, S0.OrderDateTime)
?
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
export PATH=/usr/local/bin:$PATH
brew update
brew install vim && brew install macvim
brew link macvim
You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade
every once in a while to upgrade them.
This includes the installation of the CLI mvim
and the mac application (which both point to the same thing).
I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.
You can also sort by the _id
field. For example, to get the most recent record, you can do,
const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
It's much quicker too, because I'm more than willing to bet that your date
field is not indexed.
Look into the Dimensions plugin, specifically scrollTop()
/scrollLeft()
. Information can be found at http://api.jquery.com/scrollTop.
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.
I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :
Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.
For example you can serialize like that :
// Random class initialization
com::class1* aObject = new com::class1();
for (int i=0; i<10; i++){
aObject->setData(i,i);
}
aObject->pdata = new char[7];
for (int i=0; i<7; i++){
aObject->pdata[i] = 7-i;
}
// dictionary initialization
cjson::dictionary aDict("./data/dictionary.xml");
// json transformation
std::string aJson = aDict.toJson<com::class1>(aObject);
// print encoded class
cout << aJson << std::endl ;
To deserialize data it works like that:
// decode the object
com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);
// modify data
aDecodedObject->setData(4,22);
// json transformation
aJson = aDict.toJson<com::class1>(aDecodedObject);
// print encoded class
cout << aJson << std::endl ;
Ouptuts:
>:~/cjson$ ./main
{"_index":54,"_inner": {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$
Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.
Old question, but the following might offer some more detail.
null
represents no value or an unknown value. It doesn’t specify why there is no value, which can lead to some ambiguity.
Suppose you run a query like this:
SELECT *
FROM orders
WHERE delivered=ordered;
that is, you are looking for rows where the ordered
and delivered
dates are the same.
What is to be expected when one or both columns are null?
Because at least one of the dates is unknown, you cannot expect to say that the 2 dates are the same. This is also the case when both dates are unknown: how can they be the same if we don’t even know what they are?
For this reason, any expression treating null
as a value must fail. In this case, it will not match. This is also the case if you try the following:
SELECT *
FROM orders
WHERE delivered<>ordered;
Again, how can we say that two values are not the same if we don’t know what they are.
SQL has a specific test for missing values:
IS NULL
Specifically it is not comparing values, but rather it seeks out missing values.
Finally, as regards the !=
operator, as far as I am aware, it is not actually in any of the standards, but it is very widely supported. It was added to make programmers from some languages feel more at home. Frankly, if a programmer has difficulty remembering what language they’re using, they’re off to a bad start.
extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton2"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton2"
android:textColor="@drawable/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:button="@null"
android:background="@drawable/shape_radiobutton3"
android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:scrollbars="vertical" />
According to the standard condition_variables
are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout
(since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.
The details are specified in the standard §30.5.1 [thread.condition.condvar]:
—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.
...
Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.
As Johannes has already suggested, a background-image is probally the best way to achieve this in CSS alone.
A JavaScript solution would also have to affect "dragstart" to be effective across all popular browsers.
JavaScript:
<div onselectstart="return false;" ondragstart="return false;">your text</div>
jQuery:
var _preventDefault = function(evt) { evt.preventDefault(); };
$("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
Rich
I went through all the examples and answers and in a way or another they didn't address my need. So I will list her a scenario that I need more help and I hope this can explain the idea more.
I need to develop a tool which is getting a file to process it and it needs some optional configuration file to be used to configure the tool.
so what I need is something like the following
mytool.py file.text -config config-file.json
Here is the solution code
import argparse
def main():
parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
parser.add_argument('filename', help="Input file either text, image or video")
# parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
# parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
args = parser.parse_args()
filename = args.filename
configfile = args.config_file
print("The file to be processed is", filename)
print("The config file is", configfile)
if args.debug:
print("Debug mode enabled")
else:
print("Debug mode disabled")
print("and all arguments are: ", args)
if __name__ == '__main__':
main()
I will show the solution in multiple enhancements to show the idea
List all input as mandatory inputs so second argument will be
parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
When we get the help command for this tool we find the following outcome
(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
config_file a JSON file to load the initial configuration
optional arguments:
-h, --help show this help message and exit
and when I execute it as the following
(base) > python .\argparser_example.py filename.txt configfile.json
the outcome will be
The file to be processed is filename.txt
The config file is configfile.json
and all arguments are: Namespace(config_file='configfile.json', filename='filename.txt')
But the config file should be optional, I removed it from the arguments
(base) > python .\argparser_example.py filename.txt
The outcome will be is:
usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c
Which means we have a problem in the tool
So to make it optional I modified the program as follows
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
The help outcome should be
usage: argparser_example.py [-h] [-c CONFIG] filename
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
optional arguments:
-h, --help show this help message and exit
-c CONFIG, --config CONFIG
a JSON file to load the initial configuration
so when I execute the program
(base) > python .\argparser_example.py filename.txt
the outcome will be
The file to be processed is filename.txt
The config file is configFile.json
and all arguments are: Namespace(config_file='configFile.json', filename='filename.txt')
with arguments like
(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json
The outcome will be
The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are: Namespace(config_file='anotherConfig.json', filename='filename.txt')
to change the flag name from --config_file
to --config
while we keep the variable name as is we modify the code to include dest='config_file'
as the following:
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')
and the command will be
(base) > python .\argparser_example.py filename.txt --config anotherConfig.json
To add the support for having a debug mode flag, we need to add a flag in the arguments to support a boolean debug flag. To implement it i added the following:
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
the tool command will be:
(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug
the outcome will be
The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are: Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')
You probably mistyped a few things. From what I gather, you start with a string such as:
string = "test1, test2, test3, test4, test5"
Then you want to split it to keep only the significant substrings:
array = string.split(/, /)
And in the end you only need all the elements excluding the first one:
# We extract and remove the first element from array
first_element = array.shift
# Now array contains the expected result, you can check it with
puts array.inspect
Did that answer your question ?
Very Simple .
Go to File then Settings then Select Editor then Font and change the size .
File -> Settings -> Editor -> Colors & Fonts -> Font.
Try reinstalling the app, this solved the error for me. The trick was that, I uninstalled my app, but Android didn't truly uninstall it. On my phone, there is a guest user (my sister uses it sometimes). If you uninstall the app from your main user, it will still be available on the phone, but only for the guest user. It looks like Android Studio can't handle this case. I guess it detects that the app is installed, so it will not be reinstalled again for the current user, hence the OS can't access and launch the activity. Nice bug, I'll report it.
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and
in between multiple fields during update, e.g.
update user
set token='lamblala',
accessverion='dummy' and
key='somekey'
where user = 'myself'
The problem in above query can be resolved by replacing and
with comma(,
)
I think you have missed to instruct spring to scan classes with annotation.
You can use @ComponentScan("packageToScan")
on the configuration class of your spring application to instruct spring to scan.
@Service, @Component
etc annotations add meta description.
Spring only injects instances of those classes which are either created as bean or marked with annotation.
Classes marked with annotation need to be identified by spring before injecting, @ComponentScan
instruct spring look for the classes marked with annotation. When Spring finds @Autowired
it searches for the related bean, and injects the required instance.
Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.
You could query the dataset and then loop the selected rows to set them as delete.
var rows = dt.Select("col1 > 5");
foreach (var row in rows)
row.Delete();
... and you could also create some extension methods to make it easier ...
myTable.Delete("col1 > 5");
public static DataTable Delete(this DataTable table, string filter)
{
table.Select(filter).Delete();
return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
foreach (var row in rows)
row.Delete();
}
I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments
, where Feature
is a class and command
is a method on that class. Here's a base class that makes this easy.
The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses()
which will return a dictionary. For example, if the directory looks like this:
Assuming feature.py
implements class Feature(ArgBaseClass)
, then the above invocation of load_subclasses
will return { 'feature' : <Feature object> }
. The same kwargs
(foo = bar
) will be passed into the Feature
class.
#!/usr/bin/env python3
import os, pkgutil, importlib, inspect
class ArgBaseClass():
# Assign all keyword arguments as properties on self, and keep the kwargs for later.
def __init__(self, **kwargs):
self._kwargs = kwargs
for (k, v) in kwargs.items():
setattr(self, k, v)
ms = inspect.getmembers(self, predicate=inspect.ismethod)
self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])
# Add the names of the methods to a parser object.
def _parse_arguments(self, parser):
parser.add_argument('method', choices=list(self.methods))
return parser
# Instantiate one of each of the subclasses of this class.
def load_subclasses(self):
module_dir = os.path.dirname(__file__)
module_name = os.path.basename(os.path.normpath(module_dir))
parent_class = self.__class__
modules = {}
# Load all the modules it the package:
for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
modules[name] = importlib.import_module('.' + name, module_name)
# Instantiate one of each class, passing the keyword arguments.
ret = {}
for cls in parent_class.__subclasses__():
path = cls.__module__.split('.')
ret[path[-1]] = cls(**self._kwargs)
return ret
Delete the .metadata
folder in your workspace.
You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.
TRUNCATE TABLE table_name
Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.
Related:
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.
some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc
In your case since you are sending HTML response to client you will have to set the content type as text/html
I use the vimrc in the python repo among other things:
http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc
I also add
set softtabstop=4
OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp
tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.
First of all, you need to create a batch (script) file for the ftp
program, containing instructions for it. Name it as you want, and put into it:
curl -u login:pass ftp.myftpsite.com/iiumlabs* -O
open ftp.myftpsite.com
login
pass
mget *
quit
The first line opens a connection to the ftp server at ftp.myftpsite.com
. The two following lines specify the login, and the password which ftp will ask for (replace login
and pass
with just the login and password, without any keywords). Then, you use mget *
to get all files. Instead of the *
, you can use any wildcard. Finally, you use quit
to close the ftp
program without interactive prompt.
If you needed to enter some directory first, add a cd
command before mget
. It should be pretty straightforward.
Finally, write that file and run ftp
like this:
ftp -i -s:yourscript
where -i
disables interactivity (asking before downloading files), and -s
specifies path to the script you created.
Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp
which is practically the PuTTy counter-part of the openssh scp
command.
The syntax is similar to copy
command, and it supports wildcards:
pscp -batch [email protected]:iiumlabs* .
If you authenticate using a key file, you should pass it using -i path-to-key-file
. If you use password, -pw pass
. It can also reuse sessions saved using PuTTy, using the load -load your-session-name
argument.
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
Do as you wish, as long as your are consistent among your dev. group. every few years the conventions changes..... (remmeber nIntVAr)...
I use this:
gridItems = this.state.applications.map(app =>
<ApplicationItem key={app.Id} app={app } />
);
PS: never forget the key or you will have a lot of warnings!
Another possibility of making.
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
Fairly intuitive way of doing this:
a = [1,2,3,4]
b = [2,3,4,5]
ab = [] #Create empty list
for i in range(0, len(a)):
ab.append(a[i]*b[i]) #Adds each element to the list
The correct answer is don't do that, use the HTML Agility Pack.
Edited to add:
To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());
There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.
Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.
A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.
Here is my class, works like a charm :
public static class IniFileManager
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileSection(string lpAppName,
byte[] lpszReturnBuffer, int nSize, string lpFileName);
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public static void IniWriteValue(string sPath,string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, sPath);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public static string IniReadValue(string sPath,string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, sPath);
return temp.ToString();
}
}
The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.
If you want to manually clean it up, for me with my version of jenkins (didn't appear to need an extra plugin installed, but who knows), there is a "workspace" link on the left column, click on your project, then on "workspace", then a "Wipe out current workspace" link appears beneath it on the left hand side column.
It looks like there's an extra space character in your string. You can use trim()
to remove leading and trailing whitespaces:
temp1 = Integer.parseInt(display.getText().trim(), 16 );
Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.
$product->get_categories()
is deprecated since version 3.0! Use wc_get_product_category_list
instead.
https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.
Assuming you have the Tuning template selected, to filter:
I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.
There are several ways, but using rename
will probably be the easiest.
Using one version of rename
:
rename 's/^fgh/jkl/' fgh*
Using another version of rename
(same as Judy2K's answer):
rename fgh jkl fgh*
You should check your platform's man page to see which of the above applies.
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder
, but it does what you asked.
Better technique (although still not ideal):
StringBuilder
.StringBuilder
when you're done.This will turn an O(n²) solution into O(n).
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
For me, it was very difficult to identify the problem because of a large number of methods and class involved.
What I did is commented (removed) some methods from the WebService interface and try, and then comment another bunch of methods and try, I kept doing this until I found the method that cause the problem.
In my case, it was using a complex object which cannot be serialized.
Good luck!
typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof
to test if an object is of a specific type.
function MyObj(prop) {
this.prop = prop;
}
var obj = new MyObj(10);
console.log(obj instanceof MyObj && obj instanceof Object); // outputs true
Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :
The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.
So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.
Active Mode—The client issues a PORT command to the server signaling that it will “actively” provide an IP and port number to open the Data Connection back to the client.
Passive Mode—The client issues a PASV command to indicate that it will wait “passively” for the server to supply an IP and port number, after which the client will create a Data Connection to the server.
There are lots of good answers above, but this blog post includes some helpful graphics and gives a pretty solid explanation: https://titanftp.com/2018/08/23/what-is-the-difference-between-active-and-passive-ftp/
I love how easy this is in Android Studio.
In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)
With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.
Then click Share and OK.
That's all!
You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.
https://developers.google.com/youtube/v3/docs/videos/list
You'll want to set part=contentDetails
, because the duration is there.
For example, the following call:
https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}
Gives this result:
{
"kind": "youtube#videoListResponse",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
"items": [
{
"id": "9bZkp7q19f0",
"kind": "youtube#video",
"etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
"contentDetails": {
"duration": "PT4M13S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"regionRestriction": {
"blocked": [
"DE"
]
}
}
}
]
}
The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.
You can close a figure by calling matplotlib.pyplot.close
, for example:
from numpy import *
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = 60*2*pi
fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)
You can also close all open figures by calling matplotlib.pyplot.close("all")
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
SqlDeveloper stores all the connections in a file named
connections.xml
In windows XP you can find the file in location
C:\Documents and Settings\<username>\Application Data\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml
In Windows 7 you will find it in location
C:\Users\<username>\AppData\Roaming\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml
Does Python have a string contains substring method?
99% of use cases will be covered using the keyword, in
, which returns True
or False
:
'substring' in any_string
For the use case of getting the index, use str.find
(which returns -1 on failure, and has optional positional arguments):
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
or str.index
(like find
but raises ValueError on failure):
start = 100
end = 1000
any_string.index('substring', start, end)
Use the in
comparison operator because
>>> 'foo' in '**foo**'
True
The opposite (complement), which the original question asked for, is not in
:
>>> 'foo' not in '**foo**' # returns False
False
This is semantically the same as not 'foo' in '**foo**'
but it's much more readable and explicitly provided for in the language as a readability improvement.
__contains__
The "contains" method implements the behavior for in
. This example,
str.__contains__('**foo**', 'foo')
returns True
. You could also call this function from the instance of the superstring:
'**foo**'.__contains__('foo')
But don't. Methods that start with underscores are considered semantically non-public. The only reason to use this is when implementing or extending the in
and not in
functionality (e.g. if subclassing str
):
class NoisyString(str):
def __contains__(self, other):
print(f'testing if "{other}" in "{self}"')
return super(NoisyString, self).__contains__(other)
ns = NoisyString('a string with a substring inside')
and now:
>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True
find
and index
to test for "contains"Don't use the following string methods to test for "contains":
>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2
>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'**oo**'.index('foo')
ValueError: substring not found
Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in
comparison operator.
Also, these are not drop-in replacements for in
. You may have to handle the exception or -1
cases, and if they return 0
(because they found the substring at the beginning) the boolean interpretation is False
instead of True
.
If you really mean not any_string.startswith(substring)
then say it.
We can compare various ways of accomplishing the same goal.
import timeit
def in_(s, other):
return other in s
def contains(s, other):
return s.__contains__(other)
def find(s, other):
return s.find(other) != -1
def index(s, other):
try:
s.index(other)
except ValueError:
return False
else:
return True
perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}
And now we see that using in
is much faster than the others.
Less time to do an equivalent operation is better:
>>> perf_dict
{'in:True': 0.16450627865128808,
'in:False': 0.1609668098178645,
'__contains__:True': 0.24355481654697542,
'__contains__:False': 0.24382793854783813,
'find:True': 0.3067379407923454,
'find:False': 0.29860888058124146,
'index:True': 0.29647137792585454,
'index:False': 0.5502287584545229}
Various NPM packages are available to make this task easy.
For Development
For Production (with extended functionality such as clustering, remote deploy etc.)
npm install -g pm2
npm install -g strongloop
Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.
Better and quicker approach without any software to download.
This should work.
///UPDATED DEMO 2 WATCH SOLUTION////
I hope that is the solution you're looking for! DEMO1 DEMO2
With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!
You can do that with that code here:
<div class="navTop">
<h1>Title</h1>
<nav>Dynamic menu</nav>
</div>
<div class="container">
<section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
Footer
</footer>
With that css:
.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}
And a bit of jquery:
$(document).ready(function() {
function setHeight() {
var top = $('.navTop').outerHeight();
var bottom = $('footer').outerHeight();
var totHeight = $(window).height();
$('section').css({
'height': totHeight - top - bottom + 'px'
});
}
$(window).on('resize', function() { setHeight(); });
setHeight();
});
DEMO 1
If you don't want jquery
<div class="row">
<h1>Title</h1>
<nav>NAV</nav>
</div>
<div class="row container">
<div class="content">
<div class="sidebar">
SIDEBAR
</div>
<div class="contents">
CONTENTS
</div>
</div>
<footer>Footer</footer>
</div>
CSS
*{
margin:0;padding:0;
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%;
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{
position: fixed;
bottom: 0;
left: 0;
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}
DEMO 2
getPath()
returns the path used to create the File
object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)
File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"
File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"
File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"
getAbsolutePath()
will resolve the path based on the execution location or drive. So if run from c:\test
:
path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"
getCanonicalPath()
is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.
As to when to use them. It depends on what you are trying to achieve. getPath()
is useful for portability. getAbsolutePath()
is useful to find the file system location, and getCanonicalPath()
is particularly useful to check if two files are the same.
Best solution is to use
DELETE FROM table WHERE id NOT IN ( 2 )
I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.
I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)
This is what the implementation looks like:
function displayOverlay(/*message, timeout, callback*/) {
return arrangeArgs(arguments, String, Number, Function,
function(message, timeout, callback) {
/* ... your code ... */
});
};
For clarity, here is what is going on:
function displayOverlay(/*message, timeout, callback*/) {
//arrangeArgs is the proxy
return arrangeArgs(
//first pass in the original arguments
arguments,
//then pass in the type for each argument
String, Number, Function,
//lastly, pass in your function and the proxy will do the rest!
function(message, timeout, callback) {
//debug output of each argument to verify it's working
console.log("message", message, "timeout", timeout, "callback", callback);
/* ... your code ... */
}
);
};
You can view the arrangeArgs proxy code in my GitHub repository here:
https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js
Here is the utility function with some comments copied from the repository:
/*
****** Overview ******
*
* Strongly type a function's arguments to allow for any arguments to be optional.
*
* Other resources:
* http://ejohn.org/blog/javascript-method-overloading/
*
****** Example implementation ******
*
* //all args are optional... will display overlay with default settings
* var displayOverlay = function() {
* return Sysmo.optionalArgs(arguments,
* String, [Number, false, 0], Function,
* function(message, timeout, callback) {
* var overlay = new Overlay(message);
* overlay.timeout = timeout;
* overlay.display({onDisplayed: callback});
* });
* }
*
****** Example function call ******
*
* //the window.alert() function is the callback, message and timeout are not defined.
* displayOverlay(alert);
*
* //displays the overlay after 500 miliseconds, then alerts... message is not defined.
* displayOverlay(500, alert);
*
****** Setup ******
*
* arguments = the original arguments to the function defined in your javascript API.
* config = describe the argument type
* - Class - specify the type (e.g. String, Number, Function, Array)
* - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
* The "boolean" indicates if the first value should be treated as a function.
* The "default" is an optional default value to use instead of undefined.
*
*/
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
//config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
//config doesn't need a default value.
//config can also be classes instead of an array if not required and no default value.
var configs = Sysmo.makeArray(arguments),
values = Sysmo.makeArray(configs.shift()),
callback = configs.pop(),
args = [],
done = function() {
//add the proper number of arguments before adding remaining values
if (!args.length) {
args = Array(configs.length);
}
//fire callback with args and remaining values concatenated
return callback.apply(null, args.concat(values));
};
//if there are not values to process, just fire callback
if (!values.length) {
return done();
}
//loop through configs to create more easily readable objects
for (var i = 0; i < configs.length; i++) {
var config = configs[i];
//make sure there's a value
if (values.length) {
//type or validator function
var fn = config[0] || config,
//if config[1] is true, use fn as validator,
//otherwise create a validator from a closure to preserve fn for later use
validate = (config[1]) ? fn : function(value) {
return value.constructor === fn;
};
//see if arg value matches config
if (validate(values[0])) {
args.push(values.shift());
continue;
}
}
//add a default value if there is no value in the original args
//or if the type didn't match
args.push(config[2]);
}
return done();
}
In my case, all the suggestions above were correct. I had most pages working except few that were returning 404 even though the markdown files are there and they seemed correct. Here is what fixed it for me on these pages:
UTF-8
and I think that's why GitHub pages was not able to render them. Updating/removing these char and pushing a new commit fixed it. '
surrounding the title, I removed them and the page content started showing fine Apart from the other already mentioned valid use cases std::weak_ptr
is an awesome tool in a multithreaded environment, because
std::shared_ptr
in conjunction with std::weak_ptr
is safe against dangling pointers - in opposite to std::unique_ptr
in conjunction with raw pointers std::weak_ptr::lock()
is an atomic operation (see also About thread-safety of weak_ptr)Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join()
etc is omitted, the threads would have to be handled differently in a real implementation etc)
// a simplified class to hold the thumbnail and data
struct ImageData {
std::string path;
std::unique_ptr<YourFavoriteImageLibData> image;
};
// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
for( auto& imageData : imagesToLoad )
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas =
splitImageDatas( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.
You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas
field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.
The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad
would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr
in conjunction with std::weak_ptr
.
// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
for( auto& imageDataWeak : imagesToLoad ) {
std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
if( !imageData )
continue;
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas =
splitImageDatasToWeak( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.
Add System.Web.Extensions as a reference to your project
For Ref.
Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:
ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );
Or just type the script in the HTML page suggested in the other answers.
You can use boolean indexing
:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
A Sales
0 3 10
1 4 20
2 7 30
3 6 40
4 1 50
s = 30
df1 = df[df['Sales'] >= s]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
df2 = df[df['Sales'] < s]
print (df2)
A Sales
0 3 10
1 4 20
It's also possible to invert mask
by ~
:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
print (df2)
A Sales
0 3 10
1 4 20
print (mask)
0 False
1 False
2 True
3 True
4 True
Name: Sales, dtype: bool
print (~mask)
0 True
1 True
2 False
3 False
4 False
Name: Sales, dtype: bool
You need to cast your activity from getActivity()
to AppCompatActivity
first. Here's an example:
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();
The reason you have to cast it is because getActivity()
returns a FragmentActivity
and you need an AppCompatActivity
In Kotlin:
(activity as AppCompatActivity).supportActionBar?.title = "My Title"
Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)
You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:
declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime
begin print 'true' end
else begin print 'no' end
The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.
public Tree (Object cargo, Tree left, Tree right) {
this.cargo = cargo;
this.left = left;
this.right = right;
}
We allocate the child nodes first:
Tree left = new Tree (new Integer(2), null, null);
Tree right = new Tree (new Integer(3), null, null);
We can create the parent node and link it to the children at the same time:
Tree tree = new Tree (new Integer(1), left, right);
EDIT: Updated broken link as of February, the 7th, 2017.
I think noone mentioned this:
At CERN they use a full reflection system for C++:
CERN Reflex. It seems to work very well.
Clean way with no jQuery:
function check(some_id) {
var content = document.getElementById(some_id).childNodes[0].nodeValue;
alert(content);
}
This is assuming each span has only the value as a child and no embedded HTML.
celery 4+ celery purge command to purge all configured task queues
celery -A *APPNAME* purge
programmatically:
from proj.celery import app
app.control.purge()
all pending task will be purged. Reference: celerydoc
updated:
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');
alert(new_date)
Either Collections.emptyMap()
, or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()
update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a
where a.table_name =d.table_name
and a.table_schema = d.table_schema
and a.column_name = d.column_name;
Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing (see also this document for a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).
I was facing the same problem. I have deleted the target folder and run maven install, it worked.
This String extension removes all whitespace from a string, not just trailing whitespace ...
extension String {
func replace(string:String, replacement:String) -> String {
return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
}
func removeWhitespace() -> String {
return self.replace(string: " ", replacement: "")
}
}
Example:
let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.
First part of accepted answer does not work for MSSQL.
This worked for me:
select email, COUNT(*) as C from table
group by email having COUNT(*) >1 order by C desc
It's as simple as that:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
You can do funny things then like:
var isMac = isMacintosh();
var isPC = !isMacintosh();
If watch doesn't want to install via
brew install watch
There is another similar/copy version that installed and worked perfectly for me
brew install visionmedia-watch
It is just an overload. The add
method is from the ArrayList
class. Look that Staff
inherits from it.
The Thread.stop()
method that could be used to stop a thread has been deprecated; for more info see; Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
Your best bet is to have a variable which the thread itself consults, and voluntarily exits if the variable equals a certain value. You then manipulate the variable inside your code when you want the thread to exit. Alternately of course, you can use an AsyncTask
instead.
On Linux I use:
lsof -P -T -p Application_PID
This works better than ldd
when the executable uses a non default loader
Ok, so the easiest method to create several plots is this:
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
plt.figure()
plt.plot(x[i],y[i])
# Show/save figure as desired.
plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()
Note that you need to create a figure
every time or pyplot
will plot in the first one created.
If you want to create several data series all you need to do is:
import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')
You could automate it by having a list of colours like ['r','g','b','k']
and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.
for i in range(len(x)):
plt.plot(x[i],y[i],colours[i])
plt.show()
Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.
17 Dec 2019: added plt.show()
and plt.figure()
calls to clarify this part of the story.
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
I know this is an old question, but...
I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:
http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/
I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:
Run the command:
appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']
Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT
and DELETE
verbs). Yay!
To find the HSV value of Green, try following commands in Python terminal
green = np.uint8([[[0,255,0 ]]])
hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
print hsv_green
[[[ 60 255 255]]]
header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df
In Visual Studio Code you can:
Explorer
Select for compare
Compare with '[NAME OF THE PREVIOUSLY SELECTED FILE]'
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
select your target and search for user-Defined section on build Settings,select provisioning profile and delete it
I tried most of the recommended fixes here, and still couldn't avoid the error message. I finally performed a combination of a few recommended solutions:
Added this entry to the top of the AppSettings
section of my web.config:
<add key="owin:AutomaticAppStartup" value="false"/>
Expanded the References node of my project and deleted everything that contained the string OWIN
. (I felt safe doing so since my organization is not (and won't be) an active OWIN provider in the future)
I then clicked Run
and my homepage loaded right up.
For Python2.7
You can format it into seconds and then multiply by 1000 to convert to millisecond.
from datetime import datetime
d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
d_in_ms = int(d)*1000
print(d_in_ms)
print(datetime.fromtimestamp(float(d)))
Output:
1482206922000
2016-12-20 09:38:42
I find out the reason of this problem for my project. I was added one dependency twice in build.gradle. One time by adding dependency and one time again by adding jar dependency:
compile 'org.achartengine:achartengine:1.2.0'
...
implementation files('../achartengine-1.2.0.jar')
after remove the first line problem solved.
It works fine by running genymotion with administrative privileges.
I solved it by deleting all of file in Ova,Templates and Deployed folder, I can run download and reinstall again and run without Administrative privileges
Have a look at Yahoo! tips: https://developer.yahoo.com/performance/rules.html#expires.
There are also tips by Google: https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
There are valid differences between types of architects:
Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.
Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.
Domain architects focus on specific areas, for example an application architect or network architect.
Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.
Use this command
\d table name
like
\d queuerecords
Table "public.queuerecords"
Column | Type | Modifiers
-----------+-----------------------------+-----------
id | uuid | not null
endtime | timestamp without time zone |
payload | text |
queueid | text |
starttime | timestamp without time zone |
status | text |
If people still have problems after adding/modifying the tomcat-users.xml file and adding the relevant user/role for the version of Tomcat that they're using then please be sure that you've removed the comment tags that are surrounding this block. They will look like this in the XML file:
<!--
-->
They will be above and below the user/role section.
As per you question this is what you can do
HTML
<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>
JS/Jquery
$(function () {
$('#sample').attr('readonly', 'true'); // mark it as read only
$('#sample').css('background-color' , '#DEDEDE'); // change the background color
});
or add a class in you css with the required styling
$('#sample').addClass('yourclass');
Let me know if the requirement was different
if you have number of columns in your database table more than number of columns in your csv you can proceed like this:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
You can do this with PureBasic and MsScriptControl
All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below
InitScriptControl()
SCtr_AddCode("MsgBox 1")
Use SimpleNamespace
:
>>> from types import SimpleNamespace
>>> d = dict(x=[1, 2], y=['a', 'b'])
>>> ns = SimpleNamespace(**d)
>>> ns.x
[1, 2]
>>> ns
namespace(x=[1, 2], y=['a', 'b'])
The compiler is confused by the function signature. You can fix it like this:
let task = URLSession.shared.dataTask(with: request as URLRequest) {
But, note that we don't have to cast "request" as URLRequest
in this signature if it was declared earlier as URLRequest
instead of NSMutableURLRequest
:
var request = URLRequest(url:myUrl!)
This is the automatic casting between NSMutableURLRequest
and the new URLRequest
that is failing and which forced us to do this casting here.
Firstly you need to change credentials from your local machine
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
@K Scott Piel wrote a great answer here, but I want to add one important point.
Note that the stdout
stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf
statement with a \n
Ex:
printf("hello world\n");
or
printf("hello world");
printf("\n");
or similar, OR you must call fflush(stdout);
after your printf
call.
Ex:
printf("hello world");
fflush(stdout);
Read more here: Why does printf not flush after the call unless a newline is in the format string?
IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.
Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.
yes, using and
, like:
@media screen and (max-width: 800px),
screen and (max-height: 600px) {
...
}
you can also use the Array.find
feature of es6
. the doc is here
return restaurants.find(item => {
return item.restaurant.food == 'chicken'
})
use this method
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
Toast.makeText(getActivity(),"PORTRAIT",Toast.LENGTH_LONG).show();
//add your code what you want to do when screen on PORTRAIT MODE
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Toast.makeText(getActivity(),"LANDSCAPE",Toast.LENGTH_LONG).show();
//add your code what you want to do when screen on LANDSCAPE MODE
}
}
And Do not forget to Add this in your Androidmainfest.xml
android:configChanges="orientation|screenSize"
like this
<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:configChanges="orientation|screenSize">
</activity>
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!"
}).then(
function () { /*Your Code Here*/ },
function () { return false; });
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this);
Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e)
. However, doing this for multiple buttons can be confusing, because the actionPerformed
method will have to check the source of each event (e.getSource()
) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed()
.
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed()
if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()
).
The guidance on not using a thread abort is controversial. I think there is still a place for it but in exceptional circumstance. However you should always attempt to design around it and see it as a last resort.
Example;
You have a simple windows form application that connects to a blocking synchronous web service. Within which it executes a function on the web service within a Parallel loop.
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{
Thread.Sleep(120000); // pretend web service call
});
Say in this example, the blocking call takes 2 mins to complete. Now I set my MaxDegreeOfParallelism to say ProcessorCount. iListOfItems has 1000 items within it to process.
The user clicks the process button and the loop commences, we have 'up-to' 20 threads executing against 1000 items in the iListOfItems collection. Each iteration executes on its own thread. Each thread will utilise a foreground thread when created by Parallel.ForEach. This means regardless of the main application shutdown, the app domain will be kept alive until all threads have finished.
However the user needs to close the application for some reason, say they close the form. These 20 threads will continue to execute until all 1000 items are processed. This is not ideal in this scenario, as the application will not exit as the user expects and will continue to run behind the scenes, as can be seen by taking a look in task manger.
Say the user tries to rebuild the app again (VS 2010), it reports the exe is locked, then they would have to go into task manager to kill it or just wait until all 1000 items are processed.
I would not blame you for saying, but of course! I should be cancelling these threads using the CancellationTokenSource object and calling Cancel ... but there are some problems with this as of .net 4.0. Firstly this is still never going to result in a thread abort which would offer up an abort exception followed by thread termination, so the app domain will instead need to wait for the threads to finish normally, and this means waiting for the last blocking call, which would be the very last running iteration (thread) that ultimately gets to call po.CancellationToken.ThrowIfCancellationRequested
.
In the example this would mean the app domain could still stay alive for up to 2 mins, even though the form has been closed and cancel called.
Note that Calling Cancel on CancellationTokenSource does not throw an exception on the processing thread(s), which would indeed act to interrupt the blocking call similar to a thread abort and stop the execution. An exception is cached ready for when all the other threads (concurrent iterations) eventually finish and return, the exception is thrown in the initiating thread (where the loop is declared).
I chose not to use the Cancel option on a CancellationTokenSource object. This is wasteful and arguably violates the well known anti-patten of controlling the flow of the code by Exceptions.
Instead, it is arguably 'better' to implement a simple thread safe property i.e. Bool stopExecuting. Then within the loop, check the value of stopExecuting and if the value is set to true by the external influence, we can take an alternate path to close down gracefully. Since we should not call cancel, this precludes checking CancellationTokenSource.IsCancellationRequested which would otherwise be another option.
Something like the following if condition would be appropriate within the loop;
if (loopState.ShouldExitCurrentIteration || loopState.IsExceptional || stopExecuting) {loopState.Stop(); return;}
The iteration will now exit in a 'controlled' manner as well as terminating further iterations, but as I said, this does little for our issue of having to wait on the long running and blocking call(s) that are made within each iteration (parallel loop thread), since these have to complete before each thread can get to the option of checking if it should stop.
In summary, as the user closes the form, the 20 threads will be signaled to stop via stopExecuting, but they will only stop when they have finished executing their long running function call.
We can't do anything about the fact that the application domain will always stay alive and only be released when all foreground threads have completed. And this means there will be a delay associated with waiting for any blocking calls made within the loop to complete.
Only a true thread abort can interrupt the blocking call, and you must mitigate leaving the system in a unstable/undefined state the best you can in the aborted thread's exception handler which goes without question. Whether that's appropriate is a matter for the programmer to decide, based on what resource handles they chose to maintain and how easy it is to close them in a thread's finally block. You could register with a token to terminate on cancel as a semi workaround i.e.
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{
using (cts.Token.Register(Thread.CurrentThread.Abort))
{
Try
{
Thread.Sleep(120000); // pretend web service call
}
Catch(ThreadAbortException ex)
{
// log etc.
}
Finally
{
// clean up here
}
}
});
but this will still result in an exception in the declaring thread.
All things considered, interrupt blocking calls using the parallel.loop constructs could have been a method on the options, avoiding the use of more obscure parts of the library. But why there is no option to cancel and avoid throwing an exception in the declaring method strikes me as a possible oversight.
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost';
does not work is quite simple : There is no grant called USAGE
.
The actual named grants are in the MySQL Documentation
The grant USAGE
is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user
where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE
. Running DROP USER 'phpmyadmin'@'localhost';
should work just fine. Under the hood, it's really doing this:
DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;
Therefore, the removal of a row from mysql.user
constitutes running REVOKE USAGE
, even though REVOKE USAGE
cannot literally be executed.
Fiddler listens to outbound requests rather than inbound requests so you're not going to be able to monitor all the requests coming in to your service by using Fiddler.
The best you're going to get with Fiddler is the ability to see all of the requests as they are generated by your Console App (assuming that the app generates web requests rather than using some other pipeline).
If you want a tool that is more powerful (but more difficult to use) that will allow you to monitor ALL incoming requests, you should check out WireShark.
Edit
I stand corrected. Thanks to Eric Law for posting the directions to configuring Fiddler to be a reverse proxy!
You need
char test[] = "abcde"; // This will add a terminating \0 character to the array
std::vector<std::string> v;
v.push_back(test);
Of if you meant to make a vector of character instead of a vector of strings,
std::vector<char> v(test, test + sizeof(test)/sizeof(*test));
The expression sizeof(test)/sizeof(*test)
is for calculating the number of elements in the array test.
Try this character set:
[ \t]
This does only match a space or a tabulator.
One more thing to make sure you have is the following set in your web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
This error occurs on an empty JSON file reading.
To avoid this error in NodeJS I'm checking the file's size:
const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;
Not sure of this is helpful but this what worked for me in Rails 4
Foo.where.not(bar: nil)
@Schildmeijer is largely right, however port 7001 is still used when using TLS Encrypted Internode communication
So my complete list would be for current versions of Cassandra:
A Java 8 example to convert a List<?>
of objects into a Map<k, v>
:
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));
//example 1
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));
System.out.println("Result 1 : " + result1);
//example 2
Map<Integer, String> result2 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
Code copied from:
https://www.mkyong.com/java8/java-8-convert-list-to-map/
I had same problem. After one day, I got it.
Problem was from adding two smtp
tags in mailSettings
under <system.net>
.
There are two kinds of cascades in Doctrine:
1) ORM level - uses cascade={"remove"}
in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.
2) Database level - uses onDelete="CASCADE"
on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:
@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")
I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.
Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]
What if you have a generic class that has methods that could be made ambiguous depending on the type arguments? I ran into this situation recently writing a two-way dictionary. I wanted to write symmetric Get()
methods that would return the opposite of whatever argument was passed. Something like this:
class TwoWayRelationship<T1, T2>
{
public T2 Get(T1 key) { /* ... */ }
public T1 Get(T2 key) { /* ... */ }
}
All is well good if you make an instance where T1
and T2
are different types:
var r1 = new TwoWayRelationship<int, string>();
r1.Get(1);
r1.Get("a");
But if T1
and T2
are the same (and probably if one was a subclass of another), it's a compiler error:
var r2 = new TwoWayRelationship<int, int>();
r2.Get(1); // "The call is ambiguous..."
Interestingly, all other methods in the second case are still usable; it's only calls to the now-ambiguous method that causes a compiler error. Interesting case, if a little unlikely and obscure.
None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!
They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.
Tip - if you right click on Applications > Netbeans and choose Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
function startTimer(duration, display) {_x000D_
var timer = duration, minutes, seconds;_x000D_
setInterval(function () {_x000D_
minutes = parseInt(timer / 60, 10);_x000D_
seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
if (--timer < 0) {_x000D_
timer = duration;_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
However if you want a more accurate timer that is only slightly more complicated:
function startTimer(duration, display) {_x000D_
var start = Date.now(),_x000D_
diff,_x000D_
minutes,_x000D_
seconds;_x000D_
function timer() {_x000D_
// get the number of seconds that have elapsed since _x000D_
// startTimer() was called_x000D_
diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
// does the same job as parseInt truncates the float_x000D_
minutes = (diff / 60) | 0;_x000D_
seconds = (diff % 60) | 0;_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
if (diff <= 0) {_x000D_
// add one second so that the count down starts at the full duration_x000D_
// example 05:00 not 04:59_x000D_
start = Date.now() + 1000;_x000D_
}_x000D_
};_x000D_
// we don't want to wait a full second before the timer starts_x000D_
timer();_x000D_
setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"
So with these things in mind lets write a better (but still very simple) CountDownTimer
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer
functions.
An example that displays the time in XX:XX format and restarts after reaching 00:00
An example that displays the time in two different formats
An example that has two different timers and only one restarts
An example that starts the count down timer when a button is pressed
Consider this array:
$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
To remove an element using the array key
:
// To unset an element from array using Key:
unset($arr["key2"]);
var_dump($arr);
// output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
To remove element by value
:
// remove an element by value:
$arr = array_diff($arr, ["value1"]);
var_dump($arr);
// output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
read more about array_diff: http://php.net/manual/en/function.array-diff.php
To remove an element by using index
:
array_splice($arr, 1, 1);
var_dump($arr);
// array(1) { ["key3"]=> string(6) "value3" }
read more about array_splice: http://php.net/manual/en/function.array-splice.php
You current regex will only match 1 character. you need either * (includes empty string) or + (at least one) to match multiple characters and numbers have a shortcut : \d (need \\ in a string).
word.matches("^[\\d,;]+$")
The Pattern documentation is pretty good : http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
Also you can try your regexps online at: http://www.regexplanet.com/simple/index.html
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
I think we can improve the best answer a little bit, I'm using:
len = sum(1 for _ in reader)
Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.
Offline mode could be set in Android Studio and in your project. To verify that gradle won't build your project in offline mode:
Use the Microsoft.VisualBasic.FileIO.TextFieldParser
class. This will handle parsing a delimited file, TextReader
or Stream
where some fields are enclosed in quotes and some are not.
For example:
using Microsoft.VisualBasic.FileIO;
string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";
TextFieldParser parser = new TextFieldParser(new StringReader(csv));
// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
parser.Close();
This should result in the following output:
2 1016 7/31/2008 14:22 Geoff Dalgas 6/5/2011 22:21 http://stackoverflow.com Corvallis, OR 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34
See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.
You need to add a reference to Microsoft.VisualBasic
in the Add References .NET tab.
Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:
[Unit]
Description=Python daemon
After=syslog.target
After=network.target
[Service]
Type=simple
User=<run as user>
Group=<run as group group>
ExecStart=/usr/bin/python <python script home>/script.py
# Give the script some time to startup
TimeoutSec=300
[Install]
WantedBy=multi-user.target
I prefer this method because a lot of the work is done for you, and then your daemon script behaves similarly to the rest of your system.
-Orby
I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.
This two threads explain it better:
Using writing-mode
and transform
.
.rotate {
writing-mode: vertical-lr;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
}
<span class="rotate">Hello</span>
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Cheers.
None of these resigning approaches were working for me, so I had to work out something else.
In my case, I had an IPA with an expired certificate. I could have rebuilt the app, but because we wanted to ensure we were distributing exactly the same version (just with a new certificate), we did not want to rebuild it.
Instead of the ways of resigning mentioned in the other answers, I turned to Xcode’s method of creating an IPA, which starts with an .xcarchive from a build.
I duplicated an existing .xcarchive and started replacing the contents. (I ignored the .dSYM file.)
I extracted the old app from the old IPA file (via unzipping; the app is the only thing in the Payload folder)
I moved this app into the new .xcarchive, under Products/Applications
replacing the app that was there.
I edited Info.plist
, editing
ApplicationProperties/ApplicationPath
ApplicationProperties/CFBundleIdentifier
ApplicationProperties/CFBundleShortVersionString
ApplicationProperties/CFBundleVersion
Name
I moved the .xcarchive into Xcode’s archive folder, usually /Users/xxxx/Library/Developer/Xcode/Archives
.
In Xcode, I opened the Organiser window, picked this new archive and did a regular (in this case Enterprise) export.
The result was a good IPA that works.
Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
Enter Only Numbers: _x000D_
<input type="text" id="onlynumbers">_x000D_
<br><br>_x000D_
Enter Only Alphabets: _x000D_
<input type="text" id="onlyalpha">_x000D_
<br><br>_x000D_
Enter other than Alphabets and numbers like special characters: _x000D_
<input type="text" id="speclchar">_x000D_
_x000D_
<script>_x000D_
$('#onlynumbers').keypress(function(e) {_x000D_
var letters=/^[0-9]/g; //g means global_x000D_
if(!(e.key).match(letters)) e.preventDefault();_x000D_
});_x000D_
_x000D_
$('#onlyalpha').keypress(function(e) {_x000D_
var letters=/^[a-z]/gi; //i means ignorecase_x000D_
if(!(e.key).match(letters)) e.preventDefault();_x000D_
});_x000D_
_x000D_
$('#speclchar').keypress(function(e) {_x000D_
var letters=/^[0-9a-z]/gi; _x000D_
if((e.key).match(letters)) e.preventDefault();_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **
<!DOCTYPE html>
$('#onlynumbers').keypress(function(e) {
var letters=/^[0-9]/g; //g means global
if(!(e.key).match(letters)) e.preventDefault();
});
$('#onlyalpha').keypress(function(e) {
var letters=/^[a-z]/gi; //i means ignorecase
if(!(e.key).match(letters)) e.preventDefault();
});
$('#speclchar').keypress(function(e) {
var letters=/^[0-9a-z]/gi;
if((e.key).match(letters)) e.preventDefault();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
Enter Only Numbers:
Enter Only Alphabets:
Enter other than Alphabets and numbers like special characters:
</body>
</html>
HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.
I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:
final RequestConfig params = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
httpPost.setConfig(params);
When a script generates an html form and that form's action http POSTs back to the same form.