Using directive it becomes easy and can be used throughout the application
HTML
<input type="text" placeholder="Enter value" numbersOnly>
As .keyCode()
and .which()
are deprecated, codes are checked using .key()
Referred from
Directive:
@Directive({
selector: "[numbersOnly]"
})
export class NumbersOnlyDirective {
@Input() numbersOnly:boolean;
navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
constructor(private _el: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
if (
// Allow: Delete, Backspace, Tab, Escape, Enter, etc
this.navigationKeys.indexOf(e.key) > -1 ||
(e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
(e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
(e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
(e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
(e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
(e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
(e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
(e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
) {
return; // let it happen, don't do anything
}
// Ensure that it is a number and stop the keypress
if (e.key === ' ' || isNaN(Number(e.key))) {
e.preventDefault();
}
}
}
This is possible if the browser supports the download
property in anchor elements.
var sampleBytes = new Int8Array(4096);
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveByteArray([sampleBytes], 'example.txt');
JSFiddle: http://jsfiddle.net/VB59f/2
To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.
My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.
File format
This tool parses .CRX version 2 format documented by Google. In general, .CRX file format consist of few parts:
Magic header
Version of file format
Public Key information and a package signature
Zipped contents of the extension source code
Magic header is a signature of the file telling that this file is Chrome Extension. Using this header the operating system can determine the actual type of the file (MIME type is application/x-chrome-extension), and how should it be treaten (is it executable? is it a text file?). Then the window system can show beautiful icon to the user.
In .CRX files the magic header has a constant value Cr24 or 0x43723234.
The version is provided by vendor. The version bytes are 0x02000000.
The next part of the file contains the length of the public key information and the length of a digital signature.
All .CRX packages distributed via Chrome WebStore should have public key information and digital signature in order to make possible for browser to check that the package has been transmitted without modifications and that no additions or replacements were made.
After all of the header stuff, typically ending up on 307'th byte, comes the code of extension, stored as zip-archive. So the remainder of the .crx file is the well-known .zip archive.
.crx file opened in the hex editor called HexFiend (on Mac) The header part of a .crx file selected on the picture above. Obviously, you can extract the remaining .zip archive "by hand" using any simple hex editor. In this example, we use handy HexFiend editor on Mac.
The CRX Extractor loads a file provided, checks a magic header, version and trims the file, so only .zip archive remains. Then it returns obtained .zip archive to user.
It's possible to modify the code of .CRX extension, because it's a simple .zip archive. You can download extension, extract it's source code, modify it (test and debug it as it's on your side), and package back into .CRX file.
I googled out this tool to simply download .CRX extension and extract the source code and it worked for me: http://crxextractor.com
Everything it does is parses .CRX file format and extracts actual .zip containing the source code.
There's a RemoveDuplicates
method that you could use:
Sub DeleteRows()
With ActiveSheet
Set Rng = Range("A1", Range("B1").End(xlDown))
Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End With
End Sub
IB and Swift
Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,
the goal is to move a subview (let's say green) to the top.
In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.
Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.
There are a couple of different ways to do this programmatically.
Method 1
yellowView.bringSubviewToFront(greenView)
This method is the programmatic equivalent of the IB answer above.
It only works if the subviews are siblings of each other.
An array of the subviews is contained in yellowView.subviews
. Here, bringSubviewToFront
moves the greenView
from index 0
to 2
. This can be observed with
print(yellowView.subviews.indexOf(greenView))
Method 2
greenView.layer.zPosition = 1
0
for all the other views, the result is that the greenView
looks like it is on top. However, it still remains at index 0
of the yellowView.subviews
array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.zPosition
could be set to CGFloat.greatestFiniteMagnitude
(CGFloat(FLT_MAX)
in older versions of Swift) to ensure that it is on top.var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var sessionId ='\n';
var token = '\n';
var caseId = CaseIDNumber + '\n';
var url = casewebUrl+'\n';
var uri = sessionId + token + caseId + url;//data in file
var fileName = "file.i4cvf";// any file name with any extension
if (isIE)
{
var fileData = ['\ufeff' + uri];
var blobObject = new Blob(fileData);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}
else //chrome
{
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
fs.root.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
var fileData = ['\ufeff' + uri];
var blob = new Blob(fileData);
fileWriter.addEventListener("writeend", function () {
var fileUrl = fileEntry.toURL();
var link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}, false);
fileWriter.write(blob);
}, function () { });
}, function () { });
}, function () { });
}
If you want the key (id in this case) to be a preserved as a property of each array item you can do
const arr = _(obj) //wrap object so that you can chain lodash methods
.mapValues((value, id)=>_.merge({}, value, {id})) //attach id to object
.values() //get the values of the result
.value() //unwrap array of objects
You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'.
foo = None
foo.something = 1
or
foo = None
print(foo.something)
Both will yield an AttributeError: 'NoneType'
This simple solution worked for me:
<?php
$sq = new SQLite3( 'sqlite3.db' );
$tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type="table"' );
while ( $table = $tables->fetchArray() ) {
$table = current( $table );
$result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );
if ( strpos( $table, 'sqlite' ) !== false )
continue;
printf( "-- %s\n", $table );
while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {
$values = array_map( function( $value ) {
return sprintf( "'%s'", mysql_real_escape_string( $value ) );
}, array_values( $row ) );
printf( "INSERT INTO `%s` VALUES( %s );\n", $table, implode( ', ', $values ) );
}
}
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
I'll take a little exception to jichao's answer. You can actually do everything he just talked about fairly easily. Instead of looking for a \n
, just look for carriage return at the end of the line.
sed -i 's/\r$//' "${FILE_NAME}"
To change from unix back to dos, simply look for the last character on the line and add a form feed to it. (I'll add -r
to make this easier with grep regular expressions.)
sed -ri 's/(.)$/\1\r/' "${FILE_NAME}"
Theoretically, the file could be changed to mac style by adding code to the last example that also appends the next line of input to the first line until all lines have been processed. I won't try to make that example here, though.
Warning: -i changes the actual file. If you want a backup to be made, add a string of characters after -i
. This will move the existing file to a file with the same name with your characters added to the end.
In Windows it worked for me only after trying the following: 1. Open cmd inside the folder where "requests" is unpacked. (CTRL+SHIFT+right mouse click, choose the appropriate popup menu item) 2. (Here is the path to your pip3.exe)\pip3.exe install requests Done
For unsigned APK: Simply set signingConfig null. It will give you appName-debug-unsigned.apk
debug {
signingConfig null
}
And build from Build menu. Enjoy
For signed APK:
signingConfigs {
def keyProps = new Properties()
keyProps.load(rootProject.file('keystore.properties').newDataInputStream())
internal {
storeFile file(keyProps.getProperty('CERTIFICATE_PATH'))
storePassword keyProps.getProperty('STORE_PASSWORD')
keyAlias keyProps.getProperty('KEY_ALIAS')
keyPassword keyProps.getProperty('KEY_PASSWORD')
}
}
buildTypes {
debug {
signingConfig signingConfigs.internal
minifyEnabled false
}
release {
signingConfig signingConfigs.internal
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
keystore.properties file
CERTIFICATE_PATH=./../keystore.jks
STORE_PASSWORD=password
KEY_PASSWORD=password
KEY_ALIAS=key0
As per Firebase Cloud Messaging documentation-If Activity is in foreground then onMessageReceived will get called. If Activity is in background or closed then notification message is shown in the notification center for app launcher activity. You can call your customized activity on click of notification if your app is in background by calling rest service api for firebase messaging as:
URL-https://fcm.googleapis.com/fcm/send
Method Type- POST
Header- Content-Type:application/json
Authorization:key=your api key
Body/Payload:
{ "notification": {
"title": "Your Title",
"text": "Your Text",
"click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
},
"data": {
"keyname": "any value " //you can get this data as extras in your activity and this data is optional
},
"to" : "to_id(firebase refreshedToken)"
}
And with this in your app you can add below code in your activity to be called:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
if you need to select multiple columns from dataframe use 2 pairs of square brackets eg.
df[["product_id","customer_id","store_id"]]
I modified @kolbyjack code to make it work for
http://website1/service
http://website1/service/
with parameters
location ~ ^/service/?(.*) {
return 301 http://service_url/$1$is_args$args;
}
I think its already been answered before, but just a correction if you are populating an unordered list, the *ngFor
will come in the element which you want to repeat. So it should be insdide <li>
. Also, Angular2 now uses let to declare a variable.
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
If you wants display anchors in your own choice of colors than you should define the color in anchor tag property in CSS like this:-
a { text-decoration: none; color:red; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }
see the demo:- http://jsfiddle.net/zSWbD/7/
here is the commend which is tested Sqlcmd -E -S "server name" -d "DB name" -i "SQL file path"
-E stand for windows trusted
The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.
Updating is quite straightforward:
glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update
This question has a lot of answers but all they looks not very useful in case if you really want to use backgroundColor to style your buttons. UIButton has nice option to set different images for different control states but there is not same feature for background colors. So one of solutions is to add extension which will generate images from color and apply them to button.
extension UIButton {
private func image(withColor color: UIColor) -> UIImage? {
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
self.setBackgroundImage(image(withColor: color), for: state)
}
}
Only one issue with this solution -- this change won't be applied to buttons created in storyboard. As for me it's not an issue because I prefer to style UI from code. If you want to use storyboards then some additional magic with @IBInspectable
needed.
Second option is subclassing but I prefer to avoid this.
You want to see the entire object (all nested levels of objects and variables inside it) in JSON form. JSON stands for JavaScript Object Notation, and printing out a JSON string of your object is a good equivalent of var_dump
(to get a string representation of a JavaScript object). Fortunately, JSON is very easy to use in code, and the JSON data format is also pretty human-readable.
Example:
var objectInStringFormat = JSON.stringify(someObject);
alert(objectInStringFormat);
Use the below code to resolve the issue.
import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()
As the best anwser have writed using XMLHttpResponse
except window.open
, and I make the abstracts-anwser as a instance.
The main Js file is download.js
Download-JS
// var download_url = window.BASE_URL+ "/waf/p1/download_rules";
var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
function download33() {
var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
var x=new XMLHttpRequest();
x.open("POST", download_url, true);
x.setRequestHeader("Content-type","application/json");
// x.setRequestHeader("Access-Control-Allow-Origin", "*");
x.setRequestHeader("Authorization", "JWT " + localStorage.token );
x.responseType = 'blob';
x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
x.send( JSON.stringify(sender_data) ); // post-data
}
You may try this:
Cookie::queue($name, $value, $minutes);
This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentation on Laravel
website.
Update (Retrieving A Cookie Value
):
$value = Cookie::get('name');
Note: If you set a cookie in the current request then you'll be able to retrieve it on the next subsequent request.
Enable "Show All Files" for the specific project (you might need to hit "Refresh" to see them)**.
The folders/files that are not part of your project appear slightly "lighter" in the project tree.
Right click the folders/files you want to add and click "Include In Project". It will recursively add folders/files to the project.
** These buttons are located on the mini Solution Explorer toolbar.
** Make sure you are NOT in debug mode.
You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -
, like script.ps1 -server http://devserver
Then you handle them in param
section in the beginning of the file.
You can also assign default values to your params, read them from console if not available or stop script execution:
param (
[string]$server = "http://defaultserver",
[Parameter(Mandatory=$true)][string]$username,
[string]$password = $( Read-Host "Input password, please" )
)
Inside the script you can simply
write-output $server
since all parameters become variables available in script scope.
In this example, the $server
gets a default value if the script is called without it, script stops if you omit the -username
parameter and asks for terminal input if -password
is omitted.
Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.
The keyword for that is [switch]
parameter type:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
Inside the script then you would work with it like this:
if ($force) {
//deletes a file or does something "bad"
}
Now, when calling the script you'd set the switch/flag parameter like this:
.\yourscript.ps1 -server "http://otherserver" -force
If you explicitly want to state that the flag is not set, there is a special syntax for that
.\yourscript.ps1 -server "http://otherserver" -force:$false
Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):
So it was a simple fix. Just had to move the ng-click
to a scope click handler:
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
$scope.clickUpload = function(){
angular.element('#upload').trigger('click');
};
You can also put the files or links into the root of the solution explorer and then set the files properties:
Build action = Content
and
Copy to Output Directory = Copy if newer
(for example)
For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.
Yes, ( )
captures a group. You can use it again with $i
where i
is the i'th capture group.
So:
search:
(\w+\.someMethod\(\))
replace:
((TypeName)$1)
Hint: Ctrl + Space in the textboxes gives you all kinds of suggestions for regular expression writing.
Here is a more polished version of the accepted answer. It accepts only timestamps and returns a relative date or a formatted date string for everything +/-2 days
<?php
/**
* Relative time
*
* date Format http://php.net/manual/en/function.date.php
* strftime Format http://php.net/manual/en/function.strftime.php
* latter can be used with setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
*
* @param timestamp $target
* @param timestamp $base start time, defaults to time()
* @param string $format use date('Y') or strftime('%Y') format string
* @return string
*/
function relative_time($target, $base = NULL, $format = 'Y-m-d H:i:s')
{
if(is_null($base)) {
$base = time();
}
$baseDate = new DateTime();
$targetDate = new DateTime();
$baseDate->setTimestamp($base);
$targetDate->setTimestamp($target);
// don't modify original dates
$baseDateTemp = clone $baseDate;
$targetDateTemp = clone $targetDate;
// normalize times -> reset to midnight that day
$baseDateTemp = $baseDateTemp->modify('midnight');
$targetDateTemp = $targetDateTemp->modify('midnight');
$interval = (int) $baseDateTemp->diff($targetDateTemp)->format('%R%a');
d($baseDate->format($format));
switch($interval) {
case 0:
return (string) 'today';
break;
case -1:
return (string) 'yesterday';
break;
case 1:
return (string) 'tomorrow';
break;
default:
if(strpos($format,'%') !== false )
{
return (string) strftime($format, $targetDate->getTimestamp());
}
return (string) $targetDate->format($format);
break;
}
}
setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo relative_time($weather->time, null, '%A, %#d. %B'); // Montag, 6. August
echo relative_time($weather->time, null, 'l, j. F'); // Monday, 6. August
Your condition says if X is greater than 57 AND smaller than 48
. X
cannot be both greater than 57 and smaller than 48 at the same time.
if(tmp[j] > 57 && tmp[j] < 48)
It should be if X is greater than 57 OR smaller than 48
:
if(tmp[j] > 57 || tmp[j] < 48)
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. The process of converting source code into native executable code is called "compilation", and it's not supported by scripting languages like VBScript.
Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a self-extracting archive is that decompression software (like WinZip) is not required on the end user's computer to be able to extract or "decompress" the file. If it isn't compressed in the first place, this is a moot point.
Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.
In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be compiled. Visual Basic 6 (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild.
Alternatively, you could go ahead and make the jump to Visual Basic .NET, which remains somewhat similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some huge differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.
None of the above answers worked for me, and as said in the original question I had also to keep the same bundle identifier since the app was already published in the store by the client.
The solution for me was to ask the client to change my access from App Manager to Admin, so that I had "Access to Certificates, Identifiers & Profiles.", you can check if it is the case in the App Store Connect => Users and Access => and then click on your profile (be sure to choose the right team if you belong to multiple).
Once you are admin go back to Xcode and in the signing tab select 'Automatically manage signing', then in Team dropdown you should be able to select the right team and the signature will work.
Note that reversing the whole string (either with the rbegin()
/rend()
range constructor or with std::reverse
) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.
Character constants in C like 'a'
are not guaranteed to be ASCII.
C99 only makes some guarantees about those constants, e.g. that digits be contiguous.
The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:
In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).
implying that ASCII is not the only possibility
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
After running the command once, run fc
It will launch $EDITOR
with the previous command, then you can use your regular editor to modify the command. When you save and exit, the file will be executed.
..but, as Pax said - the command line isn't particularly good for editing absurdly long lines - why not make the command into a script?
In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.
There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)
The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.
what is the type of the field EventDate
, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
clearfix
is the same as overflow:hidden
. Both clear floated children of the parent, but clearfix
will not cut off the element which overflow to it's parent
.
It also works in IE8 & above.
There is no need to define "."
in content & .clearfix. Just write like this:
.clr:after {
clear: both;
content: "";
display: block;
}
HTML
<div class="parent clr"></div>
Read these links for more
Many other answers tell you to point your Eclipse to a JDK instead of a JRE.
Here is another answer with more specific/clear [than I have seen in any answer here] step-by-steps on how to do that: How do you install JDK?
That is what for solved me for this same problem.
you're using a function
error(error)
but jquery is actually looking for a function with three parameters:
error(jqXHR, textStatus, errorThrown)
you'll need to add two more parameters.
ALSO: please have a look at all the comments above that mention 'deprecated' :)
$.ajax("www.stackoverflow.com/api/whatever", {
dataType:"JSON"
data: { id=1, name='example' }
}).succes(function (result) {
// use result
}).error(function (jqXHR, textStatus, errorThrown) {
// handle error
});
If you have a self-incrementing field (say ID
) then you can do something like:
SELECT * FROM foo WHERE ID = (SELECT max(ID) FROM foo)
Flushing the output buffers:
printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is
or
fprintf(fd, "Buffered, will be flushed");
fflush(fd); //Prints to a file
Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf()
it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf
something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.
Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf()
, so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.
I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf()
is an expensive operation (which is why it doesn't by default flush the buffer).
As far as flushing the input buffer (stdin
), you should not do that. Flushing stdin
is undefined behavior according to the C11 standard §7.21.5.2 part 2:
If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
On some systems, Linux being one as you can see in the man page for fflush()
, there's a defined behavior but it's system dependent so your code will not be portable.
Now if you're worried about garbage "stuck" in the input buffer you can use fpurge()
on that.
See here for more on fflush()
and fpurge()
You will have to build a CLR procedure that provides regex functionality, as this article illustrates.
Their example function uses VB.NET:
Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here
Namespace SimpleTalk.Phil.Factor
Public Class RegularExpressionFunctions
'RegExIsMatch function
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExIsMatch( _
ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) As SqlBoolean
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlBoolean.False
End If
Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
RegExOption = Options
Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
End Function
End Class '
End Namespace
...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:
sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
IF EXISTS ( SELECT 1
FROM sys.objects
WHERE object_id = OBJECT_ID(N'dbo.RegExIsMatch') )
DROP FUNCTION dbo.RegExIsMatch
go
IF EXISTS ( SELECT 1
FROM sys.assemblies asms
WHERE asms.name = N'RegExFunction ' )
DROP ASSEMBLY [RegExFunction]
CREATE ASSEMBLY RegExFunction
FROM '%FILE%'
GO
CREATE FUNCTION RegExIsMatch
(
@Pattern NVARCHAR(4000),
@Input NVARCHAR(MAX),
@Options int
)
RETURNS BIT
AS EXTERNAL NAME
RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO
--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)
As commented on the approved story, the HttpServerUtility.UrlEncode method replaces spaces with + instead of %20. Use one of these two methods instead: Uri.EscapeUriString() or Uri.EscapeDataString()
Sample code:
HttpUtility.UrlEncode("https://mywebsite.com/api/get me this file.jpg")
//Output: "https%3a%2f%2fmywebsite.com%2fapi%2fget+me+this+file.jpg"
Uri.EscapeUriString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https://mywebsite.com/api/get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%20me%20this%20file.jpg"
//When your url has a query string:
Uri.EscapeUriString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https://mywebsite.com/api/get?id=123&name=get%20me%20this%20file.jpg"
Uri.EscapeDataString("https://mywebsite.com/api/get?id=123&name=get me this file.jpg");
//Output: "https%3A%2F%2Fmywebsite.com%2Fapi%2Fget%3Fid%3D123%26name%3Dget%20me%20this%20file.jpg"
if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:
!conda list cudatoolkit
!conda list cudnn
and to check if the gpu is visible to tf:
tf.test.is_gpu_available(
cuda_only=False, min_cuda_compute_capability=None
)
this solution work for me ,
To revise IIS
Select Application Pools.
Clic in ASP .NET V4.0 Classic.
Select Advanced Settings.
In General, option Enable 32-Bit Applications, default is false. Select TRUE.
Refresh and check site.
Comment:
Platform: Windows Server 2012 Standart- 64Bit - IIS 8
Use a regular expression for .replace()
.:
messagetoSend = messagetoSend.replace(/\n/g, "<br />");
If those linebreaks were made by windows-encoding, you will also have to replace the carriage return
.
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");
Use the following syntax to check if the element actually exists using jQuery.
let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
Sometimes I use an attribute of a function for caching already computed values. You can also have a generic decorator that generalizes this approach. Be aware of concurrency issues and side effects of such functions!
I've use this :
except (socket.timeout, KeyboardInterrupt) as e:
logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
break
Let me know if it does not work for you !!
const oldFunction = params => {
// do something
};
const clonedFunction = (...args) => oldFunction(...args);
You can run the following command to list the content of your keystore file (and alias name):
keytool -v -list -keystore .keystore
If you are looking for a specific alias, you can also specify it in the command:
keytool -list -keystore .keystore -alias foo
If the alias is not found, it will display an exception:
keytool error: java.lang.Exception: Alias does not exist
in swift it quite simple
Write this code in ViewDidLoad() function
let tap = UITapGestureRecognizer(target: self, action: #selector(tapHandler(gesture:)))
tap.numberOfTapsRequired = 2
tapView.addGestureRecognizer(tap)
The Handler Part this could be in viewDidLoad or outside the viewDidLoad, batter is put in extension
@objc func tapHandler(gesture: UITapGestureRecognizer) {
currentGestureStates.text = "Double Tap"
}
here i'm just testing the code by printing the output if you want to make an action you can do whatever you want or more practise and read
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
I keep hearing people say they're forking code in git. Git "fork" sounds suspiciously like git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in git, right?
"Forking" is a concept, not a command specifically supported by any version control system.
The simplest kind of forking is synonymous with branching. Every time you create a branch, regardless of your VCS, you've "forked". These forks are usually pretty easy to merge back together.
The kind of fork you're talking about, where a separate party takes a complete copy of the code and walks away, necessarily happens outside the VCS in a centralized system like Subversion. A distributed VCS like Git has much better support for forking the entire codebase and effectively starting a new project.
Git (not GitHub) natively supports "forking" an entire repo (ie, cloning it) in a couple of ways:
origin
is created for youorigin
equivalentsGit makes contributing changes back to the source of the fork as simple as asking someone from the original project to pull from you, or requesting write access to push changes back yourself. This is the part that GitHub makes easier, and standardizes.
Any angst over Github extending git in this direction? Or any rumors of git absorbing the functionality?
There is no angst because your assumption is wrong. GitHub "extends" the forking functionality of Git with a nice GUI and a standardized way of issuing pull requests, but it doesn't add the functionality to Git. The concept of full-repo-forking is baked right into distributed version control at a fundamental level. You could abandon GitHub at any point and still continue to push/pull projects you've "forked".
Official FAQ ( https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate ) now recommends this way if you really need to do it:
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
function handleClick() {
forceUpdate();
}
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
The current answers are a bit out of date so, for clarity:
The short answer is:
This is documented on GitHub: duplicating-a-repository
I decided to use the json2 library and I got an error about “cyclic data structures”.
I got it solved by telling json2 how to convert my complex object. Not only it works now but also I have included only the fields I need. Here is how I did it:
OBJ.prototype.toJSON = function (key) {
var returnObj = new Object();
returnObj.devid = this.devid;
returnObj.name = this.name;
returnObj.speed = this.speed;
returnObj.status = this.status;
return returnObj;
}
A jar file is just a zip file with a structured manifest. You can open the jar file with the usual java zip tools and scan the file contents that way, inflate streams, etc. Then use that in a getResourceAsStream call, and it should be all hunky dory.
EDIT / after clarification
It took me a minute to remember all the bits and pieces and I'm sure there are cleaner ways to do it, but I wanted to see that I wasn't crazy. In my project image.jpg is a file in some part of the main jar file. I get the class loader of the main class (SomeClass is the entry point) and use it to discover the image.jpg resource. Then some stream magic to get it into this ImageInputStream thing and everything is fine.
InputStream inputStream = SomeClass.class.getClassLoader().getResourceAsStream("image.jpg");
JPEGImageReaderSpi imageReaderSpi = new JPEGImageReaderSpi();
ImageReader ir = imageReaderSpi.createReaderInstance();
ImageInputStream iis = new MemoryCacheImageInputStream(inputStream);
ir.setInput(iis);
....
ir.read(0); //will hand us a buffered image
In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:
sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient
with pygame:
dy = p1.y - p2.y
dX = p2.x - p1.x
rads = atan2(dy,dx)
degs = degrees(rads)
if degs < 0 :
degs +=90
it work for me
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
Use the CSS function from jQuery to set styles to your items :
$('#buttonId').css({ "background-color": 'brown'});
var audio = new Audio("http://rho.nu/pub/Game%20Of%20Thrones%20-%20Main%20Theme%20-%20Soundtrack.mp3");
audio.addEventListener('canplaythrough', function() {
this.currentTime = this.duration - 10;
this.loop = true;
this.play();
});
Just set loop = true in the canplaythrough eventlistener.
The best way to work with already created tables is that, Go to Sql Server Query Editor
Type: sp_help <tablename>
This will show table's structure , see the details for the desired field under COLLATE column.
then type in the query like :
SELECT myColumn FROM myTable
WHERE myColumn COLLATE SQL_Latin1_General_CP1_CI_AS = 'Case'
It could be different character schema <SQL_Latin1_General_CP1_CI_AS
>, so better to find out the exact schema that has been used against that column.
Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.
Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value
However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...
Code:
Cells(1, 3).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
Seek Bar has methods for setting max values but not for setting min value here i write a code for setting minimum seek bar value when we add this code then your seek bar values not less then mim value try this its work fine for me
/* This methods call after seek bar value change */
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
/* Check the current seekbar value is greather than min value*/
if (progress < MIN_VALUE) {
/* if seek bar value is lesser than min value then set min value to seek bar */
seekBar.setProgress(MIN_VALUE);
}
}
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
this link explains what cause the problem and the quick solve to the problem, it just by updating visual studio and it provide the link for the update
You need to use jQuery('#bar')[0].click();
to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger()
jQuery method.
Note: DOM Level 2 .click()
doesn't work on some elements in Safari. You will need to use a workaround.
Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.
And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
You were so close! The kill -HUP
method wasn't working for me either.
You were calling:
select @@global.max_connections;
All you needed was to set instead of select:
set @@global.max_connections = 400;
See:
http://www.netadmintools.com/art573.html
http://www.electrictoolbox.com/update-max-connections-mysql/
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.
Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).
Edited 2011-04-06:
The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com
domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)
Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.
Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.
Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).
Many 3rd party JavaScript libraries allow you to select all elements that have a CSS class of a particular name applied to them. Then you can iterate those elements and dynamically attach the handler.
There is no CSS-specific manner to do this.
In JQuery, you can do:
$(".myCssClass").click(function() { alert("hohoho"); });
You can also try out ctrl + alt + I even though you can also use l as well.
I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository
I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...
Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.
numpy already allows the creation of arrays of all ones or all zeros very easily:
e.g. numpy.ones((2, 2))
or numpy.zeros((2, 2))
Since True
and False
are represented in Python as 1
and 0
, respectively, we have only to specify this array should be boolean using the optional dtype
parameter and we are done.
numpy.ones((2, 2), dtype=bool)
returns:
array([[ True, True],
[ True, True]], dtype=bool)
UPDATE: 30 October 2013
Since numpy version 1.8, we can use full
to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):
numpy.full((2, 2), True, dtype=bool)
UPDATE: 16 January 2017
Since at least numpy version 1.12, full
automatically casts results to the dtype
of the second parameter, so we can just write:
numpy.full((2, 2), True)
For py2/py3 compatibility simply use
import six
if isinstance(obj, six.text_type)
Big thanks to Lars Blumberg his answer for capturing groups and full matches with Swift 4, which helped me out a lot. I also made an addition to it for the people who do want an error.localizedDescription response when their regex is invalid:
extension String {
func matchingStrings(regex: String) -> [[String]] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
For me having the localizedDescription as error helped understand what went wrong with escaping, since it's displays which final regex swift tries to implement.
I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com
" ".join(my_list)
you need to join with a space not an empty string ...
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break
, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li
be a list or tuple. It could be any iterator.
from itertools import cycle
li = [0, 1, 2, 3]
running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
thiselem, nextelem = nextelem, next(licycle)
I'm leaving the other solutions here for posterity.
All of that fancy iterator stuff has its place, but not here. Use the % operator.
li = [0, 1, 2, 3]
running = True
while running:
for idx, elem in enumerate(li):
thiselem = elem
nextelem = li[(idx + 1) % len(li)]
Now, if you intend to infinitely cycle through a list, then just do this:
li = [0, 1, 2, 3]
running = True
idx = 0
while running:
thiselem = li[idx]
idx = (idx + 1) % len(li)
nextelem = li[idx]
I think that's easier to understand than the other solution involving tee
, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li)
and use that.
This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running
in the middle of the for
loop and then break
.
You need 2 main things :
- Add @ServletComponentScan
to your Main Class
- you may add a package named filter inside it you create a Filter
Class that has the following :
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {
// whatever field you have
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
// whatever implementation you want
try {
chain.doFilter(req, res);
} catch(Exception e) {
e.printStackTrace();
}
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Grab the radio group and look at the children to see if any are unchecked.
RadioGroup rg = (RadioGroup) view;
int checked = savedInstanceState.getInt(wrap.getAttributeName());
if(checked != -1) {
RadioButton btn = (RadioButton) rg.getChildAt(checked);
btn.toggle();
}
Another bash variant
$ cat file
XXXX col1 col2 col3
row1 0 1 2
row2 3 4 5
row3 6 7 8
row4 9 10 11
Script
#!/bin/bash
I=0
while read line; do
i=0
for item in $line; { printf -v A$I[$i] $item; ((i++)); }
((I++))
done < file
indexes=$(seq 0 $i)
for i in $indexes; {
J=0
while ((J<I)); do
arr="A$J[$i]"
printf "${!arr}\t"
((J++))
done
echo
}
Output
$ ./test
XXXX row1 row2 row3 row4
col1 0 3 6 9
col2 1 4 7 10
col3 2 5 8 11
String message = URLEncoder.encode("my message", "UTF-8");
try {
// instantiate the URL object with the target URL of the resource to
// request
URL url = new URL("http://www.example.com/comment");
// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
connection.setDoOutput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");
// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write("message=" + message);
// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.
From getOutputStream:
Returns an output stream that writes to this connection.
Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream
basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream
, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);
.
From getInputStream():
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
getInputStream
does the opposite. Like getOutputStream
, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException
.
How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?
Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection()
, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.
In layman's terms, making a getInputStream
request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.
Using a similar example for getOutputStream
would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.
Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)
Question #5:
Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.
openConnection
creates a new connection object. From the URL.openConnection javadocs:
A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.
The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.
Question #6:
To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:
long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );
// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.
For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
This is so good answer. You can use this with angular like this:
moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
return function(htmlCode) {
var txt = document.createElement("textarea");
txt.innerHTML = htmlCode;
return $sce.trustAsHtml(txt.value);
}
}]);
In order to clear all local notifications in iOS 10 apps, you should use the following code:
import UserNotifications
...
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests() // To remove all pending notifications which are not delivered yet but scheduled.
center.removeAllDeliveredNotifications() // To remove all delivered notifications
} else {
UIApplication.shared.cancelAllLocalNotifications()
}
This code handles the clearing of local notifications for iOS 10.x and all preceding versions of iOS. You will need to import UserNotifications
for the iOS 10.x code.
@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU
system, they can do this:
tar cvf - folderToCompress | gzip > compressFileName
To expand the archive:
zcat compressFileName | tar xvf -
There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.
Nick's answer shows how you can do something similar that handles arbitrary types using interface{}
. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{}
type)
My other answer shows how you can do something similar that avoids creating a type using anonymous structs.
These techniques have some properties of tuples, but no, they are not tuples.
Typical usage for conditional removal of error from Model State:
Example:
public ActionResult MyAction(MyViewModel vm)
{
// perform conditional test
// if true, then remove from ModelState (e.g. ModelState.Remove("MyKey")
// Do typical model state validation, inside following if:
// if (!ModelState.IsValid)
// Do rest of logic (e.g. fetching, saving
In your example, keep everything as is and add the logic suggested to your Controller's Action. I'm assuming your ViewModel passed to the controller action has the Person and Senior Person objects with data populated in them from the UI.
I did some speed testing on various functions to return the full path to all current subdirectories.
tl;dr:
Always use scandir
:
list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
Bonus: With scandir
you can also simply only get folder names by using f.name
instead of f.path
.
This (as well as all other functions below) will not use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026
Results:
scandir
is: 3x faster than walk
, 32x faster than listdir
(with filter), 35x faster than Pathlib
and 36x faster than listdir
and 37x (!) faster than glob
.
Scandir: 0.977
Walk: 3.011
Listdir (filter): 31.288
Pathlib: 34.075
Listdir: 35.501
Glob: 36.277
Tested with W7x64, Python 3.8.1. Folder with 440 subfolders.
In case you wonder if listdir
could be speed up by not doing os.path.join() twice, yes, but the difference is basically nonexistent.
Code:
import os
import pathlib
import timeit
import glob
path = r"<example_path>"
def a():
list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
# print(len(list_subfolders_with_paths))
def b():
list_subfolders_with_paths = [os.path.join(path, f) for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
# print(len(list_subfolders_with_paths))
def c():
list_subfolders_with_paths = []
for root, dirs, files in os.walk(path):
for dir in dirs:
list_subfolders_with_paths.append( os.path.join(root, dir) )
break
# print(len(list_subfolders_with_paths))
def d():
list_subfolders_with_paths = glob.glob(path + '/*/')
# print(len(list_subfolders_with_paths))
def e():
list_subfolders_with_paths = list(filter(os.path.isdir, [os.path.join(path, f) for f in os.listdir(path)]))
# print(len(list(list_subfolders_with_paths)))
def f():
p = pathlib.Path(path)
list_subfolders_with_paths = [x for x in p.iterdir() if x.is_dir()]
# print(len(list_subfolders_with_paths))
print(f"Scandir: {timeit.timeit(a, number=1000):.3f}")
print(f"Listdir: {timeit.timeit(b, number=1000):.3f}")
print(f"Walk: {timeit.timeit(c, number=1000):.3f}")
print(f"Glob: {timeit.timeit(d, number=1000):.3f}")
print(f"Listdir (filter): {timeit.timeit(e, number=1000):.3f}")
print(f"Pathlib: {timeit.timeit(f, number=1000):.3f}")
You can use std::find
for this:
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
int main ()
{
int a[] = {3, 6, 8, 33};
int x = 8;
bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}
std::find
returns an iterator to the first occurrence of x
, or an iterator to one-past the end of the range if x
is not found.
Use a JSON parser, like JSON.NET
string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();
Incase someone is still trying to figure this out. This is how you get the center X and Y of the view
.
int pos[] = new int[2];
view.getLocationOnScreen(pos);
int centerX = pos[0] + view.getMeasuredWidth() / 2;
int centerY = pos[1] + view.getMeasuredHeight() / 2;
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
As mentioned by other folks, the variable length of the string is the issue.
Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.
StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.
Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.
Install flask-cors
pip install -U flask-cors
then after app initialization, initialize flask-cors
with default arguments:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static
if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.
It is more of a guideline than a rule, really...
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”
As stated by Maxim Dounin in the comments above:
When nginx returns 400 (Bad Request) it will log the reason into error log, at "info" level. Hence an obvious way to find out what's going on is to configure error_log to log messages at "info" level and take a look into error log when testing.
Perhaps their problem is the moment when the search is made in the database. In his Fragment Override cycles of its Fragment.java to figure out just: try testing with the methods:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_x, container, false); //Your query and ListView code probably will be here
Log.i("FragmentX", "Step OnCreateView");// Try with it
return rootView;
}
Try it similarly put Log.i
... "onStart" and "onResume".
Finally cut the code in "onCreate" e put it in "onStart" for example:
@Override
public void onStart(){
super.onStart();
Log.i("FragmentX","Step OnStart");
dbManager = new DBManager(getContext());
Cursor cursor = dbManager.getAllNames();
listView = (ListView)getView().findViewById(R.id.lvNames);
adapter = new CustomCursorAdapter(getContext(),cursor,0);// your adapter
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
Russian Edition
offers CSV
, CSV (Macintosh)
and CSV (DOS)
.
When saving in plain CSV
, it uses windows-1251
.
I just tried to save French word Résumé
along with the Russian text, it saved it in HEX
like 52 3F 73 75 6D 3F
, 3F
being the ASCII
code for question mark
.
When I opened the CSV
file, the word, of course, became unreadable (R?sum?
)
This is example code that works for sure. It took me a day to make this to read a set of objects from a REST service:
RootObject is the type of the object I'm reading from the REST service.
string url = @"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<RootObject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<RootObject> countries = (IEnumerable<RootObject>)serializer.ReadObject(memo);
}
Console.Read();
Typecasting in Objective-C is easy as:
NSArray *threeViews = @[[UIView new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
However, what happens if first object is not UIView
and you try to use it:
NSArray *threeViews = @[[NSNumber new], [UIView new], [UIView new]];
UIView *firstView = (UIView *)threeViews[0];
CGRect firstViewFrame = firstView.frame; // CRASH!
It will crash. And it's easy to find such crash for this case, but what if those lines are in different classes and the third line is executed only once in 100 cases. I bet your customers find this crash, not you! A plausible solution is to crash early, like this:
UIView *firstView = (UIView *)threeViews[0];
NSAssert([firstView isKindOfClass:[UIView class]], @"firstView is not UIView");
Those assertions doesn't look very nice, so we could improve them with this handy category:
@interface NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object;
@end
@implementation NSObject (TypecastWithAssertion)
+ (instancetype)typecastWithAssertion:(id)object {
if (object != nil)
NSAssert([object isKindOfClass:[self class]], @"Object %@ is not kind of class %@", object, NSStringFromClass([self class]));
return object;
}
@end
This is much better:
UIView *firstView = [UIView typecastWithAssertion:[threeViews[0]];
P.S. For collections type safety Xcode 7 have a much better than typecasting - generics
Several reasons:
String.Format()
is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.String.Format()
is often faster, as it uses a StringBuilder
and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.String.Format()
is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf()
function.Finally, don't forget StringBuilder.AppendFormat()
. String.Format()
actually uses this method behind the scenes*, and going to the StringBuilder
directly can give you a kind of hybrid approach: explicitly use .Append()
(analogous to concatenation) for some parts of a large string, and use .AppendFormat()
in others.
* [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.
In Opera, try:
print_win.document.write('</body></html>');
print_win.document.close(); // This bit is important
print_win.print();
print_win.close();
The function ob_start() will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So browser will not receive any output and the header will work.Also we should make sure that header() is used on the top of the code.
Not a direct answer but it could help.
I run most of my dockerized services tied to own static ips using the next approach:
Sample:
docker run --name dns --restart=always -d -p 172.16.177.20:53:53/udp dns
docker run --name registry --restart=always -d -p 172.16.177.12:80:5000 registry
docker run --name cache --restart=always -d -p 172.16.177.13:80:3142 -v /data/cache:/var/cache/apt-cacher-ng cache
docker run --name mirror --restart=always -d -p 172.16.177.19:80:80 -v /data/mirror:/usr/share/nginx/html:ro mirror
...
Nothing. It was added to the C99 standard.
If it's always the third column, you can use this (assuming table class of "products"). It's kinda hacky though, and not robust if you add a new column.
table.products td+td+td {
text-align: right;
}
table.products td,
table.products td+td+td+td {
text-align: left;
}
But honestly, the best idea is to use a class on each cell. You can use the col
element to set the width, border, background or visibility of a column, but not any other properties. Reasons discussed here.
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
You can do it like this:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".
No, this is not possible. However, one could do something like this:
List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);
This requires using wrappers, and is a List, not an array, but is the closest you will get.
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Contains
calls IndexOf
:
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
Which calls CompareInfo.IndexOf
, which ultimately uses a CLR implementation.
If you want to see how strings are compared in the CLR this will show you (look for CaseInsensitiveCompHelper).
IndexOf(string)
has no options and Contains()
uses an Ordinal compare (a byte-by-byte comparison rather than trying to perform a smart compare, for example, e with é).
So IndexOf
will be marginally faster (in theory) as IndexOf
goes straight to a string search using FindNLSString from kernel32.dll (the power of reflector!).
Updated for .NET 4.0 - IndexOf no longer uses Ordinal Comparison and so Contains can be faster. See comment below.
I had a similar issue with PyVmomi Client. With Python Version 2.7.9, I have solved this issue with the following line of code:
default_sslContext = ssl._create_unverified_context()
self.client = \
Client(<vcenterip>, username=<username>, password=<passwd>,
sslContext=default_sslContext )
Note that, for this to work, you need Python 2.7.9 atleast.
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
substring(field, 1,3) will work on your examples.
select substring(field, 1,3) from table
Also, if the alphabetic part is of variable length, you can do this to extract the alphabetic part:
select substring(field, 1, PATINDEX('%[1234567890]%', field) -1)
from table
where PATINDEX('%[1234567890]%', field) > 0
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s
instead:
.replace(/\s/g,'')
You can also use .replaceAll
if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll
, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
firstarray
and secondarray
are converted to a pointer to int, when passed to printarray()
.
printarray(int arg[], ...)
is equivalent to printarray(int *arg, ...)
However, this is not specific to C++. C has the same rules for passing array names to a function.
IETF has suggested jose libs on it's wiki: http://trac.tools.ietf.org/wg/jose/trac/wiki
I would highly recommend using them for signing. I am not a Java guy, but seems like jose4j seems like a good option. Has nice examples as well: https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples
Update: jwt.io provides a neat comparison of several jwt related libraries, and their features. A must check!
I would love to hear about what other java devs prefer.
None of the answers seemed to work for me or were too complicated. Luckily, it's not complicated with xargs
(Tested on Ubuntu 20.04).
This works with each arg on a separate line in the file as the OP mentions and was what I needed as well.
cat foo.txt | xargs my_command
One thing to note is that it doesn't seem to work with aliased commands.
The accepted answer works if the command accepts multiple args wrapped in a string. In my case using (Neo)Vim it does not and the args are all stuck together.
xargs
does it probably and actually gives you separate arguments supplied to the command.
You can use jquery.chosen or bootstrap-select to add style to your buttons.Both work great. Caveat for Using Chosen or bootstrap-select: they both hide the original select and add in their own div with its own ID. If you are using jquery.validate along with this, for instance, it wont find the original select to do its validation on because it has been renamed.
Create a new table called comments
They should have a column containing the id of the post they are assigned to.
Make a form which adds a new comment to that table.
An example (not tested so may contain lil' syntax errors): I call a page with comments a post
Post.php
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>
insertcomment.php
<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)
Install this package in Ubuntu
:
apt install sysv-rc-conf
its a substitute for chkconfig
cmd.
After install run this cmd:
sysv-rc-conf --list
It'll show all services in all the runlevels. You can also run this:
sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )
Now you can choose which service should be active in boot time.
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
open dconf Editor and go to org > gnome > desktop > application > terminal and change gnome-terminal to terminator
I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.
If print it out in the console, or in a message box, does it show with two backslashes or one?
If you actually want to replace a double backslash with a single one, it's easy to do so:
text = text.Replace(@"\\", @"\");
... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.
EDIT: In response to the edited question, your stringToBeReplaced
only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length
and count the characters.
It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.
The EASIEST way to change WITHOUT modifying the underlying data is:
as_labeller
function adding the back tick mark for each of the default values:# Necessary to put RH% into the facet labels
hum.names <- as_labeller(
c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70",
`80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))
ggplot(dataframe, aes(x = Temperature.C, y = fit)) +
geom_line() +
facet_wrap(~Humidity.RH., nrow = 2, labeller = hum.names)
This page lists some simple hash functions that tend to decently in general, but any simple hash has pathological cases where it doesn't work well.
Shorter version of previous using map()
function (works for python 2.7):
"".join(map(chr, myList))
I think that you can make some changes in your data format when you create dictionary, then you can easily convert it to DataFrame:
input:
a={'Dates':['2012-06-08','2012-06-10'],'Date_value':[388,389]}
output:
{'Date_value': [388, 389], 'Dates': ['2012-06-08', '2012-06-10']}
input:
aframe=DataFrame(a)
output: will be your DataFrame
You just need to use some text editing in somewhere like Sublime or maybe Excel.
Here it fails at Array.apply(null, new Array(1000000))
and not the .map
call.
All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.
You need to the understand what is call stack.
Stack is a LIFO data structure, which is like an array that only supports push and pop methods.
Let me explain how it works by a simple example:
function a(var1, var2) {
var3 = 3;
b(5, 6);
c(var1, var2);
}
function b(var5, var6) {
c(7, 8);
}
function c(var7, var8) {
}
When here function a
is called, it will call b
and c
. When b
and c
are called, the local variables of a
are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.
We implement the callStack as array:
var callStack = [];
Everytime a function called we push the local variables into the stack:
callStack.push(currentLocalVaraibles);
Once the function call is finished(like in a
, we have called b
, b
is finished executing and we must return to a
), we get back the local variables by poping the stack:
currentLocalVaraibles = callStack.pop();
So when in a
we want to call c
again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000))
, your currentLocalVariables
object will be huge because it will have 1000000
variables inside. Since .apply
will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.
Same error happens on infinite recursion(function a() { a() }
) as too many times, stuff has been pushed to the call stack.
Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.
var img = new Image();
img.src = sYourFilePath;
var iSize = img.fileSize;
if you have remote server installed on you machine. give server.py host as "localhost" and the port number. then client side , you have to give local ip- 127.0.0.1 and port number. then its works
according to me this answer is useful for you:
def casear(a,key):
str=""
if key>26:
key%=26
for i in range(0,len(a)):
if a[i].isalpha():
b=ord(a[i])
b+=key
#if b>90: #if upper case letter ppear in your string
# c=b-90 #if upper case letter ppear in your string
# str+=chr(64+c) #if upper case letter ppear in your string
if b>122:
c=b-122
str+=chr(96+c)
else:
str+=chr(b)
else:
str+=a[i]
print str
a=raw_input()
key=int(input())
casear(a,key)
This function shifts all letter to right according to given key.
XAMPP does not have a pre build console to run php
or mysql
commands, so, you have to add to windows PATH
environment variables, these 2: ;C:\xampp\mysql\bin;C:\xampp\php;
Then you should be able to execute php
and mysql
commands from the CMD.
I tested it, and it works.
Just wanted to add this little snippet which works beautifully for me.
INSERT INTO your_target_table SELECT * FROM your_rescource_table WHERE id = 18;
And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier
See this example: https://jsfiddle.net/pqhdce2L/
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
contentType = contentType || '';_x000D_
sliceSize = sliceSize || 512;_x000D_
_x000D_
var byteCharacters = atob(b64Data);_x000D_
var byteArrays = [];_x000D_
_x000D_
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
var byteNumbers = new Array(slice.length);_x000D_
for (var i = 0; i < slice.length; i++) {_x000D_
byteNumbers[i] = slice.charCodeAt(i);_x000D_
}_x000D_
_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
byteArrays.push(byteArray);_x000D_
}_x000D_
_x000D_
var blob = new Blob(byteArrays, {type: contentType});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
I received this error because I had made a mistake in the definition of my method. I had declared the method to accept a generic type (notice the "T" after the method name):
protected int InsertRecord<T>(CoasterModel model, IDbConnection con)
However, when I called the method, I did not use the type which, in my case, was the correct usage:
int count = InsertRecord(databaseToMigrateFrom, con);
I just removed the generic casting and it worked.
I used this Unicode Decimal Code ‌
and worked. more details
Default user for MySQL is "root", and server "localhost".
I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!
SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');
The current best way to do this is to use df.to_string()
:
with open(writePath, 'a') as f:
f.write(
df.to_string(header = False, index = False)
)
Will output the following
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70
This method also lets you easily choose which columns to print with the columns
attribute, lets you keep the column, index labels if you wish, and has other attributes for spacing ect.
[HttpPost]
public JsonResult DeleteCotnact(int id)
{
using (MycasedbEntities dbde = new MycasedbEntities())
{
Contact rowcontact = (from c in dbde.Contact
where c.Id == id
select c).FirstOrDefault();
dbde.Contact.Remove(rowcontact);
dbde.SaveChanges();
return Json(id);
}
}
What do you think of this, simple or not, you could also try this:
var productrow = cnn.Product.Find(id);
cnn.Product.Remove(productrow);
cnn.SaveChanges();
Starting simple, with no HTML:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
And you can otherwise manipulate the fields in the foreach.
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
Following @armod's update about exceptions being added right on client
objects. I'll show how you can see all exceptions defined for your client class.
Exceptions are generated dynamically when you create your client with session.create_client()
or boto3.client()
. Internally it calls method botocore.errorfactory.ClientExceptionsFactory._create_client_exceptions()
and fills client.exceptions
field with constructed exception classes.
All class names are available in client.exceptions._code_to_exception
dictionary, so you can list all types with following snippet:
client = boto3.client('s3')
for ex_code in client.exceptions._code_to_exception:
print(ex_code)
Hope it helps.
Another way is from command line, using the osql:
OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt
This can be used from a BAT file and shceduled by a windows user to authenticated.
For iOS 5.1 this is further changed to new path
~/Library/Application Support/iPhone Simulator/5.1/Media/DCIM/100APPLE
Try this:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'
Also in MySQL, you can FROM_UNIXTIME
like:
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))
For your 2nd question, it is probably because getbbb_class.end_time
is a string. You can convert it to numeric like: float(getbbb_class.end_time)
show variables
Show variables like "`secure_file_priv`";
Note: keep your csv file in location given by the above command.
create table assessments (course_code varchar(5),batch_code varchar(7),id_assessment int, assessment_type varchar(10), date int , weight int);
Note: here the 'date
' column has some blank values in the csv file.
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/assessments.csv'
INTO TABLE assessments
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY ''
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(course_code,batch_code,id_assessment,assessment_type,@date,weight)
SET date = IF(@date = '', NULL, @date);
The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
Here's an example to use ngclick & ng-if directives.
Note: that ng-if removes the element from the DOM, but ng-hide just hides the display of the element.
<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
Enter book name: <input type = "text" ng-model = "book.name"><br>
Enter book category: <input type = "text" ng-model = "book.category"><br>
Enter book price: <input type = "text" ng-model = "book.price"><br>
Enter book author: <input type = "text" ng-model = "book.author"><br>
You are entering book: {{book.bookDetails()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('bookController', function($scope) {
$scope.book = {
name: "",
category: "",
price:"",
author: "",
bookDetails: function() {
var bookObject;
bookObject = $scope.book;
return "Book name: " + bookObject.name + '\n' + "Book category: " + bookObject.category + " \n" + "Book price: " + bookObject.price + " \n" + "Book Author: " + bookObject.author;
}
};
});
</script>
Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)
// WRONG
public class DataWrapper {
final Data data;
final String description;
public DataWrapper(Object data, String description) {
this.data = data;
this.description = description;
}
....
@Override
public String toString() {
return description;
}
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());
It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).
The driving forces for breaking of rules were:
As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.
While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.
We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)
In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:
StringValue sv = new StringValue() {
@Override
public String getString(Object value) {
if (value instanceof Data) {
return ((Data) value).getSomeProperty();
}
return TO_STRING.getString(value);
}
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);
As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:
public BetterKeySelectionManager implements KeySelectionManager {
@Override
public int selectionForKey(char ch, ComboBoxModel model) {
....
if (getCellRenderer() instance of StringValue) {
String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
....
}
}
}
Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:
All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
$ hadoop fs -rmdir {directory_name}
Wouldn't establishing a connection to the database do this for you? If the database isn't up you won't be able to establish a connection.
<h2 [ngStyle]="serverStatus == 'Offline'? {'color': 'red'{'color':'green'}">Server with ID: {{serverId}} is {{getServerStatus()}} </h2>
or you can also use something like this:
<h2 [ngStyle]="{backgroundColor: getColor()}">Server with ID: {{serverId}} is {{getServerStatus()}}</h2>
and in the *.ts
getColor(){return this.serverStatus === 'Offline' ? 'red' : 'green';}
Adapted from this answer:
function scroll(y, duration) {
var initialY = document.documentElement.scrollTop || document.body.scrollTop;
var baseY = (initialY + y) * 0.5;
var difference = initialY - baseY;
var startTime = performance.now();
function step() {
var normalizedTime = (performance.now() - startTime) / duration;
if (normalizedTime > 1) normalizedTime = 1;
window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
if (normalizedTime < 1) window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
This should allow you to smoothly scroll (cosine function) from anywhere to the specified "y".
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:
GoDaddy SSL CCertificate
I've experienced this while trying to connect to our backend API server with GoDaddy certificate and here is the code that I used to solve the problem.
var rootCas = require('ssl-root-cas/latest').create();
rootCas
.addFile(path.join(__dirname, '../config/ssl/gd_bundle-g2-g1.crt'))
;
// will work with all https requests will all libraries (i.e. request.js)
require('https').globalAgent.options.ca = rootCas;
PS:
Use the bundled certificate and don't forget to install the library npm install ssl-root-cas
Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.
However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.
$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';
$trace = true;
$exceptions = false;
$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;
$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);
var_dump($response);
Add code in /wp-content/plugins/woocommerce/templates/
loop path
<?php
if ( is_product_category() ){
global $wp_query;
$cat = $wp_query->get_queried_object();
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo "<img src='{$image}' alt='' />";
}
?>
Jonathan Feinberg's answer prints each field on a separate line. You could use printf
to rebuild the record for output on the same line, but you can also just move the fields a jump to the left.
awk '{for (i=1; i<=NF-2; i++) $i = $(i+2); NF-=2; print}' logfile
In Windows we need to run $git difftool --tool-help
command to see the various options like:
'git difftool --tool=<tool>' may be set to one of the following:
vimdiff
vimdiff2
vimdiff3
The following tools are valid, but not currently available:
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff
Some of the tools listed above only work in a windowed
environment. If run in a terminal-only session, they will fail.
and we can add any of them(for example winmerge) like
$ git difftool --tool=winmerge
For configuring notepad++ to see files before committing:
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
and using $ git commit
will open the commit information in notepad++
The answers presented so far fail to check that the Base64 string has all pad bits set to 0, as required for it to be the canonical representation of Base64 (which is important in some environments, see https://tools.ietf.org/html/rfc4648#section-3.5) and therefore, they allow aliases that are different encodings for the same binary string. This could be a security problem in some applications.
Here is the regexp that verifies that the given string is not just valid base64, but also the canonical base64 string for the binary data:
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$
The cited RFC considers the empty string as valid (see https://tools.ietf.org/html/rfc4648#section-10) therefore the above regex also does.
The equivalent regular expression for base64url (again, refer to the above RFC) is:
^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-][AQgw]==|[A-Za-z0-9_-]{2}[AEIMQUYcgkosw048]=)?$
You need to put the directory that has php.exe
in you WAMP
installation into your PATH
. It is usually something like C:\wamp\xampp\php
change the app string resource to your new activity
For me the issue resolved when i updated the appcompact v7 to latest..
compile 'com.android.support:appcompat-v7:25.3.0'
Hope it helps...:)
If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:
select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;
Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.
Here's a shell script I wrote for the use case of a single subdirectory sparse checkout
localRepo=$1
remoteRepo=$2
subDir=$3
# Create local repository for subdirectory checkout, make it hidden to avoid having to drill down to the subfolder
mkdir ./.$localRepo
cd ./.$localRepo
git init
git remote add -f origin $remoteRepo
git config core.sparseCheckout true
# Add the subdirectory of interest to the sparse checkout.
echo $subDir >> .git/info/sparse-checkout
git pull origin master
# Create convenience symlink to the subdirectory of interest
cd ..
ln -s ./.$localRepo/$subDir $localRepo
Native JSON support has been included in PHP since 5.2 in the form of methods json_encode()
and json_decode()
. You would use the first to output a PHP variable in JSON.
@user.route('/<userId>/') # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
pass
https://flask.palletsprojects.com/en/1.1.x/quickstart/#unique-urls-redirection-behavior
Use:
thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();
This takes a JSON date, "/Date(1429573751663)/" and produces as the formatted string:
"4/21/2015"
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
this is probably the best way to use react-router-dom with a cookie handler
in index.js
import React, { Component } from 'react'
import {Switch,Route,Redirect} from "react-router-dom"
import {RouteWithLayout} from "./cookieCheck"
import Login from "../app/pages/login"
import DummyLayout from "../app/layouts/dummy"
import DummyPage from "../app/pages/dummy"
export default ({props})=>{
return(
<Switch>
<Route path="/login" component={Login} />
<RouteWithLayout path="/dummy" layout={DummyLayout} component={DummyPage}
{...props}/>
<Redirect from="/*" to="/login" />
</Switch>
)
}
and use a cookieCheck
import React , {createElement} from 'react'
import {Route,Redirect} from "react-router-dom"
import {COOKIE,getCookie} from "../services/"
export const RouteWithLayout = ({layout,component,...rest})=>{
if(getCookie(COOKIE)==null)return <Redirect to="/login"/>
return (
<Route {...rest} render={(props) =>
createElement(layout, {...props, ...rest}, createElement(component,
{...props, ...rest}))
}
/>
)
}
I know this is an old question, but I faced the same problem recently in Laravel 7 application.
To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal
I have issued composer require doctrine/dbal:^2.12.1
because the latest version of doctrine/dbal still throws an error.
Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
In AngularJS, we update our models, and our views/templates update the DOM "automatically" (via built-in or custom directives).
$apply and $watch, both being Scope methods, are not related to the DOM.
The Concepts page (section "Runtime") has a pretty good explanation of the $digest loop, $apply, the $evalAsync queue and the $watch list. Here's the picture that accompanies the text:
Whatever code has access to a scope – normally controllers and directives (their link functions and/or their controllers) – can set up a "watchExpression" that AngularJS will evaluate against that scope. This evaluation happens whenever AngularJS enters its $digest loop (in particular, the "$watch list" loop). You can watch individual scope properties, you can define a function to watch two properties together, you can watch the length of an array, etc.
When things happen "inside AngularJS" – e.g., you type into a textbox that has AngularJS two-way databinding enabled (i.e., uses ng-model), an $http callback fires, etc. – $apply has already been called, so we're inside the "AngularJS" rectangle in the figure above. All watchExpressions will be evaluated (possibly more than once – until no further changes are detected).
When things happen "outside AngularJS" – e.g., you used bind() in a directive and then that event fires, resulting in your callback being called, or some jQuery registered callback fires – we're still in the "Native" rectangle. If the callback code modifies anything that any $watch is watching, call $apply to get into the AngularJS rectangle, causing the $digest loop to run, and hence AngularJS will notice the change and do its magic.
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Here is the code that worked to me sure it will help you
<form name="loginBox" target="#here" method="post">
<input name="username" type="text" /><br />
<input name="password" type="password" />
<input type="submit" />
</form>
<script type="text/javascript">
$(function () {
$("form").each(function () {
$(this)
.find("input")
.keypress(function (e) {
if (e.which == 10 || e.which == 13) {
this.form.submit();
}
});
$(this).find("input[type=submit]").hide();
});
});
</script>
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {_x000D_
return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
var minutes = Math.floor(secs / 60);_x000D_
secs = secs%60;_x000D_
var hours = Math.floor(minutes/60)_x000D_
minutes = minutes%60;_x000D_
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
var d = new Date();_x000D_
var d1 = new Date(d.getTime()+s*1000);_x000D_
var hms = hhmmss(s);_x000D_
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
} _x000D_
*/
_x000D_
if (array.length>0) // edited in response Joachim's comment
sb.append(array[i]);
for (int i=1; i<array.length; i++)
sb.append(",").append(array[i]);
Based on Clearest way to comma-delimit a list (Java)?
Using this idea: Does the last element in a loop deserve a separate treatment?
If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:
var min = myData.OrderBy( cv => cv.Date1 ).First();
The above will return the entire object. If you just want the date returned:
var min = myData.Min( cv => cv.Date1 );
Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.
From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:
What about the future of LINQ to SQL?
It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.
I found this in the Cheetah source code (here)
htmlCodes = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
""" Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
for code in codes:
s = s.replace(code[1], code[0])
return s
not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)
i noticed your title asked for encode too, so here is Cheetah's encode function.
def htmlEncode(s, codes=htmlCodes):
""" Returns the HTML encoded version of the given string. This is useful to
display a plain ASCII text string on a web page."""
for code in codes:
s = s.replace(code[0], code[1])
return s
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
For instance:
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
As you see, simply adding the HttpServletRequest
and HttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession
object too.
EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.
I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.