If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
I put the year and the number series of my app example 2014-01
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
val list = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
// Using the provided count method this would yield the occurrences of each value in the list:
l map(x => l.count(_ == x))
List[Int] = List(1, 3, 3, 3, 3, 1, 1, 3, 3)
// This will yield a list of pairs where the first number is the number from the original list and the second number represents how often the first number occurs in the list:
l map(x => (x, l.count(_ == x)))
// outputs => List[(Int, Int)] = List((1,1), (2,3), (4,3), (2,3), (4,3), (7,1), (3,1), (2,3), (4,3))
IntelliJ should download and add all your dependencies to the project's classpath automatically as long as your POM is compliant and all the dependencies are available.
When importing Maven projects into IntelliJ an information box usually comes up asking you if you want to configure Auto-Import for Maven projects. That means that if you make any changes to your POM those changes will be loaded automatically.
You can enable such feature going to File > Settings > Maven > Importing, there is a checkbox that says "Import Maven projects automatically".
If that doesn't help, then I would suggest to make a full clean-up and start again:
*.iml
files and all .idea
folders (there should be one per module)mvn clean install
from the command lineIntelliJ 2016 Update:
The Import Maven Projects automatically setting has been moved to Build, Execution, Deployment > Build Tools > Maven > Importing in your IntelliJ preferences.
Looks like the solution as.numeric(levels(f))[f] no longer work with R 4.0.
Alternative solution:
factor2number <- function(x){
data.frame(levels(x), 1:length(levels(x)), row.names = 1)[x, 1]
}
factor2number(yourFactor)
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
The simple, secure, and correct answer is to use RandomLib and don't reinvent the wheel.
For those of you who insist on inventing your own solution, PHP 7.0.0 will provide random_int()
for this purpose; if you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int()
so you can use the new API even before you upgrade to PHP 7.
Safely generating random integers in PHP isn't a trivial task. You should always check with your resident StackExchange cryptography experts before you deploy a home-grown algorithm in production.
With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* This function uses type hints now (PHP 7+ only), but it was originally
* written for PHP 5 as well.
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @param int $length How many characters do we want?
* @param string $keyspace A string of all possible characters
* to select from
* @return string
*/
function random_str(
int $length = 64,
string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
if ($length < 1) {
throw new \RangeException("Length must be a positive integer");
}
$pieces = [];
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pieces []= $keyspace[random_int(0, $max)];
}
return implode('', $pieces);
}
Usage:
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
Demo: https://3v4l.org/IMJGF (Ignore the PHP 5 failures; it needs random_compat)
If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.
This works, since you are making an unreferenced copy:
const query = Object.assign({}, this.$route.query);
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated
error:
const query = this.$route.query;
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.
const { page, limit, ...otherParams } = this.$route.query;
await this.$router.push(Object.assign({
page: page,
limit: rowsPerPage
}, otherParams));
);
Note, while the above example is for push()
, this works with replace()
too.
Tested with vue-router 3.1.6.
If you need to store just simple values like API token or login data (not passwords!), here is what I used:
import 'package:shared_preferences/shared_preferences.dart';
asyncFunc() async { // Async func to handle Futures easier; or use Future.then
SharedPreferences prefs = await SharedPreferences.getInstance();
}
...
// Set
prefs.setString('apiToken', token);
// Get
String token = prefs.getString('apiToken');
// Remove
prefs.remove('apiToken');
Don't forget to add shared_preferences
dependency in your pubspec.yaml (preserve spacing format):
dependencies:
shared_preferences: any
first, in C:\users\your PC
write npm uninstall -g create-react-app
then, create your project folder with npx create-react-app folder-name
.
The collection used in foreach is immutable. This is very much by design.
As it says on MSDN:
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
This should work for you:
IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder
However, there is another method, but it may not be 100% useful:
md \path\to\your\folder >NUL 2>NUL
This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.
Try this:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
You have to change the ID of the button to be different from the function name JSFiddle
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
counter++;_x000D_
var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
newFields.id = '';_x000D_
newFields.style.display = 'block';_x000D_
var newField = newFields.childNodes;_x000D_
for (var i = 0; i < newField.length; i++) {_x000D_
var theName = newField[i].name_x000D_
if (theName) newField[i].name = theName + counter;_x000D_
}_x000D_
var insertHere = document.getElementById('writeroot');_x000D_
insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
<input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
<br />_x000D_
<br />_x000D_
<input name="cd" value="title" />_x000D_
<select name="rankingsel">_x000D_
<option>Rating</option>_x000D_
<option value="excellent">Excellent</option>_x000D_
<option value="good">Good</option>_x000D_
<option value="ok">OK</option>_x000D_
<option value="poor">Poor</option>_x000D_
<option value="bad">Bad</option>_x000D_
</select>_x000D_
<br />_x000D_
<br />_x000D_
<textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
<br />Radio buttons included to test them in Explorer:_x000D_
<br />_x000D_
<input type="radio" name="something" value="test1" />Test 1_x000D_
<br />_x000D_
<input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
<input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
<input type="submit" value="Send form" />_x000D_
</form>
_x000D_
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
You may use this formula to get the path of the file:
=LEFT(CELL("filename"),FIND("[",CELL("filename"),1)-1)
This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.
window.location.href = window.location.origin + window.location.pathname;
Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer
All the code is client side, I hope you fine this helpful:
First thing there are 3 functions we will use:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
Now we will start with the page load:
$(window).load(function () {
//if IsRefresh cookie exists
var IsRefresh = getCookie("IsRefresh");
if (IsRefresh != null && IsRefresh != "") {
//cookie exists then you refreshed this page(F5, reload button or right click and reload)
//SOME CODE
DeleteCookie("IsRefresh");
}
else {
//cookie doesnt exists then you landed on this page
//SOME CODE
setCookie("IsRefresh", "true", 1);
}
})
I guess that you are trying to play an .pls directly or something similar.
try this out:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();
2: the .pls file
This URL is from BBC just as an example. It was an .pls file that on linux i downloaded with
wget http://foo.bar/file.pls
and then i opened with vim (use your favorite editor ;) and i've seen the real URLs inside this file. Unfortunately not all of the .pls are plain text like that.
I've read that 1.6 would not support streaming mp3 over http, but, i've just tested the obove code with android 1.6 and 2.2 and didn't have any issue.
good luck!
Best I can give you is a "works for me" on SVN 1.5. You may try adding --no-auth-cache
to your svn update
to see if that lets you override more easily.
If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.
(I do realise the question is old, but it's among the top hits on Google.)
A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:
catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
doSomething(response.StatusCode)
}
This can easily be extended to further levels, such as in this case where the WebException
was actually the inner exception of another (and we're only interested in 404
):
catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)
Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.
There should not be a space after name
.
Incorrect:
{% url 'author' name = p.article_author.name.username %}
Correct:
{% url 'author' name=p.article_author.name.username %}
You can use the os Module:
var os = require("os");
os.hostname();
See http://nodejs.org/docs/latest/api/os.html#os_os_hostname
Caveats:
if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.
Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.
to disable back function of the back button:
window.addEventListener('popstate', function (event) {
history.pushState(null, document.title, location.href);
});
You could move the common parts to another configuration file and include
from both server contexts. This should work:
server {
listen 80;
server_name server1.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
server {
listen 80;
server_name another-one.example;
...
include /etc/nginx/include.d/your-common-stuff.conf;
}
Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled
(normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org
's configuration file is /etc/nginx/sites-enabled
and it looks like this:
server {
listen 80 default_server;
listen [2a01:4f8:120:3105::101:1]:80 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-80;
}
server {
listen 443 default_server;
listen [2a01:4f8:120:3105::101:1]:443 default_server;
include /etc/nginx/include.d/all-common;
include /etc/nginx/include.d/ssl-common;
include /etc/nginx/include.d/bunkus.org-common;
include /etc/nginx/include.d/bunkus.org-443;
}
As an example here's the /etc/nginx/include.d/all-common
file that's included from both server
contexts:
index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;
location ~ /\.ht {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location ~ /(README|ChangeLog)$ {
types { }
default_type text/plain;
}
FirstView
{
NSMutableArray *array; }
- (void)viewDidLoad {
[super viewDidLoad];
array = [[NSMutableArray alloc]init];
array = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"];
NSLog(@"%lu",(unsigned long)array.count);
if (array>0)
{
for (int i=0; i<array.count; i++)
{
NSDictionary *dict1 = @{@"Username":[[array valueForKey:@"Username"] objectAtIndex:i],@"Mobilenumber":[[array valueForKey:@"Mobilenumber"] objectAtIndex:i],@"Firstname":[[array valueForKey:@"Firstname"] objectAtIndex:i],@"Lastname":[[array valueForKey:@"Lastname"] objectAtIndex:i],@"dob":[[array valueForKey:@"dob"] objectAtIndex:i],@"image":[[array valueForKey:@"image"] objectAtIndex:i]};
NSLog(@"%@",dict1);
NSArray *array1 = [[NSArray alloc]initWithObjects:dict1, nil];
[[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"UserList"];
}
}
}
ImagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imaGe.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
(IBAction)submitBton:(id)sender {
NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray:
[[NSUserDefaults standardUserDefaults]objectForKey:
@"userlist"]];
UIImage *ima = _imaGe.image;
NSData *imagedata = UIImageJPEGRepresentation(ima,100);
NSDictionary *dict = @{@"Username":_userTxt.text,@"Lastname":_lastTxt.text,@"Firstname":_firstTxt.text,@"Mobilenumber":_mobTxt.text,@"dob":_dobTxt.text,@"image":imagedata};
[array2 addObject:dict];
[[NSUserDefaults standardUserDefaults]setObject:array2
forKey:@"userlist"];
NSLog(@"%@",array2);
[self performSegueWithIdentifier:@"second" sender:self];
}
(IBAction)chooseImg:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController
alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
second View { NSMutableArray *arr; }
- (void)viewDidLoad {
[super viewDidLoad];
arr =[[NSMutableArray alloc]init];
arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; }
#pragma mark- TableView DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1; }
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return arr.count; }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = @"tablecell";
TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
cell.userLbl.text =[[arr valueForKey:@"username"] objectAtIndex:indexPath.row];
cell.ageLbl.text =[[arr valueForKey:@"dob"] objectAtIndex:indexPath.row];
cell.profileImg.image =[UIImage imageNamed:[[arr valueForKey:@"image"] objectAtIndex:indexPath.row]];
return cell; }
I had a such problem too because i was using IMG tag and UL tag.
Try to apply the 'corners' plugin to elements such as $('#mydiv').corner()
, $('#myspan').corner()
, $('#myp').corner()
but NOT for $('#img').corner()
!
This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.
I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.
Good luck!
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
I had a similar issue where the SelectedItem never got updated.
My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.
public override bool Equals(object obj)
{
return this.Id == (obj as MyCustomObject).Id;
}
Create a Name.bat file that has the following line in it.
taskkill /F /IM wscript.exe /T
Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.
return new String(Hex.encode(digest));
Running on Centos7 & Docker 1.8.2, I was unable to use Zgr3doo's solution to umount by devicemapper ( I think the response I got was that the volume wasn't mounted/found. )
I think I also had a similar thing happen with sk8terboi87 ? 's answer: I believe the message was that the volumes couldn't be unmounted, and it listed the specific volumes that it tried to umount in order to delete the dead containers.
What did work for me was stopping docker first, and then deleting the directories manually. I was able to determine which ones they were by the error output of previous command to delete all the dead containers.
Apologies for the vague descriptions above. I found this SO question days after I handled the dead containers. .. However, I noticed a similar pattern today:
$ sudo docker stop fervent_fermi; sudo docker rm fervent_fermi fervent_fermi
Error response from daemon: Cannot destroy container fervent_fermi: Driver devicemapper failed to remove root filesystem a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35: Device is Busy
Error: failed to remove containers: [fervent_fermi]
$ sudo systemctl docker stop
$ sudo rm -rf /var/lib/docker/devicemapper/mnt/a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35
$
I did notice, when using this approach that docker re-created the images with different names:
a11bae452da3 trend_av_docker "bash" 2 weeks ago Dead compassionate_ardinghelli
This may have been due to the container being issued with restart=always, however, the container ID matches the ID of the container that previously used the volume that I force-deleted. There were no difficulties deleting this new container:
$ sudo docker rm -v compassionate_ardinghelli
compassionate_ardinghelli
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a)
to do as the comment posted.
I'm sorry to disagree, but according to the rules for parsing a legacy color value posted by @Yuhong Bao, chucknorris
DOES NOT equate to #CC0000
, but rather to #C00000
, a very similar but slightly different hue of red. I used the Firefox ColorZilla add-on to verify this.
The rules state:
chucknorris0
chuc knor ris0
ch kn ri
C0 00 00
I was able to use these rules to correctly interpret the following strings:
LuckyCharms
Luck
LuckBeALady
LuckBeALadyTonight
GangnamStyle
UPDATE: The original answerers who said the color was #CC0000
have since edited their answers to include the correction.
We can check by Four ways
The first way is
BOOL flagWayOne = TRUE;
NSLog(@"The flagWayOne result is - %@",flagWayOne ? @"TRUE":@"FALSE");
The second way is
BOOL flagWayTwo = YES;
NSLog(@"The flagWayTwo result is - %@",flagWayTwo ? @"YES":@"NO");
The third way is
BOOL flagWayThree = 1;
NSLog(@"The flagWayThree result is - %d",flagWayThree ? 1:0);
The fourth way is
BOOL flagWayFour = FALSE; // You can set YES or NO here.Because TRUE = YES,FALSE = NO and also 1 is equal to YES,TRUE and 0 is equal to FALSE,NO whatever you want set here.
NSLog(@"The flagWayFour result is - %s",flagWayFour ? YES:NO);
I've sorted this out using the cb.createQuery() (without the result type parameter):
public class Blah() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery query = criteriaBuilder.createQuery();
Root<Entity> root;
Predicate whereClause;
EntityManager entityManager;
Class<Entity> domainClass;
... Methods to create where clause ...
public Blah(EntityManager entityManager, Class<Entity> domainClass) {
this.entityManager = entityManager;
this.domainClass = domainClass;
criteriaBuilder = entityManager.getCriteriaBuilder();
query = criteriaBuilder.createQuery();
whereClause = criteriaBuilder.equal(criteriaBuilder.literal(1), 1);
root = query.from(domainClass);
}
public CriteriaQuery<Entity> getQuery() {
query.select(root);
query.where(whereClause);
return query;
}
public CriteriaQuery<Long> getQueryForCount() {
query.select(criteriaBuilder.count(root));
query.where(whereClause);
return query;
}
public List<Entity> list() {
TypedQuery<Entity> q = this.entityManager.createQuery(this.getQuery());
return q.getResultList();
}
public Long count() {
TypedQuery<Long> q = this.entityManager.createQuery(this.getQueryForCount());
return q.getSingleResult();
}
}
Hope it helps :)
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
There are several methods of showing a progress bar (circle) while loading an activity
. In your case, one with a ListView
in it.
IN ACTIONBAR
If you are using an ActionBar
, you can call the ProgressBar
like this (this could go in your onCreate()
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
And after you are done displaying the list, to hide it.
setProgressBarIndeterminateVisibility(false);
IN THE LAYOUT (The XML)
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="@+id/pbHeaderProgress"
style="@style/Spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:cacheColorHint="@android:color/transparent"
android:divider="#00000000"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:persistentDrawingCache="scrolling"
android:smoothScrollbar="false" >
</ListView>
</LinearLayout>
And in your activity (Java)
I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute()
I use something like this:
// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
@Override
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
and in the onPostExecute()
, after setting the adapter to the ListView
:
@Override
protected void onPostExecute(Void result) {
// SET THE ADAPTER TO THE LISTVIEW
lv.setAdapter(adapter);
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
EDIT: This is how it looks in my app while loading one of several ListViews
This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:
from django.test import Client
from django.core.urlresolvers import reverse
#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4))
If you want to use SimpleDateFormat
, you could write:
private final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
{ sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }
private long parseTimeToMillis(final String time) throws ParseException
{ return sdf.parse("1970-01-01 " + time).getTime(); }
But a custom method would be much more efficient. SimpleDateFormat
, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)
Also, SimpleDateFormat
is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)
Personally, I'd probably write a custom method.
I posted my solution here.
This is a way to delete an array element without copying to another array - just in frame of the same array instance:
public static void RemoveAt<T>(ref T[] arr, int index)
{
for (int a = index; a < arr.Length - 1; a++)
{
// moving elements downwards, to fill the gap at [index]
arr[a] = arr[a + 1];
}
// finally, let's decrement Array's size by one
Array.Resize(ref arr, arr.Length - 1);
}
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
It seems Yahoo server does some heuristic based on User-Agent
in a case Accept
header is set to */*
.
Accept: text/html
did the trick for me.
e.g.
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
Note: if you don't declare Accept
header then wget
automatically adds Accept:*/*
which means give me anything you have.
Do it the vi way.
To delete 5 lines press: 5dd
( 5 delete )
To select ( actually copy them to the clipboard ) you type: 10yy
It is a bit hard to grasp, but very handy to learn when using those remote terminals
Be aware of the learning curves for some editors:
(source: calver at unix.rulez.org)
You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.
Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.
Quoting from the gcc website:
C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
So probably you use a version of g++ which doesn't support -std=c++11
. Try -std=c++0x
instead.
Availability of C++11 features is for versions >= 4.3 only.
The low-level answer here is that a Web Reference will create a client proxy class that allows your code to talk to a Web Service that is described via WSDL and communicates via SOAP or HTTP GET (other posters indicate that it is only ASMX, but Web References can also talk to Java-based Web Services or Python-based or Ruby so long as they all talk WSDL and conform to the WS-I interoperability standard).
A Service Reference will create a client proxy class that communicates with a WCF-based service : regardless of whether that WCF service is a Web Service or not.
To add to Mike Flynn's answer, since upgrading to Xcode 7 and running my app on an iOS 9 device, I added this to my (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Hide any window that isn't the main window
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow *window in windows) {
if (window != self.window) {
window.hidden = YES;
}
}
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
Easier is subjective, but maybe the switch statement would be easier? You don't have to repeat the variable, so more values can fit on the line, and a line with many comparisons is more legible than the counterpart using the if statement.
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
One suggestion is to use LINQ to Entity Framework only for single-record CRUD statements.
For more involved queries, searches, reporting, etc, write a stored procedure and add it to the Entity Framework model as described on MSDN.
This is the approach I've taken with a couple of my sites and it seems to be a good compromise between productivity and performance. Entity Framework will not always generate the most efficient SQL for the task at hand. And rather than spending the time to figure out why, writing a stored procedure for the more complex queries actually saves time for me. Once you're familiar with the process, it's not too much of a hassle to add stored procs to your EF model. And of course the benefit of adding it to your model is that you get all that strongly typed goodness that comes from using an ORM.
If you want to remove the outline when focused as well try:
input[type="text"],
input[type="text"]:focus
{
background: transparent;
border: none;
outline-width: 0;
}
For opening a URL in the browser through the terminal, CentOS 7 users can use gio open command. For example, if you want to open google.com then gio open https://www.google.com
will open google.com URL in the browser.
xdg-open https://www.google.com
will also work but this tool has been deprecated, Use gio open
instead. I prefer this as this is the easiest way to open a URL using a command from the terminal.
As soon as you provide the directory where Tomcat needs to be installed and click ok you can notice download and installation starts in the progress tab of Eclipse.
Let the process complete.The error will automatically disappear.
Note: It is not mandatory to name your folder CATALINA_HOME
. I have tested this with windows. Cannot assert the same for Linux but IMO same rule should apply.
if(session_status()!=PHP_SESSION_ACTIVE) session_start()
open looks in the current working directory, which in your case is ~
, since you are calling your script from the ~
directory.
You can fix the problem by either
cd
ing to the directory containing data.csv
before executing the script, or
by using the full path to data.csv
in your script, or
open
and os.listdir
) may be affected by this.In zsh you can use
=time ...
In bash or zsh you can use
command time ...
These (by different mechanisms) force an external command to be used.
Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.
For what it's worth, with iOS7 dropping support for datetime
you need to use datetime-local
which doesn't accept timezone portion (which makes sense).
Doesn't work (iOS anyway):
<input type="datetime-local" value="2000-01-01T00:00:00+05:00" />
Works:
<input type="datetime-local" value="2000-01-01T00:00:00" />
PHP for value (windows safe):
strftime('%Y-%m-%dT%H:%M:%S', strtotime($my_datetime_input))
Here is a sample XAML
that will allow TextBox
to accept multiline text and it uses its own scrollbars:
<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>
Is something like this what you want to do?
$return_arr = array();
$fetch = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
It returns a json string in this format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
OR something like this:
$year = date('Y');
$month = date('m');
$json_array = array(
//Each array below must be pulled from database
//1st record
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
//2nd record
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
);
echo json_encode($json_array);
In your concrete example the problem is that you don't use this construct correctly:
@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })
@JsonSubTypes.Type
should contain the actual non-abstract subtypes of your abstract class.
Therefore if you have:
abstract class Parent
and the concrete subclasses
Ch1 extends Parent
and
Ch2 extends Parent
Then your annotation should look like:
@JsonSubTypes({
@JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
@JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})
Here name
should match the value of your 'discriminator':
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT,
property = "type")
in the property
field, here it is equal to type
. So type
will be the key and the value you set in name
will be the value.
Therefore, when the json string comes if it has this form:
{
"type": "ch1",
"other":"fields"
}
Jackson will automatically convert this to a Ch1
class.
If you send this:
{
"type": "ch2",
"other":"fields"
}
You would get a Ch2
instance.
Try VAVR Tuples.
Not only does vavr have a good set of tuple types, it has great support for functional programming, too.
Make sure to not require a package before making sure the vendor folder exists.
Check if you have done composer install
before. You may be just cloned the repository to your machine. So, you have to install the old packages before requiring a new one. Or you may want to include this option --profile
to your composer command to see the timing and memory usage information.
If you want to use pdf.js, I suggest you to read THIS
You can also upload your pdf somewhere (like Google Drive) and use its URL in a iframe
or
<object data="data/test.pdf" type="application/pdf" width="300" height="200">
<a href="data/test.pdf">test.pdf</a>
</object>
What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column -- which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I'm guessing "shares".
This scope https://www.googleapis.com/auth/userinfo.profile has been deprecated now. Please look at https://developers.google.com/+/api/auth-migration#timetable.
New scope you will be using to get profile info is: profile or https://www.googleapis.com/auth/plus.login
and the endpoint is - https://www.googleapis.com/plus/v1/people/{userId} - userId can be just 'me' for currently logged in user.
As blocking on keyboard input (since the input()
function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.
This works by creating one thread to run in the background, continually calling input()
and then passing any data it receives to a queue.
In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
input_str = input()
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit"
inputQueue = queue.Queue()
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
while (True):
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
time.sleep(0.01)
print("End.")
if (__name__ == '__main__'):
main()
"""
read_keyboard_input.py
Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018
References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html
To install PySerial: `sudo python3 -m pip install pyserial`
To run this program: `python3 this_filename.py`
"""
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
# Receive keyboard input from user.
input_str = input()
# Enqueue this input string.
# Note: Lock not required here since we are only calling a single Queue method, not a sequence of them
# which would otherwise need to be treated as one atomic operation.
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit" # Command to exit this program
# The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
# method calls in a row. Use this if you have such a need, as follows:
# 1. Pass queueLock as an input parameter to whichever function requires it.
# 2. Call queueLock.acquire() to obtain the lock.
# 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
# inputQueue.qsize(), followed by inputQueue.put(), for example.
# 4. Call queueLock.release() to release the lock.
# queueLock = threading.Lock()
#Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
inputQueue = queue.Queue()
# Create & start a thread to read keyboard inputs.
# Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
# this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
# Main loop
while (True):
# Read keyboard inputs
# Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
# multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
# example program, no locks are required.
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break # exit the while loop
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
# Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
time.sleep(0.01)
print("End.")
# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'):
main()
$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.
Note that Queue.put()
and Queue.get()
and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):
The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.
this should work also with different predicate
myFunction(strings.find( _ == mystring ).isDefined)
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula
Here's the same as the current top answer, but in an ES6 one-liner:
myArray.sort((a, b) => a.distance - b.distance);
I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.
Of course this was Java, I've translated it to Python:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")
browser = webdriver.Firefox(firefox_profile=fp)
In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf
Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.
You upgraded to PHP 7, and now mysql_connect
is deprecated. Check yours with:
php -version
Change it to mysqli_connect
as in:
$host = "127.0.0.1";
$username = "root";
$pass = "foobar";
$con = mysqli_connect($host, $username, $pass, "your_database");
If you're upgrading legacy PHP, now you're faced with the task of upgrading all your mysql_*
functions with mysqli_*
functions.
Failed to find: com.android.support:appcompat-v7:22.0.0
The "I literally tried everything else" answer:
This problem will also occur if you don't have an upto date Android Support Library and Android Support Repository. Just install using the SDK manager.
1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?
It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.
2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?
That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.
So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.
A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.
3) Would you ever want to call a destructor manually?
Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)
// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
Foo *myfoo = new Foo("foo");
}
// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
Foo *myfoo = new Foo("foo");
delete myfoo;
}
// no memory leak, object goes out of scope
if(1) {
Foo myfoo("foo");
}
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...
Q: How do I execute this in Terminal?
Confusions and Conflicts:
sudo
to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Great post here.(A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your ~/bin folder. You can get there by typing cd ~/bin
or cd $HOME/bin
from the terminal prompt. You will have full permissions in that folder.)
To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:
Tell the system the location of the script. (pick one)
/path/to/script.sh
). You can verify the full path by typing pwd
or echo $PWD
in the terminal../
for the path (e.g. ./script.sh
). Easy.PATH
and just type the name (e.g. script.sh
). You can verify the system PATH
by typing echo $PATH
or echo -e ${PATH//:/\\n}
if you want a neater list.Tell the system that the script has permission to execute. (pick one)
chmod +x /path/to/script.sh
in the terminal.chmod 755 /path/to/script.sh
if you prefer numbers. There is a great discussion with a cool chart here.Tell the system the type of script. (pick one)
BASH /path/to/script.sh
or PHP /path/to/script.php
) If the script has an extension, such as .php or .py, it is part of the script name and you must include it.#!/bin/bash
) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions. PATH
by using #!/usr/bin/env
followed by the program name (e.g. #!/usr/bin/env bash
or #!/usr/bin/env python3
). There are pros and cons as thoroughly discussed here.For kotlin user's
fun Activity.displayMetrics(): DisplayMetrics {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics
}
And in Activity you could use it like
resources.displayMetrics.let { displayMetrics ->
val height = displayMetrics.heightPixels
val width = displayMetrics.widthPixels
}
Or in fragment
activity?.displayMetrics()?.run {
val height = heightPixels
val width = widthPixels
}
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
I had not agreed to the new updated licensed agreement from apple.
Briefly : Please log in to your developer's account -> profile's -> review -> read the agreement or get your lawyer read it for you -> agree (at your own will) -> and again click profile's to check the status of your profile.
In my scenario the valid code signing entity was not showing up. When i followed the above procedure it was visible and i was able to run the app on the device and/or create the iPA file without much difficulty.
There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.
Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.
Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.
This is actually one of the cases where I advise to read what Knuth has to say in The Art of Computer Programming, vol. 3. Another good read is Julienne Walker's The Art of Hashing.
A very elegant way is to use ng-controller to run a single controller outside of the ng-view:
<div class="collapse navbar-collapse" ng-controller="HeaderController">
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
<li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
<li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
</ul>
</div>
<div ng-view></div>
and include in controllers.js:
function HeaderController($scope, $location)
{
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}
The & and | are usually bitwise operations.
Where as && and || are usually logical operations.
For comparison purposes, it's perfectly fine provided that everything returns either a 1 or a 0. Otherwise, it can return false positives. You should avoid this though to prevent hard to read bugs.
There is now the built in ability to detect empty string with .isEmpty
:
if emptyString.isEmpty {
print("Nothing to see here")
}
Apple Pre-release documentation: "Strings and Characters".
Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.
remote: error: GH003: Sorry, force-pushing to master is not allowed.
If you get an error message like this one please try the following steps.
To effectively reset your fork you need to follow these steps :
git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin
Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :
git checkout master
git push --force origin
Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :
git push origin --delete tmp_master
git branch -D tmp_master
Other answers warning about lossing your change still apply, be carreful.
In SSMS, set the database to read-only then back. The connections will be closed, which frees up the locks.
In my case there was a website that had open connections to the database. This method was easy enough:
Database Read-Only
to TrueYou can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date
object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:
start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)
ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
As discussed previously, without doing something like this, records are ignored on the last day.
Edited to avoid the use of datetime.combine
-- seems more logical to stick with date instances when comparing against a DateTimeField
, instead of messing about with throwaway (and confusing) datetime
objects. See further explanation in comments below.
/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'
This will list down the exact ip address for the machine
You probably want to assign the lastname
you are reading out here
lastname = sheet.cell(row=r, column=3).value
to something; currently the program just forgets it
you could do that two lines after, like so
unpaidMembers[name] = lastname, email
your program will still crash at the same place, because .items()
still won't give you 3-tuples but rather something that has this structure: (name, (lastname, email))
good news is, python can handle this
for name, (lastname, email) in unpaidMembers.items():
etc.
If you are using 'request.js' you might use the following:
var options = {
url: 'localhost',
method: 'GET',
headers:{
Accept: '*/*'
}
}
request(options, function (error, response, body) {
...
})
I had a similar problem where the following queries wouldn't work;
update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = (select LGA.LGA_NAME from tbl_Prop_LGA as LGA where LGA.LGA_CODE = LVD.LGCode)
where LVD.LGAName is null;
update tbl_LOT_VALUATION_DETAILS inner join tbl_prop_LGA on tbl_LOT_VALUATION_DETAILS.LGCode = tbl_prop_LGA.LGA_CODE
set tbl_LOT_VALUATION_DETAILS.LGAName = [tbl_Prop_LGA].[LGA_NAME]
where tbl_LOT_VALUATION_DETAILS.LGAName is null;
However using DLookup resolved the problem;
update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = dlookup("LGA_NAME", "tbl_Prop_LGA", "LGA_CODE="+LVD.LGCode)
where LVD.LGAName is null;
This solution was originally proposed at https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query
To count everything just pipe ls to word count line:
ls | wc -l
To count with pattern, pipe to grep first:
ls | grep log | wc -l
I would think this: http://jsfiddle.net/Skooljester/S3y5p/1/ should do it. If I don't have the class names 100% correct you can just change them to whatever you need them to be.
Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.
at.net 3.5 use:
String.Join("", new List<int>(array).ConvertAll(i => i.ToString()).ToArray());
at.net 4.0 or above use: (see @Jan Remunda's answer)
string result = string.Join("", array);
The default install location is /usr/local, so add this to your ~/.bash_profile file:
export PATH=$PATH:/usr/local/git/bin/
Then run source ~/.bash_profile
in Terminal.
Use sqlite3 database.sqlite3 < db.sql
. You'll need to make sure that your files contain valid SQL for SQLite.
On the one hand, when you call System.getProperty("java.io.tmpdir")
instruction, Java calls the Win32 API's function GetTempPath
.
According to the MSDN :
The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:
- The path specified by the TMP environment variable.
- The path specified by the TEMP environment variable.
- The path specified by the USERPROFILE environment variable.
- The Windows directory.
On the other hand, please check the historical reasons on why TMP
and TEMP
coexist. It's really worth reading.
DateAndTime Reformat:
SELECT *, to_char( last_update, 'DD-MON-YYYY') as re_format from actor;
DEMO:
In the constructor of Startup class, you can access appsettings.json and many other settings using the injected IConfiguration object:
Startup.cs Constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//here you go
var myvalue = Configuration["Grandfather:Father:Child"];
}
public IConfiguration Configuration { get; }
Contents of appsettings.json
{
"Grandfather": {
"Father": {
"Child": "myvalue"
}
}
If every char in the file is properly encoded in UTF-8, you won't have any problem reading it using a reader with the UTF-8 encoding. Up to you to check every char of the file and see if you consider it printable or not.
I have resolved import error by Ctrl + Shift + P. Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present. This should import all modules that you have installed using PIP for autocomplete.
I know, this is an old question, but couldn't find the solution here. After some tries, I found out, that some added "<asp:UpdatePanel" had been the reason.
After (re)moving them, all works fine like before.
Modify the background image of the <td> itself.
Or apply some css to the div:
.thatSetsABackgroundWithAnIcon{
height:100%;
}
You could read the entire input line from scanner, then split the line by ,
then you have a String[]
, parse each number into int[]
with index one to one matching...(assuming valid input and no NumberFormatExceptions
) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[]
will be represented by a 0
, these need to be removed in order to differentiate between a valid input value of 0
.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:
There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction
Row-By-Row Processing Without Cursor
That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.
But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....
Try this
import os
import subprocess
DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')
subprocess.call(['python', DIR])
Redirect the output to a file like this:
./a.sh > somefile 2>&1 &
This will redirect both stdout and stderr to the same file. If you want to redirect stdout and stderr to two different files use this:
./a.sh > stdoutfile 2> stderrfile &
You can use /dev/null
as one or both of the files if you don't care about the stdout and/or stderr.
See bash manpage for details about redirections.
Below are the commands for Ubuntu user to authorise devices once developer option is ON.
sudo ~/Android/Sdk/platform-tools/adb kill-server
sudo ~/Android/Sdk/platform-tools/adb start-server
On Device:
Connect your device now and you must only accept request, on your phone.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
you should use []
var x = ConfigurationManager.AppSettings["APIKey"];
USE join to get 0 count in the result using GROUP BY.
simply 'join' does Inner join in MS SQL so , Go for left or right join.
If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.
EG:
select WARDNO,count(WARDCODE) from MAIPADH
right join MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO
.
select WARDNO,count(WARDCODE) from MSWARDH
left join MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO
Take group by from the table which has Primary key and count from the another table which has actual entries/details.
This is useful when you have your own origin
which is not upstream
. In other words, you might have your own origin
repo that you do development and local changes in and then occasionally merge upstream
changes. The difference between your example and the highlighted text is that your example assumes you're working with a clone of the upstream repo directly. The highlighted text assumes you're working on a clone of your own repo that was, presumably, originally a clone of upstream.
From all I know, BCP only exports the data - I don't think there's any way to make it export the header row with column names, too.
One common technique seen to solve this is to use a view over your actual data for export, which basically does a UNION ALL over two statements:
and then use bcp on that view, instead of your underlying data table directly.
Marc
Try width: max-content
to adjust the width of the div by it's content.
<!DOCTYPE html>
<html>
<head>
<style>
div.ex1 {
width:500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
width: max-content;
margin: auto;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<div class="ex1">This div element has width 500px;</div>
<br>
<div class="ex2">Width by content size</div>
</body>
</html>
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];
-(void)saveAction:(UIBarButtonItem *)sender{
//perform your action
}
If you just want to print the substrings ...
char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
printf("%.4s\n", s + i);
}
If the position of the element containing the Lorum Ipsum is set absolute, you can specify the position via CSS. The "here" and "and here" elements would need to be contained in a block level element. I'll use markup like this.
print("<div id="lipsum">");
print("<div id="here">");
print(" here");
print("</div>");
print("<div id="andhere">");
print("and here");
print("</div>");
print("blah");
print("</div>");
Here's the CSS for above.
#lipsum {position:absolute;top:0;left:0;} /* example */ #here {position:absolute;top:0;right:0;} #andhere {position:absolute;bottom:0;right:0;}
Again, the above only works (reliably) if #lipsum is positioned via absolute.
If not, you'll need to use the float property.
#here, #andhere {float:right;}
You'll also need to put your markup in the appropriate place. For better presentation, your two divs will probably need some padding and margins so that the text doesn't all run together.
If the strings are not even of equal length, you can use this
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Then add this code to your View:
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
I'm afraid there is no such a member for std::string, but you can easily program that kind of functions. It may not be the fastest solution but this would suffice:
std::string RemoveChars(const std::string& source, const std::string& chars) {
std::string result="";
for (unsigned int i=0; i<source.length(); i++) {
bool foundany=false;
for (unsigned int j=0; j<chars.length() && !foundany; j++) {
foundany=(source[i]==chars[j]);
}
if (!foundany) {
result+=source[i];
}
}
return result;
}
EDIT: Reading the answer below, I understood it to be more general, not only to detect digit. The above solution will omit every character passed in the second argument string. For example:
std::string result=RemoveChars("(999)99-8765-43.87", "()-");
Will result in
99999876543.87
I couldn't get it to work using Calendar. You have to use DateFormat
//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());
//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());
//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());
private String convertToString(java.sql.Clob data)
{
final StringBuilder builder= new StringBuilder();
try
{
final Reader reader = data.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
builder.append((char)b);
}
br.close();
}
catch (SQLException e)
{
log.error("Within SQLException, Could not convert CLOB to string",e);
return e.toString();
}
catch (IOException e)
{
log.error("Within IOException, Could not convert CLOB to string",e);
return e.toString();
}
//enter code here
return builder.toString();
}
Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).
Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.
Using Larry Wall's filename fixer:
$op = shift or die $help;
chomp(@ARGV = <STDIN>) unless @ARGV;
for (@ARGV) {
$was = $_;
eval $op;
die $@ if $@;
rename($was,$_) unless $was eq $_;
}
It's as simple as
find | fix 'tr/A-Z/a-z/'
(where fix
is of course the script above)
I have change it little bit but still can not do few things.
I added that clicking on it close it - it was easy but very functional.
<div class="modal-dialog" data-dismiss="modal">
I also need different description under each photo. I added description in footer just to show what I need. It need to change with every photo.
HTML
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" data-dismiss="modal">
<div class="modal-content" >
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<img src="" class="imagepreview" style="width: 100%;" >
</div>
<div class="modal-footer">
<div class="col-xs-12">
<p class="text-left">1. line of description<br>2. line of description <br>3. line of description</p>
</div>
</div>
</div>
</div>
JavaScript:
$(function() {
$('.pop').on('click', function() {
$('.imagepreview').attr('src', $(this).find('img').attr('src'));
$('#imagemodal').modal('show');
});
});
Also it would be nice if this window will open only on 100% of screen. Here picture inside with description have more than 100% and in become scrollable... and if screen in much bigger than pictures it shoud stop only on orginal size. for ex. 900 px and no bigger in height.
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
I think what you're looking for is !!val==false
which can be turned to !val
(even shorter):
You see:
function checkValue(value) {
console.log(!!value);
}
checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false
checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true
That works by flipping the value by using the !
operator.
If you flip null
once for example like so :
console.log(!null) // that would output --> true
If you flip it twice like so :
console.log(!!null) // that would output --> false
Same with undefined
or false
.
Your code:
if(val==null || val===false){
;
}
would then become:
if(!val) {
;
}
That would work for all cases even when there's a string but it's length is zero.
Now if you want it to also work for the number 0 (which would become false
if it was double flipped) then your if would become:
if(!val && val !== 0) {
// code runs only when val == null, undefined, false, or empty string ""
}
If you read the help for vector
(or numeric
or logical
or character
or integer
or double
, 'raw' or complex
etc ) then you will see that they all have a length
(or length.out
argument which defaults to 0
Therefore
numeric()
logical()
character()
integer()
double()
raw()
complex()
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')
All return 0 length vectors of the appropriate atomic modes.
# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')
Like this:
var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)
root.setAttribute( 'class', 'myCssClass' );
Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)
root.className += ' myCssClass';
Or, depending on the required browser support, you can use the classList.add()
method:
root.classList.add('myCssClass');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist
UPDATE:
A more elegant solution for referencing the HTML
element might be this:
var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
// root.classList.add('myCssClass');
//
Check your file name in which you have saved your program. If the file name is wordlists
then you will get an error. Your filename should not be same as any of methods{functions} that you use in your program.
You can build a nice tree of dicts of dicts like this:
import collections
def Tree():
return collections.defaultdict(Tree)
It might not be exactly what you want but it's quite useful! Values are saved only in the leaf nodes. Here is an example of how it works:
>>> t = Tree()
>>> t
defaultdict(<function tree at 0x2142f50>, {})
>>> t[1] = "value"
>>> t[2][2] = "another value"
>>> t
defaultdict(<function tree at 0x2142f50>, {1: 'value', 2: defaultdict(<function tree at 0x2142f50>, {2: 'another value'})})
For more information take a look at the gist.
Actually in case if you have any file that has key value pairs like this:
someKey=someValue
someOtherKey=someOtherValue
You can import that into webpack by a npm module called properties-reader
I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.
"properties-reader": "0.0.16"
const PropertiesReader = require('properties-reader');
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
externals: {
'Config': JSON.stringify(appProperties)
}
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
The xor operator is ^
For example: SELECT A ^ B
where A and B are integer category data types.
To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:
AllowSameSiteAttribute.cs
public class AllowSameSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
if(response != null)
{
response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
//Add more headers...
}
base.OnActionExecuting(filterContext);
}
}
HomeController.cs
[AllowSameSite] //For the whole controller
public class UserController : Controller
{
}
or
public class UserController : Controller
{
[AllowSameSite] //For the method
public ActionResult Index()
{
return View();
}
}
There are in fact 3 questions in your question :
What JB King has described is correct, but it is a particular, simple version, where in fact he mapped front, middle and bacn to an MVC layer. He mapped M to the back, V to the front, and C to the middle.
For many people, it is just fine, since they come from the ugly world where even MVC was not applied, and you could have direct DB calls in a view.
However in real, complex web applications, you indeed have two or three different layers, called front, middle and back. Each of them may have an associated database and a controller.
The front-end will be visible by the end-user. It should not be confused with the front-office, which is the UI for parameters and administration of the front. The front-end will usually be some kind of CMS or e-commerce Platform (Magento, etc.)
The middle-end is not compulsory and is where the business logics is. It will be based on a PIM, a MDM tool, or some kind of custom database where you enrich your produts or your articles (for CMS). It'll also be the place where you code business functions that need to be shared between differents frontends (for instance between the PC frontend and the API-based mobile application). Sometimes, an ESB or tool like ActiveMQ will be your middle-end
The back-end will be a 3rd layer, surrouding your source database or your ERP. It may be jsut the API wrting to and reading from your ERP. It may be your supplier DB, if you are doing e-commerce. In fact, it really depends on web projects, but it is always a central repository. It'll be accessed either through a DB call, through an API, or an Hibernate layer, or a full-featured back-end application
This description means that answering the other 2 questions is not possible in this thread, as bottlenecks really depend on what your 3 ends contain : what JB King wrote remains true for simple MVC architectures
at the time the question was asked (5 years ago), maybe the MVC pattern was not yet so widely adopted. Now, there is absolutely no reason why the MVC pattern would not be followed and a view would be tied to DB calls. If you read the question "Are there cases where they MUST overlap, and frontend/backend cannot be separated?" in a broader sense, with 3 different components, then there times when the 3 layers architecture is useless of course. Think of a simple personal blog, you'll not need to pull external data or poll RabbitMQ queues.
So, after spending so many days over this, this is what I came up with which worked for me, and is good practice as well,
code
@Override
public void onTicketSelect(int position) {
for (ListType listName : list) {
listName.setmSelectedConstant(0);
}
8. Outside this, make the selected position constant 1:
code
list.get(position).setmSelectedConstant(1);
adapter.notifyDataSetChanged();
immediately after this.code
if (listVarInAdapter.get(position).getmSelectedConstant() == 1) {
holder.checkIcon.setChecked(true);
selectedTicketType = dataSetList.get(position);}
else {
commonHolder.checkCircularIcon.setChecked(false);
}
In general, synchronized
methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized
instance method; when the resource belongs to all instances (i.e. when it is in a static
variable) then you use a synchronized static
method to access it.
For example, you could make a static
factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static
collection. If your factory is used from multiple threads, you need to make the factory method synchronized
(or have a synchronized
block inside the method) to protect access to the shared static
collection.
Note that using synchronized
without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.
date under Mac OSX is slightly different.
For yesterday
date -v-1d +%F
For Last week
date -v-1w +%F
@nithin,
AWS released layers
concept inside Lambda
functions. You can create your layer and there you can upload as much as libraries and then you can connect the layer with the lambda functions.
For more details: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html
This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video controls >
<source src="sample.mp4" type="video/mp4">
<track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>
the video and subtitle files are stored in the same folder as default.htm
I have the very latest version of Chrome (just updated this morning)
When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!
(note that if I input localhost.. to IE11 the video plays!!!!
In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.
This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4
This is an extremely old question, but here are the approaches I personally use ...
As many have already stated, this works for most situations.
var url = window.location.origin;
However, this simple approach can be used to strip off any port numbers.
var url = "http://" + location.host.split(":")[0];
Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...
var url = window.location.protocol + "//" + location.host.split(":")[0];
As a bonus -- the base URL can then be redefined globally.
document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";
As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:
<?php echo strtotime('+1 day'); ?>
Above code will add 1 day or 24 hours to your current timestamp.
in place of +1 day
you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.
examples from the manual are as below:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
And about timing:
fn1 <- function (N) {
for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
i=1
while (i <= N) {
y <- i*i
i <- i + 1
}
}
system.time(fn1(60000))
# user system elapsed
# 0.06 0.00 0.07
system.time(fn2(60000))
# user system elapsed
# 0.12 0.00 0.13
And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.
Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:
Template File
<html>
<head>
<title>{insert script variable for title}</title>
</head>
<body>
<div class="menu">
{menu items inserted here by server-side scripting}
</div>
<div class="main-content">
{main content inserted here by server-side scripting}
</div>
</body>
</html>
If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.
But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.
You could emulate your example like this:
Frames Example
<html>
<head>
<title>Frames Test</title>
<style>
.menu {
float:left;
width:20%;
height:80%;
}
.mainContent {
float:left;
width:75%;
height:80%;
}
</style>
</head>
<body>
<iframe class="menu" src="menu.html"></iframe>
<iframe class="mainContent" src="events.html"></iframe>
</body>
</html>
There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.
int [][] twoDim = new int [5][5];
int a = (twoDim.length);//5
int b = (twoDim[0].length);//5
for(int i = 0; i < a; i++){ // 1 2 3 4 5
for(int j = 0; j <b; j++) { // 1 2 3 4 5
int x = (i+1)*(j+1);
twoDim[i][j] = x;
if (x<10) {
System.out.print(" " + x + " ");
} else {
System.out.print(x + " ");
}
}//end of for J
System.out.println();
}//end of for i
Firstly — I don't think column1 is not NULL or column1 <> ''
makes very much sense. Maybe you meant to write column1 is not NULL and column1 <> ''
(AND
instead of OR
)?
Secondly — because of Hive's "schema on read" approach to table definitions, invalid values will be converted to NULL
when you read from them. So, for example, if table1.column1
is of type STRING
and table2.column1
is of type INT
, then I don't think that table1.column1 IS NOT NULL
is enough to guarantee that table2.column1 IS NOT NULL
. (I'm not sure about this, though.)
The easiest way is to use Math library.
Use Math.pow(a, b)
and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
Adding this to your WebSecurityConfiguration class should do the trick.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
You can use cat > filename
to use standart input to write to the file. At the end you have to put EOF CTRL+D
.
Observations:
#include <cstring>
should introduce std::strcpy().using namespace std;
(as written in medico.h) introduces any identifiers from std::
into the global namespace.Aside from using namespace std;
being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using
in a header file (see below!), using namespace
does not affect identifiers introduced after the statement.
(using namespace std
is written in the header, which is included in medico.cpp, but #include <cstring>
comes after that.)
My advice: Put the using namespace std;
(if you insist on using it at all) into medico.cpp, after any includes, and use explicit std::
in medico.h.
strcmpi()
is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.
(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)
warning: deprecated conversion from string constant to ‘char*’
A "string constant" is when you write a string literal (e.g. "Hello"
) in your code. Its type is const char[]
, i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *
, i.e. removing the const
qualifier, generates the warning you are seeing.
OT clarification: using
in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string
and a self-written ::string
just perfectly in my code, unless I include your medico.h, because then the two classes will clash.
Don't use using
in header files.
And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.
from netifaces import interfaces, ifaddresses, AF_INET
iplist = [ifaddresses(face)[AF_INET][0]["addr"] for face in interfaces() if AF_INET in ifaddresses(face)]
print(iplist)
['10.8.0.2', '192.168.1.10', '127.0.0.1']
The attribute align=middle
sets vertical alignment. To set horizontal alignment using HTML, you can wrap the element inside a center
element and remove all the CSS you have now.
<center><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></center>
_x000D_
If you would rather do it in CSS, there are several ways. A simple one is to set text-align
on a container:
<div style="text-align: center"><img src=_x000D_
"http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"></div>
_x000D_
Amazon EBS provides block level storage - It is used to create a filesystem on it and store files. Amazon EFS - its shared storage system similar like NAS/SAN. You need to mount it to unix server and use it. Amazon S3 - It is object based storage where each item is stored with a http URL.
One of the difference is - EBS can be attached to 1 instance at a time and EFS can be attached to multiple instances that why shared storage. S2 plain object storage cannot be mounted.
Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.
using (var context = new DataDb())
{
var ctx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext;
ctx.ExecuteStoreCommand("DELETE FROM [TableName] WHERE Name= {0}", Name);
}
or
using (var context = new DataDb())
{
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
}
I had the same doubt as you until I came across this book by the C++ Guru Scott Meyers. Refer the third Item in this book where he talks in details about using const
.
Just follow this advice
const
appears to the left of the asterisk, what's pointed to is constantconst
appears to the right of the asterisk, the pointer itself is constantconst
appears on both sides, both are constantgo 1.13
(exec from module root directory)
Update specified dependencies:
go get -u <package-name>
Update all direct and indirect dependencies to latest minor or patch upgrades (pre-releases are ignored):
go get -u ./...
# or
go get -u=patch ./...
Reference:
https://github.com/golang/go/wiki/Modules#daily-workflow
go help get
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110
and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.
I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
This works to me:
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES);
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName,
ri.activityInfo.name));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, element);
} catch (NameNotFoundException e) {
ToastHelper.MakeShortText("Whatsapp have not been installed.");
}
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
I would strongl suggest the use of the javascript escape() method
you can use this with jQuery by grabbing a form value like so:
var encodedString = escape($("#myFormFieldID").val());
You need to find the selected option:
$(this).find(':selected').data('id')
or
$(this).find(':selected').attr('data-id')
although the first method is preferred.
This flexbox principle also works horizontally
During calculations of flex bases and flexible lengths, auto margins
are treated as 0.
Prior to alignment via justify-content and
align-self, any positive free space is distributed to auto margins in
that dimension.
Setting an automatic left margin for the Last Item will do the work.
.last-item {
margin-left: auto;
}
Code Example:
.container {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
margin: 5px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p class="last-item"></p>_x000D_
</div>
_x000D_
This can be very useful for Desktop Footers.
As Envato did here with the company logo.
May be you need "dynamic" type?
public dynamic GetAnything()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return /*what boject you needed*/ ;`enter code here`
}
The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).
For example:
struct foo_t {
int x;
char c;
};
Even though the c
field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8
(on a 32-bit system - rather a system with a 32-bit int
type) because there will need to be 3 bytes of padding after the c
field.
Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.
change the input boxes like
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
and js code as
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for(var i=0;i<chboxs.length;i++) {
if(chboxs[i].checked){
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
here is a demo fiddle
I had the same Error, because of JUNIT version, I had 3 3.8.1 and I have changed to 4.8.1.
so the solution is
you have to go to POM, and make sure that you dependency looks like this
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
Make a custom interface extends the Window and add your custom property as optional.
Then, let the customWindow that use the custom interface, but valued with the original window.
It's worked with the [email protected].
interface ICustomWindow extends Window {
MyNamespace?: any
}
const customWindow:ICustomWindow = window;
customWindow.MyNamespace = customWindow.MyNamespace {}
You have the wrong table set on the command. You should use the following on your setup:
ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;
If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:
Api Controller:
public class ProductController : ApiController
{
[HttpPost]
public void Post(Newtonsoft.Json.Linq.JObject data)
{
System.Diagnostics.Debugger.Break();
Product product = data["product"].ToObject<Product>();
Product product2 = data["product2"].ToObject<Product>();
int someRandomNumber = data["randomNumber"].ToObject<int>();
string productName = product.ProductName;
string product2Name = product2.ProductName;
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
View:
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.AddProducts = function () {
var product = {
ProductID: 0,
ProductName: "Orange",
}
var product2 = {
ProductID: 1,
ProductName: "Mango",
}
var data = {
product: product,
product2: product2,
randomNumber:12345
};
$http.post("/api/Product", data).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>
Yours and VladLosevs' solutions are probably better than mine. If you want a brute-force solution, however, try this:
SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:\"msvcprtd.lib;MSVCRTD.lib\")
FOREACH(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
If you're using IntelliJ add your DB to Database view then right click on databases and select full text search, it will list all tables and all fields for your specific text.
#!/bin/sh
or #!/bin/bash
has to be first line of the script because if you don't use it on the first line then the system will treat all the commands in that script as different commands. If the first line is #!/bin/sh
then it will consider all commands as a one script and it will show the that this file is running in ps
command and not the commands inside the file.
./echo.sh
ps -ef |grep echo
trainee 3036 2717 0 16:24 pts/0 00:00:00 /bin/sh ./echo.sh
root 3042 2912 0 16:24 pts/1 00:00:00 grep --color=auto echo
import javax.swing.*;
class Demo extends JFrame
{
String str1;
Demo(String s1)
{
str1=s1;
JOptionPane.showMessageDialog(null,"your message : "+str1);
}
public static void main (String ar[])
{
new Demo("Java");
}
}
You could use Javascript's substring method. For example:
var list = ["bird1", "bird2", "pig1"]
for (var i = 0; i < list.length; i++) {
if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}
Which outputs:
bird1
bird2
Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.
So let's say your getting a pathname from a URL :
Let's say your at bird1?=letsfly - you could use this code to check the URL:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
for (var i = 0; i < list.length; i++) {
if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}
The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4)
with a regex, or even another javascript method like .contains()
Using the .contains()
method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:
var url = 'www.example.com/bird?=fly'
if (url.contains('bird')) {
// this is true
// do something
}
What about sed? That will work in a single command:
sed 's#.*/\([^:]*\).*#\1#' <<<$string
#
are being used for regex dividers instead of /
since the string has /
in it..*/
grabs the string up to the last backslash.\( .. \)
marks a capture group. This is \([^:]*\)
.
[^:]
says any character _except a colon, and the *
means zero or more..*
means the rest of the line.\1
means substitute what was found in the first (and only) capture group. This is the name.Here's the breakdown matching the string with the regular expression:
/var/cpanel/users/ joebloggs :DNS9=domain.com joebloggs
sed 's#.*/ \([^:]*\) .* #\1 #'
I have the same issue. It seems that pip is the problem. Try
pip uninstall xlsxwriter
easy_install xlsxwriter
Tensorflow 2.0 Compatible Answer: In Tensorflow Version >= 2.0, the command for Initializing all the Variables if we use Graph Mode, to fix the FailedPreconditionError
is shown below:
tf.compat.v1.global_variables_initializer
This is just a shortcut for variables_initializer(global_variables())
It returns an Op that initializes global variables in the graph.
CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index
values are likely to get screwed with.
If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.
So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased;
is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.
Most decompilers for Java are based on JAD. It's a great tool, but unfortunately hasn't been updated for a while and does not handle Java 1.5+ classes very well. I have not seen any tools that will properly handle 1.5+ classes.
Why the fuss?
replace(haystack, haystack %in% needles, replacements)
Demo:
haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")
replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"
You might be looking for Promise.race
(native I/O racing solution, not threads)
Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race
with setTimeout
(example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race
statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
I've discovered that you can use eval to avoid using a subshell. Thus:
IFS=$'\n' eval 'echo "${my_array[*]}"'
Probably, my experience with this bug will be needed for someone (including myself too... :) ).
So, I could to add one thing to the mentioned here answers. I mean playing with the trailing "/" symbol in the options, because playing with it does not work in my case. But when I have deleted the .eclipse/org.eclipse.oomph.p2/cache
and the .eclipse/org.eclipse.oomph.setup/cache
dirs (names are given relatively to the home dir) and then have done the well known procedure with "/", it started to work.
you can use the below command for reset of single file
git checkout HEAD -- path_to_file/file_name
List all changed files to get path_to_file/filename
with below command
git status
SQL%ROWCOUNT
can also be used without being assigned (at least from Oracle 11g).
As long as no operation (updates, deletes or inserts) has been performed within the current block, SQL%ROWCOUNT
is set to null. Then it stays with the number of line affected by the last DML operation:
say we have table CLIENT
create table client (
val_cli integer
,status varchar2(10)
)
/
We would test it this way:
begin
dbms_output.put_line('Value when entering the block:'||sql%rowcount);
insert into client
select 1, 'void' from dual
union all select 4, 'void' from dual
union all select 1, 'void' from dual
union all select 6, 'void' from dual
union all select 10, 'void' from dual;
dbms_output.put_line('Number of lines affected by previous DML operation:'||sql%rowcount);
for val in 1..10
loop
update client set status = 'updated' where val_cli = val;
if sql%rowcount = 0 then
dbms_output.put_line('no client with '||val||' val_cli.');
elsif sql%rowcount = 1 then
dbms_output.put_line(sql%rowcount||' client updated for '||val);
else -- >1
dbms_output.put_line(sql%rowcount||' clients updated for '||val);
end if;
end loop;
end;
Resulting in:
Value when entering the block:
Number of lines affected by previous DML operation:5
2 clients updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10
But fortunately, with the MySQL FOREIGN_KEY_CHECKS variable, you don't have to worry about the order of your DROP TABLE statements at all, and you can write them in any order you like -- even the exact opposite -- like this:
SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;
For more clarification, check out the link below:
http://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys/
If you think about the problem we're trying to solve, it's not an enum we need at all. We need an object that allows a certain number of values to be associated with eachother; in other words, to define a class.
Jakub Šturc's type-safe enum pattern is the best option I see here.
Look at it:
Alternative to DATEPART
SELECT LEFT(CONVERT(CHAR(20), GETDATE(), 101), 2)