I solved this problem using Bootstrap 4 Emdeds Utilities
https://getbootstrap.com/docs/4.3/utilities/embed
In this case you just need to add you image to a div.embbed-responsive
like this:
<div class="card">
<div class="embed-responsive embed-responsive-16by9">
<img alt="Card image cap" class="card-img-top embed-responsive-item" src="img/butterPecan.jpg" />
</div>
<div class="card-block">
<h4 class="card-title">Butter Pecan</h4>
<p class="card-text">Roasted pecans, butter and vanilla come together to make this wonderful ice cream</p>
</div>
</div>
All images will fit the ratio specified by modifier classes:
.embed-responsive-21by9
.embed-responsive-16by9
.embed-responsive-4by3
.embed-responsive-1by1
Aditionally this css enables zoom instead of image stretching
.embed-responsive .card-img-top {
object-fit: cover;
}
In my case, WebStrom auto-complete inserted lowercased *ngfor
, even when it looks like you choose the right camel cased one (*ngFor
).
This Statement used in Angular2 Beta version.....
Hereafter use let instead of #
let keyword is used to declare local variable
It's a syntax issue related to imports/exports in your files, mine resolved by removing an extra quote from my import
<Route path={`${match.path}/iso-line-number`} component={ISOLineNumber} />
Full CSS support is exactly the reason this huge amount of CSSinJS libraries, to do this efficiently, you need to generate actual CSS, not inline styles. Also inline styles are much slower in react in a bigger system. Disclaimer - I maintain JSS.
Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover
via onMouseEnter
and onMouseLeave
to using more elements to reproduce pseudo-elements like :after
and :before
to just use an external stylesheet.
Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.
Imagine a large team wherein each developer is recreating CSS features like :hover
. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.
So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).
Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after
:
npm install style-it --save
Functional Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`,
<div id="heart" />
);
}
}
export default Intro;
JSX Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before,
#heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
-moz-border-radius: 50px 50px 0 0;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
`}
<div id="heart" />
</Style>
}
}
export default Intro;
Heart example pulled from CSS-Tricks
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:
This will turn off interrupts and put the CPU into (permanent until reset/power toggled) sleep:
cli();
sleep_enable();
sleep_cpu();
See also http://arduino.land/FAQ/content/7/47/en/how-to-stop-an-arduino-sketch.html, for more details.
I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.
To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:
Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.
for me i solved it like the following In Visual Studio 2015 : From View menu click Other Windows then click Package Manager Console then run the following commands :
PM> enable-migrations
Migrations have already been enabled in project 'mvcproject'. To overwrite the existing migrations configuration, use the -Force parameter.
PM> enable-migrations -Force
Checking if the context targets an existing database... Code First Migrations enabled for project mvcproject.
then add the migration name under the migration folder it will add the class you need in Solution Explorer by run the following command
PM>Add-migration AddColumnUser
Finally update the database
PM> update-database
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
It is possible to construct a struct inside the function arguments:
function({ .variable = PUT_DATA_HERE });
Maybe the following helps you.
arraylistname.get(position);
It sounds like the only varaible stored in the .RData
file was one named isfar
.
Are you really sure that you saved the table? The command should have been:
save(the_table, file = "isfar.RData")
There are many ways to examine a variable.
Type it's name at the command prompt to see it printed. Then look at str
, ls.str
, summary
, View
and unclass
.
I made a solution based in part by the information above. I just set the titleLabel.text to the string I want to pass, and set the titleLabel.hidden = YES
Like this :
UIButton *imageclick = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
imageclick.frame = photoframe;
imageclick.titleLabel.text = [NSString stringWithFormat:@"%@.%@", ti.mediaImage, ti.mediaExtension];
imageclick.titleLabel.hidden = YES;
This way, there is no need for a inheritance or category and there is no memory leak
Just come across this, the answer is simple, use ISNULL
. SQL won't return rows if the field you are testing has no value (in some of the records) when doing a text comparison search, eg:
WHERE wpp.comment NOT LIKE '%CORE%'
So, you have temporarily substitute a value in the null
(empty) records by using the ISNULL
command, eg
WHERE (ISNULL(wpp.comment,'')) NOT LIKE '%CORE%'
This will then show all your records that have nulls and omit any that have your matching criteria. If you wanted, you could put something in the commas to help you remember, eg
WHERE (ISNULL(wpp.comment,'some_records_have_no_value')) NOT LIKE '%CORE%'
Simulation = For analysis and study
Emulation = For usage as a substitute
A simulator is an environment which models but an emulator is one that replicates the usage as on the original device or system.
Simulator mimics the activity of something that it is simulating. It "appears"(a lot can go with this "appears", depending on the context) to be the same as the thing being simulated. For example the flight simulator "appears" to be a real flight to the user, although it does not transport you from one place to another.
Emulator, on the other hand, actually "does" what the thing being emulated does, and in doing so it too "appears to be doing the same thing". An emulator may use different set of protocols for mimicking the thing being emulated, but the result/outcome is always the same as the original object. For example, EMU8086 emulates the 8086 microprocessor on your computer, which obviously is not running on 8086 (= different protocols), but the output it gives is what a real 8086 would give.
You can't detect it with javascript.
Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.
But you could make an own link for every from url.
Example: http://example.com?auth=holasite
In this example your site is: example.com
If somebody open that link it's give you the holasite value for the auth variable.
Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.
Like: $holasite = http://holasite.com (You could use mysql too..)
And just match it, and you have the url.
This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.
In my scenario, I want to update the status of status based on his id
student_obj = StudentStatus.objects.get(student_id=101)
student_obj.status= 'Enrolled'
student_obj.save()
Or If you want the last id from Student_Info table you can use the following.
student_obj = StudentStatus.objects.get(student_id=StudentInfo.objects.last().id)
student_obj.status= 'Enrolled'
student_obj.save()
If the global variable should not be written to by anything, including Vuejs, you can use Object.freeze
to freeze your object. Adding it to Vue's viewmodel won't unfreeze it.
Another option is to provide Vuejs with a frozen copy of the object, if the object is intended to be written globally but just not by Vue: var frozenCopy = Object.freeze(Object.assign({}, globalObject))
Using portecle :
SELECT CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
WHEN SERVERPROPERTY('EditionID') = -2117995310 THEN 'Developer'
WHEN SERVERPROPERTY('EditionID') = 610778273 THEN 'Windows Embedded SQL'
WHEN SERVERPROPERTY('EditionID') = 4161255391 THEN 'Express with Advanced Services'
END AS 'Edition';
Swift 3 / 4 / 5.1
Here is a simple String
extension, allowing for preserving optionals in the event of an error when decoding.
extension String {
/// Encode a String to Base64
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
/// Decode a String from Base64. Returns nil if unsuccessful.
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else { return nil }
return String(data: data, encoding: .utf8)
}
}
Example:
let testString = "A test string."
let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="
guard let decoded = encoded.fromBase64() // "A test string."
else { return }
A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.
I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.
To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.
This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:
More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.
The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.
Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv
This MsvcLibX library is by no means complete, and contributions for improving it are welcome!
Here is the small example
public class TryWithResource {
public static void main(String[] args) {
try (TestMe r = new TestMe()) {
r.generalTest();
} catch(Exception e) {
System.out.println("From Exception Block");
} finally {
System.out.println("From Final Block");
}
}
}
public class TestMe implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println(" From Close - AutoCloseable ");
}
public void generalTest() {
System.out.println(" GeneralTest ");
}
}
Here is the output:
GeneralTest
From Close - AutoCloseable
From Final Block
Check npm config by command:
npm config list
It needs properties: "prefix", global "prefix" and "node bin location".
; userconfig C:\Users\username\.npmrc
cache = "C:\\ProgramData\\npm-cache"
msvs_version = "2015"
prefix = "C:\\ProgramData\\npm"
python = "C:\\Python27\\"
registry = "http://registry.com/api/npm/npm-packages/"
; globalconfig C:\ProgramData\npm\etc\npmrc
cache = "C:\\ProgramData\\npm-cache"
prefix = "C:\\ProgramData\\npm"
; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
In this case it needs to add these paths to the end of environment variable PATH:
;C:\Program Files\nodejs;C:\ProgramData\npm;
Just added ignore: []
in the specific page for the specific form, this solution worked for me.
$("#form_name").validate({
ignore: [],
onkeyup: false,
rules: {
},
highlight:false,
});
Do NOT have trailing commas in your OBJECT (JSON is a string notation)
UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing
var data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.
data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
_x000D_
Using Date object guarantees that. For eg if you try to create April 31st
:
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is
0
, Feb. is1
etc.
You need to try one of the following:
They offer many more features and will be easier to get what you are looking for.
I prefer the clean formatting of yaml
:
import yaml
print(yaml.dump(cars))
output:
A:
color: 2
speed: 70
B:
color: 3
speed: 60
Node.js 0.8 has fs.appendFile
:
fs.appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If someone uses selenide:
public static final Long SHORT_WAIT = 5000L; // 5 seconds
$("some_css_selector").waitUntil(Condition.appear, SHORT_WAIT);
More Conditions can be found here: http://selenide.org/javadoc/3.0/com/codeborne/selenide/Condition.html
You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" id="myButton" value="Add"/>
</form>
</body>
</html>
JQuery
var button_my_button = "#myButton";
$(button_my_button).click(function(){
window.location.href='Students.html';
});
Javascript
//get a reference to the element
var myBtn = document.getElementById('myButton');
//add event listener
myBtn.addEventListener('click', function(event) {
window.location.href='Students.html';
});
See comments why avoid inline scripting and also why inline scripting is bad
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers
I have tested this method with content://com.adobe.scan.android.documents/document/
The LLVM Compiler Infrastructure is particularly useful for performing optimizations and transformations on code. It also consists of a number of tools serving distinct usages. llvm-prof is a profiling tool that allows you to do profiling of execution in order to identify program hotspots. Opt is an optimization tool that offers various optimization passes (dead code elimination for instance).
Importantly LLVM provides you with the libraries, to write your own Passes. For instance if you require to add a range check on certain arguments that are passed into certain functions of a Program, writing a simple LLVM Pass would suffice.
For more information on writing your own Pass, check this http://llvm.org/docs/WritingAnLLVMPass.html
if you want to strip all tags, then try this
function:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
usage:
var newText=$('selector').html().stripTags();
this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.
for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.
PS: but like I said, this might be totally unrelated to your query :)
More about "load average" showing CPU load over 1 minute, 5 minutes and 15 minutes
Linux, Mac, and other Unix-like systems display “load average” numbers. These numbers tell you how busy your system’s CPU, disk, and other resources are. They’re not self-explanatory at first, but it’s easy to become familiar with them.
WIKI: example, one can interpret a load average of "1.73 0.60 7.98" on a single-CPU system as:
during the last minute, the system was overloaded by 73% on average (1.73 runnable processes, so that 0.73 processes had to wait for a turn for a single CPU system on average).
during the last 5 minutes, the CPU was idling 40% of the time on average.
during the last 15 minutes, the system was overloaded 698% on average (7.98 runnable processes, so that 6.98 processes had to wait for a turn for a single CPU system on average) if dual core mean: 798% - 200% = 598%.
You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.
To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.
more info : Link
Welcome to the fickle world of SQL Server log management.
SOMETHING is wrong, though I don't think anyone will be able to tell you more than that without some additional information. For example, has this database ever been used for Transactional SQL Server replication? This can cause issues like this if a transaction hasn't been replicated to a subscriber.
In the interim, this should at least allow you to kill the log file:
You should now be able to shrink the files (if performing the backup didn't do that for you).
Good luck!
this code works and dont throw any exception:
Session.Abandon();
Session["tempKey1"] = "tempValue1";
One thing to note here that Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request. That simply means that suppose you tried to access value in code just after the session.abandon command was executed, it will be still there. So do not get confused if your code is just not working even after issuing session.abandon command and immediately doing some logic with the session.
I have found that %CD%
gives the path the script was called from and not the path of the script, however, %~dp0
will give the path of the script itself.
I've managed to get this working by the following fix:
//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720
You video should have the hd720 resolution to do so.
I was using the embedding via iframe, BTW. Hope someone will find this helpful.
The solution that worked for me is:
suptitle()
for the actual titletitle()
for the subtitle and adjust it using the optional parameter y
: import matplotlib.pyplot as plt
"""
some code here
"""
plt.title('My subtitle',fontsize=16)
plt.suptitle('My title',fontsize=24, y=1)
plt.show()
There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y
until you get it right.
If you'd like to add text at the end of each line in-place (in the same file), you can use -i
parameter, for example:
sed -i'.bak' 's/$/:80/' foo.txt
However -i
option is non-standard Unix extension and may not be available on all operating systems.
So you can consider using ex
(which is equivalent to vi -e
/vim -e
):
ex +"%s/$/:80/g" -cwq foo.txt
which will add :80
to each line, but sometimes it can append it to blank lines.
So better method is to check if the line actually contain any number, and then append it, for example:
ex +"g/[0-9]/s/$/:80/g" -cwq foo.txt
If the file has more complex format, consider using proper regex, instead of [0-9]
.
public bool IsCollection<T>(T value){
var valueType = value.GetType();
return valueType.IsArray() || typeof(IEnumerable<object>).IsAssignableFrom(valueType) || typeof(IEnumerable<T>).IsAssignableFrom(valuetype);
}
When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List.
Not as complicated as it sounds.... Just leave the duplicate primary key out of your query.... this works for me !
INSERT INTO
Content(
`status`,
content_category,
content_type,
content_id,
user_id,
title,
description,
content_file,
content_url,
tags,
create_date,
edit_date,
runs
)
SELECT `status`,
content_category,
content_type,
content_id,
user_id,
title,
description,
content_file,
content_url,
tags,
create_date,
edit_date,
runs
FROM
Content_Images
There are many possibilities to solve this task.
The easiest solution is running the batch file with full path.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
Once end of batch file Template.bat
is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.
The current directory for the batch file Template.bat
is the current directory of the current process. In case of Template.bat
requires that the directory of this batch file is the current directory, the batch file Template.bat
should contain after @echo off
as second line the following command line:
cd /D "%~dp0"
Run in a command prompt window cd /?
for getting displayed the help of this command explaining parameter /D
... change to specified directory also on a different drive.
Run in a command prompt window call /?
for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0
... drive and path of argument 0 which is the name of the batch file.
Another solution is calling the batch file with full path.
call "F:\- Big Packets -\kitterengine\Common\Template.bat"
The difference to first solution is that after end of batch file Template.bat
is reached the batch processing continues in batch script containing this command line.
For the current directory read above.
There are 3 operators for running multiple commands on one command line: &
, &&
and ||
.
For details see answer on Single line with multiple commands using Windows batch file
I suggest for this task the &&
operator.
cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat
As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat
is successful.
This command line changes the directory and on success calls the batch file.
cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat
The difference to third solution is the return to current batch script on exiting processing of Template.bat
.
The four solutions above change the current directory and it is unknown what Template.bat
does regarding
In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat
changes on environment for itself, it is advisable to use setlocal
and endlocal
.
Run in a command prompt window setlocal /?
and endlocal /?
for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.
setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal
Now there is only &
instead of &&
used as it is important here that after setlocal
is executed the command endlocal
is finally also executed.
ONE MORE NOTE
If batch file Template.bat
contains the command exit
without parameter /B
and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat
contains exit /B
or goto :EOF
instead of just exit
if there is exit
used at all in this batch file.
You can use the following command to update the DATA PUMP DIRECTORY path,
create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';
For me data path correction was required as I have restored the my database from production to test environment.
Same command can be used to create a new DATA PUMP DIRECTORY
name
and path
.
var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";
Try this:
<script>
var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
this.window.close();
</script>
This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.
For me there was an issue in that I want to distinguish between alpha, numeric and alpha numeric, so to ensure an alphanumeric string contains at least one alpha and at least one numeric, I used :
^([a-zA-Z_]{1,}\d{1,})+|(\d{1,}[a-zA-Z_]{1,})+$
give the same command as you used to give while installing a single module only pass it via space delimited format
PHP doesn't really get compiled as with many programs. You can use Zend's encoder to make it unreadable though.
char* str = "blablabla";
You should not modify this string at all. It resides in implementation defined read only region. Modifying it causes Undefined Behavior.
You need a char array not a string literal.
Good Read:
What is the difference between char a[] = "string"; and char *p = "string";
I hope it's simple and pythonic enough:
def is_valid_ip(ip):
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))
If you are inside of Spring bean (in this case @Controller
bean) you shouldn't use Spring context instance at all. Just autowire className
bean directly.
BTW, avoid using field injection as it's considered as bad practice.
Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("param1", "somevalue")
reqparm.Add("param2", "othervalue")
Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using
The key part is this:
client.UploadValues(someurl, "POST", reqparm)
It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
$.ajax({
url:"",
type: "POST",
data: new FormData($('#uploadDatabaseForm')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
What I do so I don't specify a time zone is,
System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());
gives
ldt 1424812121078
ctm 1424812121281
As you can see the numbers are the same except for a small execution time.
Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
Thank you guys for all your help! Finally I was able to make it work perfectly thanks to a friend and also you! Here is the final code so you can also see how we solve it.
Thanks again!
Option Explicit
Sub k()
Dim x As Integer, i As Integer, a As Integer
Dim name As String
'name = InputBox("Please insert the name of the sheet")
i = 1
name = "Reserva"
Sheets(name).Cells(4, 57) = Sheets(name).Cells(4, 56)
On Error GoTo fim
x = Sheets(name).Cells(4, 56).Value
Application.Calculation = xlCalculationManual
Do While Not IsEmpty(Sheets(name).Cells(i + 4, 56))
a = 0
If Sheets(name).Cells(4 + i, 56) <> x Then
If Sheets(name).Cells(4 + i, 56) <> 0 Then
If Sheets(name).Cells(4 + i, 56) = 3 Then
a = x
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - x
x = Cells(4 + i, 56) - x
End If
Sheets(name).Cells(4 + i, 57) = Sheets(name).Cells(4 + i, 56) - a
x = Sheets(name).Cells(4 + i, 56) - a
Else
Cells(4 + i, 57) = ""
End If
Else
Cells(4 + i, 57) = ""
End If
i = i + 1
Loop
Application.Calculation = xlCalculationAutomatic
Exit Sub
fim:
MsgBox Err.Description
Application.Calculation = xlCalculationAutomatic
End Sub
Install nmap,
sudo apt-get install nmap
then
nmap -sP 192.168.1.*
or more commonly
nmap -sn 192.168.1.0/24
will scan the entire .1 to .254 range
This does a simple ping scan in the entire subnet to see which hosts are online.
Run this command line on your preferred shell session:
db2 "select tabname from syscat.tables where owner = 'DB2INST1'"
Maybe you'd like to modify the owner name, and need to check the list of current owners?
db2 "select distinct owner from syscat.tables"
In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.
Here is an example I have just written to demonstrate how you could do it using deferreds/promises.
Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.
Hope this helps!
$(function(){
function1().done(function(){
// function1 is done, we can now call function2
console.log('function1 is done!');
function2().done(function(){
//function2 is done
console.log('function2 is done!');
});
});
});
function function1(){
var dfrd1 = $.Deferred();
var dfrd2= $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function1 is done!');
dfrd1.resolve();
}, 1000);
setTimeout(function(){
// doing more async stuff
console.log('task 2 in function1 is done!');
dfrd2.resolve();
}, 750);
return $.when(dfrd1, dfrd2).done(function(){
console.log('both tasks in function1 are done');
// Both asyncs tasks are done
}).promise();
}
function function2(){
var dfrd1 = $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function2 is done!');
dfrd1.resolve();
}, 2000);
return dfrd1.promise();
}
I can give you two advices:
Your values
object is obviously an Object[]
containing a String[]
containing the values.
String[] stringValues = (String[])values[0];
About the question of the regular expression methods to parse (x)HTML, the answer to all of the ones who spoke about some limits is: you have not been trained enough to rule the force of this powerful weapon, since nobody here spoke about recursion.
A regular expression-agnostic colleague notified me this discussion, which is not certainly the first on the web about this old and hot topic.
After reading some posts, the first thing I did was looking for the "?R" string in this thread. The second was to search about "recursion".
No, holy cow, no match found. Since nobody mentioned the main mechanism a parser is built onto, I was soon aware that nobody got the point.
If an (x)HTML parser needs recursion, a regular expression parser without recursion is not enough for the purpose. It's a simple construct.
The black art of regular expressions is hard to master, so maybe there are further possibilities we left out while trying and testing our personal solution to capture the whole web in one hand... Well, I am sure about it :)
Here's the magic pattern:
$pattern = "/<([\w]+)([^>]*?)(([\s]*\/>)|(>((([^<]*?|<\!\-\-.*?\-\->)|(?R))*)<\/\\1[\s]*>))/s";
Just try it. It's written as a PHP string, so the "s" modifier makes classes include newlines.
Here's a sample note on the PHP manual I wrote in January: Reference
(Take care. In that note I wrongly used the "m" modifier; it should be erased, notwithstanding it is discarded by the regular expression engine, since no ^
or $
anchoring was used).
Now, we could speak about the limits of this method from a more informed point of view:
Anyhow, it is only a regular expression pattern, but it discloses the possibility to develop of a lot of powerful implementations.
I wrote this pattern to power the recursive descent parser of a template engine I built in my framework, and performances are really great, both in execution times or in memory usage (nothing to do with other template engines which use the same syntax).
The advantages of EditorFor
is that your code is not tied to an <input type="text"
. So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div
you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml
) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
Use a SortedSet (TreeSet is the default one):
SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);
No extra sorting code needed.
Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:
new TreeSet<String>(Comparator.comparing(Integer::valueOf));
Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)
Reference:
TreeSet
Comparator
This is a very old post, but I thought I should post my solution of a similar problem I faced recently.
Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.
<style>_x000D_
tr {_x000D_
display: block;_x000D_
padding-bottom: 20px;_x000D_
}_x000D_
table {_x000D_
border: 1px solid red;_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<h2>Lorem Ipsum</h2>_x000D_
<p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
</p>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
This thread is a little old, and I am brand new to this, but I think I found the preferred solution.
First, I assume that you are using Eclipse and the Android ADT plugin.
In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.
When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.
Think of Observables as a pipe with flowing water in it, sometimes water flows and sometimes it doesn't. In some cases, you may actually need a pipe that has always water in it, you can do this by creating a special pipe which always contains a water no matter how small it is, lets call this special pipe BehaviorSubject, if you happens to be a water supply provider in your community, you can sleep peacefully at night knowing that your newly installed pipe just works.
In technical terms: you may encounter usescases where an Observable should always have value in it, perhaps you want to capture the value of a input text over time, you can then create an instance of BehaviorSubject to ensure this kind of behavior, lets say:
const firstNameChanges = new BehaviorSubject("<empty>");
// pass value changes.
firstNameChanges.next("Jon");
firstNameChanges.next("Arya");
You can then use "value" to sample changes over time.
firstNameChanges.value;
This comes handy when you combine Observables later, by taking a look at the type of your stream as BehaviorSubject you can then ensure that the stream at least fires or signal just once atleast.
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
This is the best tool that you can use for all views and its FREE many thanks to @Jérôme Van Der Linden.
The Android Holo Colors Generator allows you to easily create Android components such as EditText
or spinner with your own colours for your Android application. It will generate all necessary nine patch assets plus associated XML drawable and styles which you can copy straight into your project.
http://android-holo-colors.com/
UPDATE 1
This domain seems expired but the project is an open source you can find here
https://github.com/jeromevdl/android-holo-colors
try it
this image put in the background of EditText
android:background="@drawable/textfield_activated"
UPDATE 2
For API 21 or higher, you can use android:backgroundTint
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Underline color change"
android:backgroundTint="@android:color/holo_red_light" />
Update 3
Now We have with back support AppCompatEditText
Note: We need to use app:backgroundTint instead of android:backgroundTint
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Underline color change"
app:backgroundTint="@color/blue_gray_light" />
Update 4 AndroidX version
<androidx.appcompat.widget.AppCompatEditText
app:backgroundTint="@color/blue_gray_light" />
https://jsfiddle.net/SyedFayaz/ud0mpgoh/7/
<table class="table-bordered">
<col />
<col />
<col />
<colgroup span="4"></colgroup>
<col />
<tr>
<th rowspan="2" style="vertical-align: middle; text-align: center">
S.No.
</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">Item</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">
Description
</th>
<th
colspan="3"
style="horizontal-align: middle; text-align: center; width: 50%"
>
Items
</th>
<th rowspan="2" style="vertical-align: middle; text-align: center">
Rejected Reason
</th>
</tr>
<tr>
<th scope="col">Order</th>
<th scope="col">Received</th>
<th scope="col">Accepted</th>
</tr>
<tr>
<th>1</th>
<td>Watch</td>
<td>Analog</td>
<td>100</td>
<td>75</td>
<td>25</td>
<td>Not Functioning</td>
</tr>
<tr>
<th>2</th>
<td>Pendrive</td>
<td>5GB</td>
<td>250</td>
<td>165</td>
<td>85</td>
<td>Not Working</td>
</tr>
</table>
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.
Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.
...
Another quick lookup table is available at this github page
Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this
This method works fine for me:
private void alert(string message)
{
Response.Write("<script>alert('" + message + "')</script>");
}
Example:
protected void Page_Load(object sender, EventArgs e)
{
alert("Hello world!");
}
And when your page load yo will see something like this:
I'm using .NET Framework 4.5 in Firefox.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
As of CMake Wiki:
CMAKE_BINARY_DIR if you are building in-source, this is the same as CMAKE_SOURCE_DIR, otherwise this is the top level directory of your build tree
Compare these two variables to determine if out-of-source build was started
The jquery.selectboxes.js plugin has a sort method. You can implement the plugin, or dive into the code to see a way to sort the options.
The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':
You could also try:
import csv
import pandas as pd
import re
with open (filename, "r") as file:
df = pd.read_csv(file, delimiter = ",")
df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
print(df.columns)
My version for kotlin looks like the following:
PreferenceManager.getDefaultSharedPreferences(this).apply {
// Check if we need to display our OnboardingSupportFragment
if (!getBoolean("wasAppStartedPreviously", false)) {
// The user hasn't seen the OnboardingSupportFragment yet, so show it
startActivity(Intent(this@SplashScreenActivity, AppIntroActivity::class.java))
} else {
startActivity(Intent(this@SplashScreenActivity, MainActivity::class.java))
}
}
Please don't let the question of "which one is faster" be the deciding factor of which to use. Chances are you're never going to care that much, and besides, programmer reading time is far more expensive than machine time.
Use whichever makes most sense to the human reading the code.
This could be achieved with a hook. However, I would not recommend it, as it strictly couples state and layout.
const useInput = (placeholder, initial) => {
const [value, setVal] = useState(initial)
const onChange = (e) => setVal(e.target.value)
const element = <input value={value} onChange={onChange} placeholder={placeholder}/>
return {element, value}
}
Use it in any functional component
const BensPlayGround = () => {
const name = useInput("Enter name here")
return (
<>
{name.element}
<h1>Hello {name.value}</h1>
</>
)
}
const useDataBind = () => {
const [value, setVal] = useState("")
const onChange = (e) => setVal(e.target.value)
return {value, onChange}
}
const Demo = (props) => {
const nameProps = useDataBind()
return (
<>
<input {...nameProps} placeholder="Enter name here" />
<h1>Hello {nameProps.value}</h1>
</>
)
}
I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.
Problems I observed:
They save the instance of Fragment
which is replaced. In my case, it is a Fragment which holds MapView
and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED)
instead of Fragment
itself.
Here is my implementation.
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
private SwitchFragListener mSwitchFragListener;
private Switch mToggle;
private int pagerAdapterPosChanged = POSITION_UNCHANGED;
private static final int TOGGLE_ENABLE_POS = 2;
public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
super(fm);
mToggle = toggle;
mSwitchFragListener = new SwitchFragListener();
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSwitchFragListener.onSwitchToNextFragment();
}
});
}
@Override
public Fragment getItem(int i) {
switch (i)
{
case TOGGLE_ENABLE_POS:
if(mToggle.isChecked())
{
return TabReplaceFragment.getInstance();
}else
{
return DemoTab2Fragment.getInstance(i);
}
default:
return DemoTabFragment.getInstance(i);
}
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + (position + 1);
}
@Override
public int getItemPosition(Object object) {
// This check make sures getItem() is called only for the required Fragment
if (object instanceof TabReplaceFragment
|| object instanceof DemoTab2Fragment)
return pagerAdapterPosChanged;
return POSITION_UNCHANGED;
}
/**
* Switch fragments Interface implementation
*/
private final class SwitchFragListener implements
SwitchFragInterface {
SwitchFragListener() {}
public void onSwitchToNextFragment() {
pagerAdapterPosChanged = POSITION_NONE;
notifyDataSetChanged();
}
}
/**
* Interface to switch frags
*/
private interface SwitchFragInterface{
void onSwitchToNextFragment();
}
}
Demo link here.. https://youtu.be/l_62uhKkLyM
For demo purpose, used 2 fragments TabReplaceFragment
and DemoTab2Fragment
at position two. In all the other cases I'm using DemoTabFragment
instances.
Explanation:
I'm passing Switch
from Activity to the DemoCollectionPagerAdapter
. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener
's onSwitchToNextFragment
method, where I'm changing the value of pagerAdapterPosChanged
variable to POSITION_NONE
. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.
Once again big thanks to @wize and @mdelolmo for the original idea.
Hope this is helpful. :)
Let me know if this implementation has any flaws. That will be greatly helpful for my project.
If you don't have the .PBO
file:
C#
public int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
Vb.net
Public Function GetLineNumber(ByVal ex As Exception)
Dim lineNumber As Int32 = 0
Const lineSearch As String = ":line "
Dim index = ex.StackTrace.LastIndexOf(lineSearch)
If index <> -1 Then
Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
If Int32.TryParse(lineNumberText, lineNumber) Then
End If
End If
Return lineNumber
End Function
Or as an extentions on the Exception class
public static class MyExtensions
{
public static int LineNumber(this Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
I have found that, with zsh5 (the default one on Debian Jessie), all those solutions works:
$'\e[00m
$fg[white]
$fg{white}
Now, they have a problem: they will move the cursor, resulting in ugly decal when tabbing (for auto-completion). The solution is simply to surround the escape sequences with %{FOOBAR%}
. Took me a while to figure this.
For 2nd and 3rd solutions loading colors
module is mandatory.
To keep the 1st solution readable, just define variables for the colors you use.
Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).
The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.
Please follow the steps as mentioned below.
Visit the standard URL www.visualstudio.com/downloads
Scroll down and click on encircled below as shown in snapshot down
After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Join
Problem is if you type /public and it will still be available in the url, therefor i created a fix which should be placed in the public/index.php
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
if(stristr($uri, '/public/') == TRUE) {
if(file_exists(__DIR__.'/public'.$uri)){
}else{
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$actual_link = str_replace('public/', '',$actual_link);
header("HTTP/1.0 404 Not Found");
header("Location: ".$actual_link."");
exit();
return false;
}}
this peace of code will remove public from the url and will give a 404 and then redirects to the url without the public
Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.
Edit
Further information:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
keytool
.public function boot()
{
if(config('app.debug')!=true) {
\URL::forceScheme('https');
}
}
in app/Providers/AppServiceProvider.php
My answer provides a ways to run a subset of test in different scenarios.
pytest
To run all the tests from one directory, use the directory as a parameter to
pytest
:
pytest tests/my-directory
To run a file full of tests, list the file with the relative path as a parameter to pytest
:
pytest tests/my-directory/test_demo.py
To run a single test function, add ::
and the test function name:
pytest -v tests/my-directory/test_demo.py::test_specific_function
-v
is used so you can see which function was run.
To run just a class, do like we did with functions and add ::
, then the class name to the file parameter:
pytest -v tests/my-directory/test_demo.py::TestClassName
If you don't want to run all of a test class, just one method, just add
another ::
and the method name:
pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method
The -k
option enables you to pass in an expression to run tests that have
certain names specified by the expression as a substring of the test name.
It is possible to use and, or, and not to create complex expressions.
For example, to run all of the functions that have _raises in their name:
pytest -v -k _raises
try this:
$('div[id^="player_"]')
They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT
under the hood).
If one of them is faster, it's going to be DISTINCT
. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY
is not taking advantage of any group members, just their keys. DISTINCT
makes this explicit, so you can get away with a slightly dumber optimizer.
When in doubt, test!
test.matches() method checks all text.use test.find()
If you need to split something into 3 pieces, such as an email address and you don't know the length of the middle part, try this (I just ran this on sqlserver 2012 so I know it works):
SELECT top 2000
emailaddr_ as email,
SUBSTRING(emailaddr_, 1,CHARINDEX('@',emailaddr_) -1) as username,
SUBSTRING(emailaddr_, CHARINDEX('@',emailaddr_)+1, (LEN(emailaddr_) - charindex('@',emailaddr_) - charindex('.',reverse(emailaddr_)) )) domain
FROM
emailTable
WHERE
charindex('@',emailaddr_)>0
AND
charindex('.',emailaddr_)>0;
GO
Hope this helps.
I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket>
connection settings.
I set the headers object on my client-side script with the following options:
/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
method: 'OPTIONS',
credentials: "include",
body: JSON.stringify(data),
cors: 'cors',
headers: head, //could be object literal too
cache: 'default'
})
.then(response=>{
....
}).catch(err=>{...});
And on my express server I setup my router as follows:
router.head('absolute or regex', (request, response, next)=>{
req.setTimeout(1000*60*5, ()=>{
console.info("socket timed out");
});
console.info("Proceeding down the middleware chain link...\n\n");
next();
});
/*Keep the socket alive by enabling it on the server, with an optional
delay on the last packet sent
*/
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))
WARNING
Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.
I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.
for (var key in validation_messages) {
// skip loop if the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var obj = validation_messages[key];
for (var prop in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(prop)) continue;
// your code
alert(prop + " = " + obj[prop]);
}
}
Another alternative is
dtColumns[index].visible = false/true;
To show or hide any column.
Using Gradle or Android Studio, try adding a dependency on com.android.support:cardview-v7
.
There does not seem to be a regular Android library project at this time for cardview-v7
, leanback-v17
, palette-v7
, or recyclerview-v7
. I have no idea if/when Google will ship such library projects.
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst()
does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String
class' charAt()
method, and then use Character.toUpperCase()
to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea
to an upper case character.
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
I had the same issue with oracle returning scientic notation, but I needed the actual number for a url. I just used a PHP trick by subtracting zero, and I get the correct number.
for example 5.4987E7 is the val.
newval = val - 0;
newval now equals 54987000
$@
is all of the parameters passed to the script.
For instance, if you call ./someScript.sh foo bar
then $@
will be equal to foo bar
.
If you do:
./someScript.sh foo bar
and then inside someScript.sh
reference:
umbrella_corp_options "$@"
this will be passed to umbrella_corp_options
with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.
Your manage.py
is "wrong"; I don't know where you got it from, but that's not a 1.7 manage.py
- were you using some funky pre-release build or something?
Reset your manage.py
to the conventional, as below, and things Should Just Work:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
You are using a local path. Is that really what you want? If it is, you need to use the file:///
prefix:
file:///H:/media/css/static/img/sprites/buttons-v3-10.png
obviously, this will work only on your local computer.
Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://
, https://
) pages has been widely disabled due to security reasons.
The post needs an update after the links
option is deprecated.
Basically, links
is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network
. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.
For docker run
, --link
is also deprecated and should be replaced by a custom network.
docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image
depends_on
expresses start order (and implicitly image pulling order), which was a good side effect of links
.
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
In iOS 4 and later, there's a way to do this just using the UIView transition method without needing to import QuartzCore. You can just say:
[UIView transitionWithView:button
duration:0.4
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
button.hidden = YES;
}
completion:NULL];
UIView.transition(with: button, duration: 0.4,
options: .transitionCrossDissolve,
animations: {
button.hidden = false
})
Michail's solution will work, but it's not actually the best approach.
The problem with alpha fading is that sometimes the different overlapping view layers look weird as they fade out. There are some other alternatives using Core Animation. First include the QuartzCore framework in your app and add #import <QuartzCore/QuartzCore.h>
to your header. Now you can do one of the following:
1) set button.layer.shouldRasterize = YES;
and then use the alpha animation code that Michail provided in his answer. This will prevent the layers from blending weirdly, but has a slight performance penalty, and can make the button look blurry if it's not aligned exactly on a pixel boundary.
Alternatively:
2) Use the following code to animate the fade instead:
CATransition *animation = [CATransition animation];
animation.type = kCATransitionFade;
animation.duration = 0.4;
[button.layer addAnimation:animation forKey:nil];
button.hidden = YES;
The nice thing about this approach is you can crossfade any property of the button even if they aren't animatable (e.g. the text or image of the button), just set up the transition and then set your properties immediately afterwards.
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
Option 3
To update current iframe
$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');
Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...
So for example the code below throw an error:
print( "Alireza" + 1980)
like this:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str
To solve the issue, just add str to your number or value like:
print( "Alireza" + str(1980))
And the result as:
Alireza1980
Try this one:
find . -type f -printf "%T@ %p\n" | sort -nr | cut -d\ -f2-
The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with
conda install -c anaconda pandas
Unfortunately I do not know how to help with Eclipse.
Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)
You make these changes to your ~/.gitconfig
:
[diff]
tool = diffmerge
[difftool "diffmerge"]
cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE
This will fix the diff tool. You can also fix this without editing the ~/.gitconfig
directly by entering these commands from the terminal:
git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"
The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt
; you need to run git difftool myfile.txt
.
From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/
HTML
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm">
<div id="notification"></div>
<input type="submit">
</form>
javascript
function onlyAlphabets() {
var regex = /^[a-zA-Z]*$/;
if (regex.test(document.f.nm.value)) {
//document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
return true;
} else {
document.getElementById("notification").innerHTML = "Alphabets Only";
return false;
}
}
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
Drawbacks of using TCP for live video:
FYI, please don't use the word "packages" when describing networks. Networks send "packets".
You have to declare height of html to div1 elements together, like:
html,
body,
.container,
.div1,
.div2 {
height:100%;
}
The error "Cannot read property 'map' of undefined"
will be encountered if there is an error in the "this.props.data"
or there is no props.data array.
Better put condition to check the the array like
if(this.props.data){
this.props.data.map(........)
.....
}
Referencing my comments on other answers. This is how I would work out the difference in days based on 24 hours and calender days. the days attribute works well for 24 hours and the function works best for calendar checks.
from datetime import timedelta, datetime
def cal_days_diff(a,b):
A = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
B = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
return (A - B).days
if __name__ == '__main__':
x = datetime(2013, 06, 18, 16, 00)
y = datetime(2013, 06, 19, 2, 00)
print (y - x).days # 0
print cal_days_diff(y, x) # 1
z = datetime(2013, 06, 20, 2, 00)
print (z - x).days # 1
print cal_days_diff(z, x) # 2
<?php
echo '<p>Hello World</p>'
?>
As simple as placing something along those lines within your HTML assuming your server is set-up to execute PHP in files with the HTML extension.
As an addition to the answer by marc_s, you can use a more generic extension method to get values from the SqlDataReader:
public static T SafeGet<T>(this SqlDataReader reader, int col)
{
return reader.IsDBNull(col) ? default(T) : reader.GetFieldValue<T>(col);
}
I use this: https://github.com/Homebrew/homebrew-php
The command is:
$ xcode-select --install
$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/homebrew-php
$ brew options php56
$ brew install php56
Then config in your .bash_profile
or .bashrc
# Homebrew PHP CLI
export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"
SELECT * FROM (SELECT colA, colB FROM tableA UNION SELECT colA, colB FROM tableB) as tableC WHERE tableC.colA > 1
If we're using a union that contains the same field name in 2 tables, then we need to give a name to the sub query as tableC(in above query). Finally, the WHERE
condition should be WHERE tableC.colA > 1
Remove -Werror
from your Make or CMake files, as suggested in this post
var src = "data:image/jpeg;base64,";
src += item_image;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "80";
document.querySelector('#imageContainer').innerHTML = newImage.outerHTML;//where to insert your image
I'd like to recommend ack -- better than grep, a power search tool for programmers.
$ ack --color --passthru --pager="${PAGER:-less -R}" pattern files
$ ack --color --passthru pattern files | less -R
$ export ACK_PAGER_COLOR="${PAGER:-less -R}" $ ack --passthru pattern files
I love it because it defaults to recursive searching of directories (and does so much smarter than grep -r
), supports full Perl regular expressions (rather than the POSIXish regex(3)
), and has a much nicer context display when searching many files.
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method only takes up constant memory(like iteration).
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
def fact(n):
return math.factorial(n)
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.
For example:-
//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")
//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")
In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.
Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.
let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")
As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).
let NotSoCuriousAnyMore = ("ca" == "ca")
println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")
This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
The 'string' extension type solves several issues with object-dtype NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear than string.
More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
The functions below will allow one to insert one string into another string:
def str_insert(from_me, into_me, at):
"""
Inserts the string <from_me> into <into_me>
Input <at> must be an integer index of <into_me> or a substring of <into_me>
Inserts <from_me> AFTER <at>, not before <at>
Inputs <from_me> and <into_me> must have working __str__ methods defined.
This is satisfied if they already are strings.
If not already strings, <from_me>, <into_me> are converted into strings.
If you try to insert an empty string, that's fine, and the result
is no different from the original.
In order to insert 'from_me' after nothing (insert at the beginning of the string) use:
at = '' or at = 0
"""
try:
return str_insert_or_raise(from_me, into_me, at)
except ValueError as err:
serr = str(err)
if (str_insert_or_raise.__name__ in serr) and 'not found' in serr and '<at>' in serr:
# if can't find where to insert stuff, don't bother to insert it
# use str_insert_or_raise if you want an exception instead
return into_me
else:
raise err
##############################################################
def str_insert_or_raise(from_me, into_me, at):
"""
Inserts the string <from_me> into <into_me>
Inserts <from_me> AFTER <at>, not before <at>
Input <at> must be an integer index of <into_me> or a substring of <into_me>
If <at> is the string '15', that substring will be searched for,
'15' will not be interpreted as an index/subscript.
Inputs <from_me> and <into_me> must have working __str__ methods defined.
If not already strings, <from_me>, <into_me> are converted into strings.
If you try to insert something, but we cannot find the position where
you said to insert it, then an exception is thrown guaranteed to at least
contain the following three substrings:
str_insert_or_raise.__name__
'not found'
'<at>'
"""
try:
if isinstance(at, int):
return str_insert_by_int(from_me, into_me, at)
# Below, the calls to str() work fine if <at> and <from_me> are already strings
# it makes them strings if they are not already
return str_insert_by_str(str(from_me), str(into_me), str(at))
except ValueError as err:
serr = str(err)
if 'empty string' in serr:
return into_me # We allow insertion of the empty string
elif ("<at>" in serr) and 'not found' in serr:
msg_start = "In " + str_insert_or_raise.__name__ + ": "
msg = [msg_start, "\ninput ", "<at> string", " not found in ", "<into_me>",
"\ninput <", str(at) , "> not found in <", str(into_me), ">"]
msg = ''.join(msg)
raise ValueError(msg) from None
else:
raise err
#############################################################
def str_insert_by_str(from_me, into_me, at):
"""
Inserts the string <from_me> into <into_me>
puts 'from_me' AFTER 'at', not before 'at'
For example,
str_insert_or_raise(at = '2', from_me = '0', into_me = '123')
puts the zero after the 2, not before the 2
The call returns '1203' not '1023'
Throws exceptions if input arguments are not strings.
Also, if <from_me> is empty or <at> is not a substring of <into_me> then
an exception is raised.
For fewer exceptions, use <str_insert_or_raise> instead.
"""
try:
s = into_me.replace(at, at + from_me, 1)
except TypeError as terr: # inputs to replace are not strings
msg_list = ['Inputs to function ', str_insert_by_str.__name__, '() must be strings']
raise TypeError(''.join(msg_list)) from None
# At the end of call to replace(), the '1' indicates we will replace
# the leftmost occurrence of <at>, instead of every occurrence of <at>
if (s == into_me): # <at> string not found and/or <from_me> is the empty string
msg_start = "In " + str_insert_by_str.__name__ + ": "
if from_me == '':
msg = ''.join([msg_start, "attempted to insert an empty string"])
raise ValueError(msg) from None
raise ValueError(msg_start, "Input <at> string not found in <into_me>.",
"\nUnable to determine where you want the substring inserted.") from None
return s
##################################################
def str_insert_by_int(from_me, into_me, at):
"""
* Inserts the string <from_me> into <into_me> at integer index <at>
* throws exceptions if input arguments are not strings.
* Also, throws an exception if you try to insert the empty string
* If <at> is less than zero, <from_me> gets placed at the
beginning of <into_me>
* If <at> is greater than the largest index of <into_me>,
<from_me> gets placed after the end of <into_me>
For fewer exceptions, use <str_insert_or_raise> instead.
"""
at = into_me[:(at if at > 0 else 0)]
return str_insert_by_str(from_me, into_me, at)
The code below demonstrates how to call the str_insert
function given earlier
def foo(*args):
return args
F = 'F. '
s = 'Using the string \'John \' to specify where to make the insertion'
result = str_insert(from_me = F, into_me ='John Kennedy', at ='John ')
print(foo('\n\n', s, '\n', result))
s = 'Using an int returned by find(\'Ken\') to specify where to make the insertion'
index = 'John Kennedy'.find('Ken') # returns the position of the first letter of 'Ken', not the last letter
result = str_insert(from_me = F, into_me ='John Kennedy', at = index)
print(foo('\n\n', s, '\n', result))
s = 'Using an int (5) to specify where to make the insertion.'
result = str_insert(from_me = F, into_me ='John Kennedy', at = 5)
print(foo('\n\n', s, '\n', result))
s = "Looking for an 'at' string which does not exist"
result = str_insert(from_me = F, into_me ='John Kennedy', at ='x')
print(foo('\n\n', s, '\n', result))
s = ''.join(["Looking for the empty string.",
"\nFind one immediately at the beginning of the string"])
result = str_insert(from_me = F, into_me ='John Kennedy', at = '')
print(foo('\n\n', s, '\n', result))
s = "Insert an empty string at index 3. No visible change"
result = str_insert(from_me = '', into_me = 'John Kennedy', at = 3)
print(foo('\n\n', s, '\n', result))
for index in [-5, -1, 0, 1, 997, 999]:
s = "index " + str(index)
result = str_insert(from_me = F, into_me = 'John Kennedy', at = index)
print(foo('\n\n', s, '\n', result))
None of the functions above will modify a string "in-place." The functions each return a modified copy of the string, but the original string remains intact.
For example,
s = ''.join(["Below is what we get when we forget ",
"to overwrite the string with the value",
" returned by str_insert_or_raise:"])
examp_str = 'John Kennedy'
str_insert('John ', F, examp_str)
print(foo('\n\n', s, '\n', examp_str))
# examp_str is still 'John Kennedy' without the F
Building off of Ben Blank's answer, the only way that I got this to validate in the w3 validator was like so:
<img src="/./.:0" alt="">`
Here is a simple method to read the text file from the raw folder:
public static String readTextFile(Context context,@RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, size);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
Arrays
in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).
Instead, use a List
:
ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:
String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.
Put another table inside the td element like this.
<table>
<tr>
...
</tr>
<tr>
<td>ABC</td>
<td>ABC</td>
<td>
<table>
<tr>
<td>name1</td>
<td>price1</td>
</tr>
...
</table>
</td>
<td>ABC</td>
</tr>
...
</table>
Add the class "pnradio" to the radio buttons, then switch with .attr('id')
<input type="radio" id="sampleradio1" class="pnradio" />
<input type="radio" id="sampleradio2" class="pnradio" />
$('.pnradio').click(function() {
switch ($(this).attr('id')) {
case 'sampleradio1':
alert("xxx");
break;
case 'sampleradio2':
alert("xxx");
break;
}
});
import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')
# read bytes from archive
img_data = archive.read('img_01.png')
# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)
img = pygame.image.load(bytes_io)
I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.
If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name
That will show you STDOUT and STDERR.
It is a batch terminator, you can however change it to whatever you want
There's now a new css3 property for this: text-decoration-color
So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element
p {_x000D_
text-decoration: underline;_x000D_
-webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
NB:
1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari
2) You could also use the text-decoration shorthand property which looks like this:
<text-decoration-line> || <text-decoration-style> || <text-decoration-color>
...so using the text-decoration
shorthand - the example above would simply be:
p {
text-decoration: underline red;
}
p {_x000D_
text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
Just add http://download.eclipse.org/egit/updates to your Eclipse update manager.
This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14)
.
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
This way sets the focus and cursor to the end of your input:
div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
How to POST mixed data: File, String[], String in one request.
You can use only what you need.
private String doPOST(File file, String[] array, String name) {
RestTemplate restTemplate = new RestTemplate(true);
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
//add array
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
for (String item : array) {
builder.queryParam("array", item);
}
//add some String
builder.queryParam("name", name);
//another staff
String result = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}
The POST request will have File in its Body and next structure:
POST https://my_url?array=your_value1&array=your_value2&name=bob
Instead of downloading curl, down libcurl.
curl is just the application, libcurl is what you need for your C++ program
So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.
char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.
int s = 1;
int i = -1;
int res = 0;
if (c[0] == '-') {
s = -1;
i = 0;
}
while (c[++i] != '\0') { //iterate until the array end
res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}
res = res*s; //answer: -908
You should upgrade the version of gradle. for example: com.android.build.gradle 1.3.0
this issue occurs when version of the gradle is changed.
In C++,
static const int foo = 42;
is the preferred way to define & use constants. I.e. use this rather than
#define foo 42
because it doesn't subvert the type-safety system.
This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:
<table border='1' style='border-collapse:collapse'>
No further styling of <tr>
/<td>
tags is required (for a basic table grid).
Let's start by describing DOM elements' event handling.
First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element
interface. For the purpose of assigning event handlers, Element.addListener
and Element.on
(these are equivalent) were created. So, for example, if we have html:
<div id="test_node"></div>
and we want add click
event handler.
Let's retrieve Element
:
var el = Ext.get('test_node');
Now let's check docs for click
event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
// event name event handler
el.on( 'click' , function(e, t, eOpts){
// handling event here
});
Widgets event handling is pretty much similar to DOM nodes event handling.
First of all, widgets event handling is realized by utilizing Ext.util.Observable
mixin. In order to handle events properly your widget must containg Ext.util.Observable
as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable
as a mixin by default.
For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener
). Let's for example create Button
widget and assign click
event to it. First of all you should check event's docs for handler's arguments:
click( Ext.button.Button this, Event e, Object eOpts )
Now let's use on
:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
});
The second way is to use widget's listeners config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
listeners : {
click: function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
}
});
Notice that Button
widget is a special kind of widgets. Click event can be assigned to this widget by using handler
config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
handler : function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
});
First of all you need to register an event using addEvents method:
myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
Using the addEvents
method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.
To fire your event use fireEvent method:
myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);
arg1, arg2, arg3, /* ... */
will be passed into handler. Now we can handle your event:
myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
// event handling here
console.log(arg1, arg2, arg3, /* ... */);
});
It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent
method when you are defining new widget:
Ext.define('MyCustomButton', {
extend: 'Ext.button.Button',
// ... other configs,
initComponent: function(){
this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
// ...
this.callParent(arguments);
}
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });
To prevent bubbling you can return false
or use Ext.EventObject.preventDefault()
. In order to prevent browser's default action use Ext.EventObject.stopPropagation()
.
For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:
myButton.on('click', function(btn, e){
if (e.button !== 0)
e.preventDefault();
});
Swift 3 (probably 2), you can override didSet on placeholder in UITextField
subclass to apply attribute on it, this way:
override var placeholder: String? {
didSet {
guard let tmpText = placeholder else {
self.attributedPlaceholder = NSAttributedString(string: "")
return
}
let textRange = NSMakeRange(0, tmpText.characters.count)
let attributedText = NSMutableAttributedString(string: tmpText)
attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)
self.attributedPlaceholder = attributedText
}
}
sys.stdout.write
is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:
print "a",
print "b",
This will print a b
, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:
print "a",
sys.stdout.write("0")
print "b",
This will print a0b
. How do you explain that? Where have the spaces gone?
I still can't quite make out what's really going on here. Could somebody look over my best guess:
My attempt at deducing the rules when you have a trailing ,
on your print
:
First, let's assume that print ,
(in Python 2) doesn't print any whitespace (spaces nor newlines).
Python 2 does, however, pay attention to how you are printing - are you using print
, or sys.stdout.write
, or something else? If you make two consecutive calls to print
, then Python will insist on putting in a space in between the two.
Delete '.git/config' and try again. Attention this will may reset some git settings too!
I've tried alternative credentials and Personal Access Token for many times with right credential and it kept telling me "fatal: Authentication failed".
Finally, I found there is a file named ".git/config" located at the root of my Repo. I deleted this file and type in my credentials again, it worked.
You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.
Something like:
...
watch: {
leaveType () {
this.whateverMethod(this.leaveType)
}
},
methods: {
onChange() {
console.log('The new value is: ', this.leaveType)
}
}
A couple of observations:
When you instantiate the second view controller, you are calling ViewControllerB()
. If that view controller programmatically creates its view (which is unusual) that would be fine. But the presence of the IBOutlet
suggests that this second view controller's scene was defined in Interface Builder, but by calling ViewControllerB()
, you are not giving the storyboard a chance to instantiate that scene and hook up all the outlets. Thus the implicitly unwrapped UILabel
is nil
, resulting in your error message.
Instead, you want to give your destination view controller a "storyboard id" in Interface Builder and then you can use instantiateViewController(withIdentifier:)
to instantiate it (and hook up all of the IB outlets). In Swift 3:
let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
You can now access this controller
's view
.
But if you really want to do addSubview
(i.e. you're not transitioning to the next scene), then you are engaging in a practice called "view controller containment". You do not just want to simply addSubview
. You want to do some additional container view controller calls, e.g.:
let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
addChild(controller)
controller.view.frame = ... // or, better, turn off `translatesAutoresizingMaskIntoConstraints` and then define constraints for this subview
view.addSubview(controller.view)
controller.didMove(toParent: self)
For more information about why this addChild
(previously called addChildViewController
) and didMove(toParent:)
(previously called didMove(toParentViewController:)
) are necessary, see WWDC 2011 video #102 - Implementing UIViewController Containment. In short, you need to ensure that your view controller hierarchy stays in sync with your view hierarchy, and these calls to addChild
and didMove(toParent:)
ensure this is the case.
Also see Creating Custom Container View Controllers in the View Controller Programming Guide.
By the way, the above illustrates how to do this programmatically. It is actually much easier if you use the "container view" in Interface Builder.
Then you don't have to worry about any of these containment-related calls, and Interface Builder will take care of it for you.
For Swift 2 implementation, see previous revision of this answer.
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
Make it a background image and larger than 100% to get the desired effect: http://jsfiddle.net/derekstory/hVM9v/
HTML
<div id="image"></div>
CSS
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
width: 100%;
height: 500px;
background: #000 url('http://static.ddmcdn.com/gif/dog-9.jpg') center no-repeat;
background-size: auto 200%;
}
As noted in the comments, the query in Saharsh Shah's answer must be run multiple times if items are duplicated more than once.
Here's a solution that doesn't delete any data, and keeps the data in the original table the entire time, allowing for duplicates to be deleted while keeping the table 'live':
alter table tableA add column duplicate tinyint(1) not null default '0';
update tableA set
duplicate=if(@member_id=member_id
and @quiz_num=quiz_num
and @question_num=question_num
and @answer_num=answer_num,1,0),
member_id=(@member_id:=member_id),
quiz_num=(@quiz_num:=quiz_num),
question_num=(@question_num:=question_num),
answer_num=(@answer_num:=answer_num)
order by member_id, quiz_num, question_num, answer_num;
delete from tableA where duplicate=1;
alter table tableA drop column duplicate;
This basically checks to see if the current row is the same as the last row, and if it is, marks it as duplicate (the order statement ensures that duplicates will show up next to each other). Then you delete the duplicate records. I remove the duplicate
column at the end to bring it back to its original state.
It looks like alter table ignore
also might go away soon: http://dev.mysql.com/worklog/task/?id=7395
EDIT : 31/10/2017
The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult
or one of it's implementation (Ex :OkObjectResult
)
Use
contentType:"application/json"
You need to use JSON.stringify
method to convert it to JSON string when you send it,
And the model binder will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
Result
contentType
property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.
If you inspect the ajax request's headers, you can see that the Content-Type
value is set as application/json
.
If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;
Edit on Nov 2015 to address other possible issues raised in comments
Let's say you have a complex view model class as your web api action method parameter like this
public class CreateUserViewModel
{
public int Id {set;get;}
public string Name {set;get;}
public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
public int Id {set;get;}
public string Code {set;get;}
}
and your web api end point is like
public class ProductController : Controller
{
[HttpPost]
public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
{
// I am just returning the posted model as it is.
// You may do other stuff and return different response.
// Ex : missileService.LaunchMissile(m);
return m;
}
}
At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller
base class.
To send data to the method from client side, the below code should work fine
//Build an object which matches the structure of our view model class
var model = {
Name: "Shyju",
Id: 123,
Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../product/save",
contentType: "application/json"
}).done(function(res) {
console.log('res', res);
// Do something with the result :)
});
If you do not decorate the web api method parameter with [FromBody]
attribute
[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
return m;
}
And send the model(raw javascript object, not in JSON format) without specifying the contentType property value
$.ajax({
type: "POST",
data: model,
url: "../product/save"
}).done(function (res) {
console.log('res', res);
});
Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id
and Name
properties will be properly bound to the parameter m
, But the Tags
property will be an empty list.
The same problem will occur if you are using the short version, $.post
which will use the default Content-Type when sending the request.
$.post("../product/save", model, function (res) {
//res contains the markup returned by the partial view
console.log('res', res);
});
mysql> use mysql;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-password-here';
Try it once, it worked for me.
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
You can change it by going File
=> Settings
(Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance
, Now from Right Panel choose theme.
Android Studio 2.1
Preference -> Search for Appearance -> UI options , Click on DropDown Theme
Android 2.2
Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options
EDIT :
Import External Themes
You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the
.jar
file downloaded.
To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE
and GIT_COMMITTER_DATE
:
GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'
where date -d'...'
can be exact date like 2019-01-01 12:00:00
or relative like 5 months ago 24 days ago
.
To see both dates in git log use:
git log --pretty=fuller
This also works for merge commits:
GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff
Install Fiddler on your PC and use it as a proxy on your Android device.
Source: http://www.cantoni.org/2013/11/06/capture-android-web-traffic-fiddler
No! You should avoid using HTML entities.
Instead of using HTML entities for symbols you should just put those symbols directly into your text and correctly encode your document.
£
you should use the character £
.??
which is currently the most commonly used single character for rupee. Other alternatives are using INR
, Rs.
or rupees
.When the new Unicode symbol for the Indian Rupee is introduced then could use that instead (but note that it will be a while before all browsers support it).
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
Using has a gotcha, while it is by far the fastest method, it also expects all of your filenames to be lowercase.
spl_autoload_extensions(".php");
spl_autoload_register();
For example:
A file containing the class SomeSuperClass would need to be named somesuperclass.php, this is a gotcha when using a case sensitive filesystem like Linux, if your file is named SomeSuperClass.php but not a problem under Windows.
Using __autoload in your code may still work with current versions of PHP but expect this feature to become deprecated and finally removed in the future.
So what options are left:
This version will work with PHP 5.3 and above and allows for filenames SomeSuperClass.php and somesuperclass.php. If your using 5.3.2 and above, this autoloader will work even faster.
<?php
if ( function_exists ( 'stream_resolve_include_path' ) == false ) {
function stream_resolve_include_path ( $filename ) {
$paths = explode ( PATH_SEPARATOR, get_include_path () );
foreach ( $paths as $path ) {
$path = realpath ( $path . PATH_SEPARATOR . $filename );
if ( $path ) {
return $path;
}
}
return false;
}
}
spl_autoload_register ( function ( $className, $fileExtensions = null ) {
$className = str_replace ( '_', '/', $className );
$className = str_replace ( '\\', '/', $className );
$file = stream_resolve_include_path ( $className . '.php' );
if ( $file === false ) {
$file = stream_resolve_include_path ( strtolower ( $className . '.php' ) );
}
if ( $file !== false ) {
include $file;
return true;
}
return false;
});
Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
You could try:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());
Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count); // or .Length
The only way to do it is by checking the value of the isCancelled() method and stopping playback when it returns true.
To manually sign an Android APK file run these three commands:
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
Sign Your APK file using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
Align Signed APK using zipalign tool
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
Generate Keystore file
keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
keystore password : yourApp@123 key password : yourApp@123
D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
-alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
[Unknown]: MySignedApp Sample
What is the name of your organizational unit?
[Unknown]: Information Technology
What is the name of your organization?
[Unknown]: MySignedApp Demo
What is the name of your City or Locality?
[Unknown]: Mumbai
What is the name of your State or Province?
[Unknown]: Maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
[no]: y
Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
C=IN
Enter key password for <MySignedApp>
(RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]
D:\ru\SignedBuilds\MySignedApp>
Sign your app with your private keystore using jarsigner
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id
D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
adding: META-INF/MANIFEST.MF
adding: META-INF/---.SF
adding: META-INF/---.RSA
signing: AndroidManifest.xml
.....
signing: classes.dex
signing: lib/commons-codec-1.6.jar
signing: lib/armeabi/libkonyjsvm.so
jar signed.
Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.
D:\ru\SignedBuilds\MySignedApp>
Verify that your APK is signed
jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH
jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
future revocation date.
D:\ru\SignedBuilds\MySignedApp>
zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK
zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4528613 classes.dex (OK - compressed)
5656594 lib/commons-codec-1.6.jar (OK - compressed)
5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
Verify that your APK is Aligned successfully
zipalign -c -v 4 YOUR_APK_PATH
zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...
4453984 res/drawable/zoomout.png (OK)
4454772 res/layout/tabview.xml (OK - compressed)
4455243 res/layout/wheel_item.xml (OK - compressed)
4455608 resources.arsc (OK)
4470161 classes.dex (OK - compressed)
5597923 lib/commons-codec-1.6.jar (OK - compressed)
5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful
D:\Android\android-sdk\build-tools\19.1.0>
The verify command is just to check whether APK is built and signed correctly!
I hope this will help one and all :)
Skype was the main cause of my problem:
This error usually occurs when you have set up Visual Studio to debug an existing web application running in IIS rather than the built in ASP.NET debug web server. IIS by default listens for web requests on port 80. In this case, another application is already listening for requests on port 80. Typically, the offending application is Skype, which by default takes over listening on ports 80 and 443 when installed. Skype is already occupy the port 80. So IIS is unable to start.
To resolve the issue follow the steps:
Skype -> Tools -> Options -> Advanced -> Connection:
Uncheck "Use port 80 and 443 as alternatives for incoming connections".
And as pointed out below perform an IIS reset once done.
Okay. I finally found what actually works to answer the question that seems to be asked;
"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"
Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.
But thanks to Cody Gray's link to an example, I was able to discern a proper answer;
Situation; You have multiple Modules and/or Forms and want to reference a particular variable from each or all.
"A" way that works; On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);
Public Module DefineGlobals
Public Parts As Integer 'Assembled-particle count
Public FirstPrtAff As Long 'Addr into Link List
End Module
And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);
Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Parts = Parts + 3
End Sub
End Class
And perhaps another Form; Public Class FormX
Sub CreateAff()
Parts = 1000
End Sub
End Class
That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.
Nothing beats exact and well worded, explicit examples.
Thanks again, Cody
what might get you where you want in plain SQL92:
select * from tbl where lower(answer) = upper(answer)
or, if you also want to be robust for leading/trailing spaces:
select * from tbl where lower(answer) = trim(upper(answer))
a.h:
#ifndef A_H
#define A_H
struct a {
int i;
struct b {
int j;
}
};
#endif
there you go, now you just need to include a.h to the files where you want to use this structure.
In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));
There is also a nice web app to see the dependencies in a weighted map kind of view.
For example:
I spent ages trying to figure this out but it is simple! You can use length(·)
. length(mylist)
will tell you the number of objects mylist
contains.
... and just realised someone had already answered this- sorry!
The user-agent
should be specified as a field in the header.
Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent
.
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]' # This is another valid field
}
response = requests.get(url, headers=headers)
Older versions of requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
I implemented something similar with Horizontal Variable ListView The only drawback is, it works only with Android 2.3 and later.
Using this library is as simple as implementing a ListView with a corresponding Adapter. The library also provides an example
DateTime.Now.ToString("dd/MM/yyyy");
FileUtils
is class from apache org.apache.commons.io
package, you need to download org.apache.commons.io.jar
and then configure that jar
file in your class path.
I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.
To those that are incline to use GUI:
Click Right mouse button on procecdure name then select Test
Then in new window you will see script generated just add the parameters and click on Start Debugger
or F9
Hope this saves you some time.
If adapter
is set to AutoCompleteTextView
then notifyDataSetChanged()
doesn't work.
Need this to update adapter:
myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, myList);
myAutoComplete.setAdapter(myAutoCompleteAdapter);
Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html
I am using eclipse 2019-09.
I had to update the junit-bom version to at least 5.4.0. I previously had 5.3.1 and that caused the same symptoms of the OP.
My config is now:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.5.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
To list untracked files try:
git ls-files --others --exclude-standard
If you need to pipe the output to xargs
, it is wise to mind white spaces using git ls-files -z
and xargs -0
:
git ls-files -z -o --exclude-standard | xargs -0 git add
Nice alias for adding untracked files:
au = !git add $(git ls-files -o --exclude-standard)
Edit: For reference: git-ls-files
Standard YAML 1.2 doesn't include natively this feature. Nevertheless many implementations provides some extension to do so.
I present a way of achieving it with Java and snakeyaml:1.24
(Java library to parse/emit YAML files) that allows creating a custom YAML tag to achieve the following goal (you will see I'm using it to load test suites defined in several YAML files and that I made it work as a list of includes for a target test:
node):
# ... yaml prev stuff
tests: !include
- '1.hello-test-suite.yaml'
- '3.foo-test-suite.yaml'
- '2.bar-test-suite.yaml'
# ... more yaml document
Here is the one-class Java that allows processing the !include
tag. Files are loaded from classpath (Maven resources directory):
/**
* Custom YAML loader. It adds support to the custom !include tag which allows splitting a YAML file across several
* files for a better organization of YAML tests.
*/
@Slf4j // <-- This is a Lombok annotation to auto-generate logger
public class MyYamlLoader {
private static final Constructor CUSTOM_CONSTRUCTOR = new MyYamlConstructor();
private MyYamlLoader() {
}
/**
* Parse the only YAML document in a stream and produce the Java Map. It provides support for the custom !include
* YAML tag to split YAML contents across several files.
*/
public static Map<String, Object> load(InputStream inputStream) {
return new Yaml(CUSTOM_CONSTRUCTOR)
.load(inputStream);
}
/**
* Custom SnakeYAML constructor that registers custom tags.
*/
private static class MyYamlConstructor extends Constructor {
private static final String TAG_INCLUDE = "!include";
MyYamlConstructor() {
// Register custom tags
yamlConstructors.put(new Tag(TAG_INCLUDE), new IncludeConstruct());
}
/**
* The actual include tag construct.
*/
private static class IncludeConstruct implements Construct {
@Override
public Object construct(Node node) {
List<Node> inclusions = castToSequenceNode(node);
return parseInclusions(inclusions);
}
@Override
public void construct2ndStep(Node node, Object object) {
// do nothing
}
private List<Node> castToSequenceNode(Node node) {
try {
return ((SequenceNode) node).getValue();
} catch (ClassCastException e) {
throw new IllegalArgumentException(String.format("The !import value must be a sequence node, but " +
"'%s' found.", node));
}
}
private Object parseInclusions(List<Node> inclusions) {
List<InputStream> inputStreams = inputStreams(inclusions);
try (final SequenceInputStream sequencedInputStream =
new SequenceInputStream(Collections.enumeration(inputStreams))) {
return new Yaml(CUSTOM_CONSTRUCTOR)
.load(sequencedInputStream);
} catch (IOException e) {
log.error("Error closing the stream.", e);
return null;
}
}
private List<InputStream> inputStreams(List<Node> scalarNodes) {
return scalarNodes.stream()
.map(this::inputStream)
.collect(toList());
}
private InputStream inputStream(Node scalarNode) {
String filePath = castToScalarNode(scalarNode).getValue();
final InputStream is = getClass().getClassLoader().getResourceAsStream(filePath);
Assert.notNull(is, String.format("Resource file %s not found.", filePath));
return is;
}
private ScalarNode castToScalarNode(Node scalarNode) {
try {
return ((ScalarNode) scalarNode);
} catch (ClassCastException e) {
throw new IllegalArgumentException(String.format("The value must be a scalar node, but '%s' found" +
".", scalarNode));
}
}
}
}
}
You can just do
System.out.print("String");
Instead
System.out.println("String");
$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
$tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
$tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));
Here is what works for me on Swift 3
let _ = (dict[key].map { $0 as? String } ?? "")
Run -> Run configurations, select project, second tab: “Arguments”. Top box is for your program, bottom box is for VM arguments, e.g. -Dkey=value
.
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
Node : http://www.w3schools.com/js/js_htmldom_nodes.asp
The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.
Element : http://www.w3schools.com/js/js_htmldom_elements.asp
The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.
duplicate :
The appropriate way for doing this:
@app.route('/')
def index():
if form.validate_on_submit():
if 'download' in request.form:
pass # do something
elif 'watch' in request.form:
pass # do something else
Put watch
and download
buttons into your template:
<input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">
You can hang a lot of functions on the onClick
event for one element. How can you be sure the false
one will be the last one to fire? preventDefault
on the other hand will definitely prevent only the default behavior of the element.
Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:
To export selected certificates
- Choose Xcode > Preferences.
- Click Accounts at the top of the window.
- Select the team you want to view, and click View Details.
- Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.
- Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
- Click Save. The file is saved to the location you specified with a .p12 extension.
Source (Apple's documentation)
To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
Here's an example that makes sure that the body has minimum height of the device screen height and also hides the scroll bar. It uses DOMSubtreeModified event, but makes the check only every 400ms, to avoid performance loss.
var page_size_check = null, q_body;
(q_body = $('#body')).bind('DOMSubtreeModified', function() {
if (page_size_check === null) {
return;
}
page_size_check = setTimeout(function() {
q_body.css('height', '');
if (q_body.height() < window.innerHeight) {
q_body.css('height', window.innerHeight + 'px');
}
if (!(window.pageYOffset > 1)) {
window.scrollTo(0, 1);
}
page_size_check = null;
}, 400);
});
Tested on Android and iPhone.
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
Unfortunately, IE and VLC don't really work right now... I found this on the vlc forums:
VLC included activex support up until version 0.8.6, I believe. At that time, you could
access a cab on the videolan and therefore 'automatic' installation into IE and Firefox
family browsers was fine. Thereafter support for activex seemed to stop; no cab, no
activex component.
VLC 1.0.* once again contains activex support, and that's brilliant. A good decision in
my opinion. What's lacking is a cab installer for the latest version.
This basically means that even if you found a way to make it work, anyone trying to view the video on your site in IE would have to download and install the entire VLC player program to have it work in IE, and users probably don't want to do that. I can't get your code to work in firefox or IE8 on my boyfriends computer, although I might not have been putting the video address in properly... I get some message about no video output...
I'll take a guess and say it probably works for you locally because you have VLC installed, but your server doesn't. Unfortunately you'll probably have to use Windows media player or something similar (Microsoft is great at forcing people to use their stuff!)
And if you're wondering, it appears that the reason there is no cab file is because of the cost of having an active-x control signed.
It's rather simple to have your page use VLC for firefox and chrome users, and Windows Media Player for IE users, if that would work for you.
On a WEC7 project I'm working on, I got a similar error. The file I was serializing in was serialized out from an array of objects, so I figured the XML was fine. Also, I have had this working for a few previous classes, so it was quite a puzzle.
Then I noticed in my earlier work that every class that I was serializing/deserializing had a default constructor. That was missing in my failed case so I added it and and voila... it worked fine.
I seem to remember reading somewhere that this was required. I guess it is.
One solution is to first encode data and then decode it in the same file:
$string =json_encode($input, JSON_UNESCAPED_UNICODE) ;
echo $decoded = html_entity_decode( $string );
Another option is to convert nil to an empty result on the fly:
(my_string||'').empty?