So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\
. However, they were never registered in the GAC.
I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies
to C:\windows\assembly
and the application worked on that problem machine. You could also do this programmatically with Gacutil.
So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!
It is possible and is deceptively easy:
bin\Debug
folder below the project file (.csproj).app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
Here's what I found that worked for being able to get the deployed folder location of my clickonce application and that hasn't been mentioned anywhere I saw in my searches, for my similar, specific scenario:
Here is a visual of my use case:
I did not find any of the suggestions in this question or their comments to work in returning the folder that the clickonce application was deployed to (that I would then move relative to this folder to find the folder of interest). No other internet searching or related SO questions turned up an answer either.
All of the suggested properties either were failing due to the object (e.g. ActivationUri) being null, or were pointing to the local PC's cached installed app folder. Yes, I could gracefully handle null objects by a check for IsNetworkDeployed - that's not a problem - but surprisingly IsNetworkDeployed returns false even though I do in fact have a network deployed folder location for the clickonce application. This is because the application is running from the local, cached bits.
The solution is to look at:
AppDomain.CurrentDomain.BaseDirectory
when the application is being run within visual studio as I develop andSystem.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation
when it is executing normally.System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation
correctly returns the network directory that my clickonce application is deployed to, in all cases. That is, when it is launched via:
Here's the code I use at application startup to get the path of the WorkAccounts folder. Getting the deployed application folder is simple by just not marching up to parent directories:
string directoryOfInterest = "";
if (System.Diagnostics.Debugger.IsAttached)
{
directoryOfInterest = Directory.GetParent(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName).FullName;
}
else
{
try
{
string path = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
path = path.Replace("file:", "");
path = path.Replace("/", "\\");
directoryOfInterest = Directory.GetParent(Directory.GetParent(path).FullName).FullName;
}
catch (Exception ex)
{
directoryOfInterest = "Error getting update directory needed for relative base for finding WorkAccounts directory.\n" + ex.Message + "\n\nUpdate location directory is: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
}
}
The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address
The IIS is a multi web site server. The way is distinct the site is by the host header name. So you need to setup that on your web site.
Here is the steps that you need to follow:
How to configure multiple IIS websites to access using host headers?
In general, open your web site properties, locate the Ip Address and near its there is the advanced, "multiple identities for this web site". There you need ether to add all income to this site with a star: "*", ether place the names you like to work with.
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
function(url,callback){
request(url).on('data',(data) => {
try{
var json = JSON.parse(data);
}
catch(error){
callback("");
}
callback(json);
})
}
You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .
Alternatively, you could invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
I liked this example.
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
In my case, i had to save the file as UTF8 with BOM not just as UTF8 utf8
then this error was gone.
For me it started working after setting global username/email.
To set your global username/email configuration:
1. Open the command line.
2. Set your username:
git config --global user.name "FIRST_NAME LAST_NAME"
git config --global user.email "[email protected]"
git commit -m "comment"
git push heroku master
BOOM! It worked (atleast for me)
Check out this link (Running react-native run-ios occurs an error?). It appears to be a problem with the location of Command line tools
.
In Xcode, select Xcode menu, then Preferences, then Locations tab. Select your Xcode version from the dropdown and exit Xcode.
I wrote a class that downloads all of the data to the '.' location in the colab server
The whole thing can be pulled from here https://github.com/brianmanderson/Copy-Shared-Google-to-Colab
!pip install PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
import os
class download_data_from_folder(object):
def __init__(self,path):
path_id = path[path.find('id=')+3:]
self.file_list = self.get_files_in_location(path_id)
self.unwrap_data(self.file_list)
def get_files_in_location(self,folder_id):
file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format(folder_id)}).GetList()
return file_list
def unwrap_data(self,file_list,directory='.'):
for i, file in enumerate(file_list):
print(str((i + 1) / len(file_list) * 100) + '% done copying')
if file['mimeType'].find('folder') != -1:
if not os.path.exists(os.path.join(directory, file['title'])):
os.makedirs(os.path.join(directory, file['title']))
print('Copying folder ' + os.path.join(directory, file['title']))
self.unwrap_data(self.get_files_in_location(file['id']), os.path.join(directory, file['title']))
else:
if not os.path.exists(os.path.join(directory, file['title'])):
downloaded = drive.CreateFile({'id': file['id']})
downloaded.GetContentFile(os.path.join(directory, file['title']))
return None
data_path = 'shared_path_location'
download_data_from_folder(data_path)
"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.
@Georgiy Ivankin made a suggestion in a comment, I used it successfully :) -- , but with slight changes:
$('#note').on('keyup',function(e){
var maxHeight = 200;
var f = document.getElementById('note');
if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight )
{ f.style.height = f.scrollHeight + 'px'; }
});
It stops expanding after it reaches max height of 200px
There are two main classes of exception:
1) System exception (eg Database connection lost) or 2) User exception. (eg User input validation, 'password is incorrect')
I found it helpful to create my own User Exception Class and when I want to throw a user error I want to be handled differently (ie resourced error displayed to the user) then all I need do in my main error handler is check the object type:
If TypeName(ex) = "UserException" Then
Display(ex.message)
Else
DisplayError("An unexpected error has occured, contact your help desk")
LogError(ex)
End If
So you want to remove dangling images? Am I correct?
systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer
systemctl start docker-image-cleanup.timer
https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units
one could also use a fixed lengths vector and access it with indexing
int Lcs(string a, string b)
{
int x = a.size() + 1;
int y = b.size() + 1;
vector<vector<int>> L(x, vector<int>(y));
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
L[i][j] = a[i - 1] == b[j - 1] ?
L[i - 1][j - 1] + 1 :
max(L[i - 1][j], L[i][j - 1]);
}
}
return L[a.size()][b.size()];
}
I borrowed from ideas above. This is neither fast nor elegant. but it is accurate.
CASE
WHEN left(column, 3) = '000' THEN right(column, (len(column)-3))
WHEN left(column, 2) = '00' THEN right(a.column, (len(column)-2))
WHEN left(column, 1) = '0' THEN right(a.column, (len(column)-1))
ELSE
END
Just choose "Edit Top 200 rows", press Ctrl + 3 in the edit grid region (or click "Show SQL Pane") and edit the query...
But please note that this will work only for the query that doesn't contain "join"
Check Yasea library
Yasea is an Android streaming client. It encodes YUV and PCM data from camera and microphone to H.264/AAC, encapsulates in FLV and transmits over RTMP.
Feature:
In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.
Try below code using RJSONIO in console
library(RJSONIO)
library(RCurl)
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")
json_file2 = RJSONIO::fromJSON(json_file)
head(json_file2)
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
I realize that I'm a bit late with this, but you can also call sleep and pass the disired time in. For example, If I wanted to wait for 3 seconds I can do:
/bin/sleep 3
4 seconds would look like this:
/bin/sleep 4
I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:
from threading import Thread, Lock
mutex = Lock()
def processData(data):
mutex.acquire()
try:
print('Do some stuff')
finally:
mutex.release()
while True:
t = Thread(target = processData, args = (some_data,))
t.start()
But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.
An alternative, for Python 2.6 and later, is to use Python's multiprocessing
package. It mirrors the threading
package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:
from multiprocessing import Process, Lock
mutex = Lock()
def processData(data):
with mutex:
print('Do some stuff')
if __name__ == '__main__':
while True:
p = Process(target = processData, args = (some_data,))
p.start()
For handling the event on overing, you can try something like this (it works for me):
In the Html template:
<div (mouseenter)="onHovering($event)" (mouseleave)="onUnovering($event)">
<img src="../../../contents/ctm-icons/alarm.svg" class="centering-me" alt="Alerts" />
</div>
In the angular component:
onHovering(eventObject) {
console.log("AlertsBtnComponent.onHovering:");
var regExp = new RegExp(".svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, "_h.svg"));
}
}
onUnovering(eventObject) {
console.log("AlertsBtnComponent.onUnovering:");
var regExp = new RegExp("_h.svg" + "$");
var srcObj = eventObject.target.offsetParent.children["0"];
if (srcObj.tagName == "IMG") {
srcObj.setAttribute("src", srcObj.getAttribute("src").replace(regExp, ".svg"));
}
}
As always, http://www.csszengarden.com/. Note that the images aren't public domain.
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatu`enter code here`s) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
As far as I know, there are simply two safe ways: ssh or passwd encrypted using a keystore.
cat ~/.ssh/id_rsa.pub
, paste it there, name and save it (if you have no such file, generate one for yourself by ssh-keygen -t rsa
- just Enter for all prompts);git remote set-url origin git+ssh://[email protected]/username/reponame.git
- you can check it first by git remote -v
);touch t; git add t; git commit -m "test"; git push
and confirm yes to enjoy the password-free world.If you just use git config --global credential.helper store
as others mentioned, your unencrypted passwords will be just stored in a plain text under ~/.git-credentials
which is not safe as it sounds.
Try to encrypt it as
sudo apt-get install libgnome-keyring-dev
sudo make --directory=/usr/share/doc/git/contrib/credential/gnome-keyring
git config --global credential.helper /usr/share/doc/git/contrib/credential/gnome-keyring/git-credential-gnome-keyring
git config --global credential.helper store
In this case, you are using
https://[email protected]/username/reponame.git
.
As explained before:
ALTER TABLE TABLEName
drop CONSTRAINT FK_CONSTRAINTNAME;
ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
FOREIGN KEY (FId)
REFERENCES OTHERTABLE
(Id)
ON DELETE CASCADE ON UPDATE NO ACTION;
As you can see those have to be separated commands, first dropping then adding.
Since ViewPager is tending to be replaced by ViewPager2 and we will need to migrate to it.
A quick work around using Java would be something like this:
final List<String> colors = new ArrayList<String>(){
{
add("#FF0000");
add("#800000");
add("#FFFF00");
}
};
ViewPager2 viewPager = findViewById(R.id.viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(your_data_structure);
viewPager.setAdapter(adapter);
final TabLayout tabs = findViewById(R.id.tabs);
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.view.setAlpha((float) 0.5);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.view.setAlpha(1);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
TabLayoutMediator mediator = new TabLayoutMediator(tabs, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab" + position);
/*
* With this feature the TabIndicator color is ignored
* or covered by the new color ex.(if alpha channel is changed the indicator can be seen through)
*/
tab.view.setBackgroundColor(Color.parseColor(colors.get(position))); //You can use your HEX string color
}
});
mediator.attach();
Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "@" symbol in a much more convenient way:
NSString *myString = @"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!
SOLUTION 1 (combine find
and grep
)
The purpose of this solution is not to deal with grep
performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.
Use find
, for excluding directories foo and bar :
find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
Then combine find
and the non-recursive use of grep
, as a portable solution :
find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
SOLUTION 2 (using the --exclude-dir
option of grep
):
You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.
grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
To exclude multiple directories, use --exclude-dir
as:
--exclude-dir={node_modules,dir1,dir2,dir3}
SOLUTION 3 (Ag)
If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in .gitignore
, so you don't have to keep passing the same cumbersome exclude options to grep
or find
.
If you don't want to create another migration-file for a small, recent change - from Rails Console:
ActiveRecord::Migration.change_column :profiles, :show_attribute, :boolean, :default => true
Then exit and re-enter rails console, so DB-Changes will be in-effect. Then, if you do this ...
Profile.new()
You should see the "show_attribute" default-value as true.
For existing records, if you want to preserve existing "false" settings and only update "nil" values to your new default:
Profile.all.each{|profile| profile.update_attributes(:show_attribute => (profile.show_attribute == nil ? true : false)) }
Update the migration that created this table, so any future builds of the DB will get it right from the onset. Also run the same process on any deployed-instances of the DB.
If using the "new db migration" method, you can do the update of existing nil-values in that migration.
To change your background color of the botton use:
yourBtn.backgroundColor = UIColor.black
if you are using storyBoard
make sure you have connected your storyBoard
with your viewController
and also that your items are linked.
if you don´t know how to do this check the next link:
How to connect ViewController.swift to ViewController in Storyboard?
Unbind the mouseenter
and mouseleave
events individually or unbind all events on the element(s).
$(this).unbind('mouseenter').unbind('mouseleave');
or
$(this).unbind(); // assuming you have no other handlers you want to keep
It's because you have included a leading /
in your file path. The /
makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once
(one that doesn't start with a leading /
).
You can change it to this:
include_once 'headerSite.php';
That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\
in your example.
This setting needs to be set:
SET SERVEROUTPUT ON
Since we all love one-liners
... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
Documentation: Serializing and Deserializing JSON
Are there good reasons why it's a better practice to have only one return statement in a function?
Yes, there are:
The question is often posed as a false dichotomy between multiple returns or deeply nested if statements. There's almost always a third solution which is very linear (no deep nesting) with only a single exit point.
Update: Apparently MISRA guidelines promote single exit, too.
To be clear, I'm not saying it's always wrong to have multiple returns. But given otherwise equivalent solutions, there are lots of good reasons to prefer the one with a single return.
To force LF line endings for all text files, you can create .gitattributes
file in top-level of your repository with the following lines (change as desired):
# Ensure all C and PHP files use LF.
*.c eol=lf
*.php eol=lf
which ensures that all files that Git considers to be text files have normalized (LF
) line endings in the repository (normally core.eol
configuration controls which one do you have by default).
Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):
$ echo "* text=auto" >> .gitattributes
$ rm .git/index # Remove the index to force Git to
$ git reset # re-scan the working directory
$ git status # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"
or as per GitHub docs:
git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.
See also: @Charles Bailey post.
In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.
manual.pdf -text
Or mark it explicitly as binary:
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
To see some more advanced git normalization file, check .gitattributes
at Drupal core:
# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048
# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.
# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
# - Exposed by default in `git diff --color` on the CLI.
# - Validate with `git diff --check`.
# - Deny applying with `git apply --whitespace=error-all`.
# - Fix automatically with `git apply --whitespace=fix`.
*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot -text diff
*.exe -text diff
*.gif -text diff
*.gz -text diff
*.ico -text diff
*.jpeg -text diff
*.jpg -text diff
*.otf -text diff
*.phar -text diff
*.png -text diff
*.svgz -text diff
*.ttf -text diff
*.woff -text diff
*.woff2 -text diff
See also:
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label
See this link for more on the differences between a TextBlock and other Controls
You should find out last timestamp
values in each group (subquery), and then join this subquery to the table -
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.
Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.
In case you happen to be on Android and you are not using Jack yet (e.g. because it's still lacking support for Instant Run), and if you want more control over formatting of the resulting string (e.g. you would like to use the newline character as the divider of elements), and happen to use/want to use the StreamSupport library (for using streams on Java 7 or earlier versions of the compiler), you could use something like this (I put this method in my ListUtils class):
public static <T> String asString(List<T> list) {
return StreamSupport.stream(list)
.map(Object::toString)
.collect(Collectors.joining("\n"));
}
And of course, make sure to implement toString() on your list objects' class.
Alvaros JS free answer was a great start for me, and I really tried to get a truly JS-free answer that still delivered all the functionality expected of a Select with images, but sadly nesting forms was the down-fall. I'm posting two solutions here; my main solution that uses 1 line of JavaScript, and a totally JavaScript-free solution that won't work inside another form, but might be useful for nav menus.
Unfortunately there is a bit of repetition in the code, but when you think about what a Select does it makes sense. When you click on an option it copies that text to the selected area, i.e., clicking 1 of 4 options will not change the 4 options, but the top will now repeat the one you clicked. To do this with images would require JavaScript, orrrr... you duplicate the entries.
In my example we have a list of games (Products), which have versions. Each product may also have Expansions, which can also have versions. For each Product we give the user a list of each version if there's more than one, along with an image and version specific text.
<h4>@Model.Name</h4>
@if (Model.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@Model.Versions[0].ImageUrl" alt="">@Model.Versions[0].VersionName (@Model.Versions[0].Year)
</div>
}
else
{
<h5>Select the version</h5>
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<input type="radio" name="game" id="[email protected]@version.VersionId" @if (version == Model.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="rich-select-dropdown-button" class="rich-select-dropdown-button" />
<label for="rich-select-dropdown-button"></label>
<div class="rich-select-options">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('rich-select-dropdown-button').click();">
<img src="@version.ImageUrl" alt=""> @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
Using JS for the checkbox deselection we can have multiple instances on a form. Here I've extended to show a list of Expansions, which also have the same logic around versions.
<h5 class="mt-3">Include Expansions?</h5>
@foreach (var expansion in Model.Expansions)
{
<div class="form-row">
<div class="custom-control custom-checkbox w-100">
<input type="checkbox" class="expansion-checkbox custom-control-input" id="[email protected]">
<label class="custom-control-label w-100" for="[email protected]">
@if (expansion.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@expansion.ImageUrl" />@expansion.Name: @expansion.Versions[0].VersionName (@expansion.Versions[0].Year)
</div>
}
else
{
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<input type="radio" name="[email protected]" id="[email protected]@version.VersionId" @if (version == expansion.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="[email protected]" class="rich-select-dropdown-button" />
<label for="[email protected]"></label>
<div class="rich-select-options">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('[email protected]').click();">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
</label>
</div>
</div>
Of course this requires a fair bit of CSS, which I've only included in this JSFiddle to reduce the size of this already massive answer. I've used Bootstrap 4 to reduce the amount needed, and also to allow it to fit in with other Bootstrap controls and any site customisations that have been made.
The images are set to 75px, but this can easily be changed in 5 lines in .rich-select
and .rich-select-option-body img
try that method.....
function popitup(url) {
//alert(url);
newwindow=window.open("http://www.zeeshanakhter.com","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
newwindow.moveTo(350,150);
if (window.focus)
{
newwindow.focus()
}
return false;
}
I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.
The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.
check out
http://www.thesitewizard.com/general/set-cron-job.shtml
for the specifics of setting your crontab directives.
45 10 * * *
will run in the 10th hour, 45th minute of every day.
for midnight... maybe
0 0 * * *
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList
is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector
, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList
.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements
Method. Aside from all the input
Nodes, the RadioNodeList
also includes a property value
, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel.
Solved in Catalina
look into my screenshot
To convert the Keys to a List of their own:
listNumber = dicNumber.Select(kvp => kvp.Key).ToList();
Or you can shorten it up and not even bother using select:
listNumber = dicNumber.Keys.ToList();
Among the other well-explained answers about memory alignment and structure padding/packing, there is something which I have discovered in the question itself by reading it carefully.
"Why isn't
sizeof
for a struct equal to the sum ofsizeof
of each member?""Why does the
sizeof
operator return a size larger for a structure than the total sizes of the structure's members"?
Both questions suggest something what is plain wrong. At least in a generic, non-example focused view, which is the case here.
The result of the sizeof
operand applied to a structure object can be equal to the sum of sizeof
applied to each member separately. It doesn't have to be larger/different.
If there is no reason for padding, no memory will be padded.
One most implementations, if the structure contains only members of the same type:
struct foo {
int a;
int b;
int c;
} bar;
Assuming sizeof(int) == 4
, the size of the structure bar
will be equal to the sum of the sizes of all members together, sizeof(bar) == 12
. No padding done here.
Same goes for example here:
struct foo {
short int a;
short int b;
int c;
} bar;
Assuming sizeof(short int) == 2
and sizeof(int) == 4
. The sum of allocated bytes for a
and b
is equal to the allocated bytes for c
, the largest member and with that everything is perfectly aligned. Thus, sizeof(bar) == 8
.
This is also object of the second most popular question regarding structure padding, here:
You might want to start with scapy.
Why not get the html first then pass it to the web view?
private String getHtml(String url){
HttpGet pageGet = new HttpGet(url);
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String html;
if (entity != null) {
html = EntityUtils.toString(entity);
return html;
} else {
return null;
}
}
};
pageHTML = null;
try {
while (pageHTML==null){
pageHTML = client.execute(pageGet, handler);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageHTML;
}
@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
webview.getSettings().setJavaScriptEnabled(true);
WebViewClient anchorWebViewClient = new WebViewClient()
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Do what you want to with the html
String html = getHTML(url);
if( html!=null && !url.equals(lastLoadedURL)){
lastLoadedURL = url;
webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
}
}
This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.
I was looking for a ES6 example (so it could pass my linter) So for other people who are looking for the same:
$('#dSuggest').keyup((e) => {
console.log(e.currentTarget.value);
});
I would also use keyup because you get the current value that is filled in.
You can use either h()
or html_escape()
, but most people use h()
by convention. h()
is short for html_escape()
in rails.
In your controller:
@stuff = "<b>Hello World!</b>"
In your view:
<%=h @stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>
.
It will appear an be displayed as <b>Hello World!</b>
When you annotate a parameter with @RequestHeader
, the parameter retrieves the header information. So you can just do something like this:
@RequestHeader("Accept")
to get the Accept
header.
So from the documentation:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}
The Accept-Encoding
and Keep-Alive
header values are provided in the encoding
and keepAlive
parameters respectively.
And no worries. We are all noobs with something.
How about this
for (int i = 0; i < str.length(); i++) {
System.out.println(str.substring(i, i + 1));
}
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
As an alternative SuperPutty has tabs and the option to run the same command across many terminals... might be what someone is looking for.
https://code.google.com/p/superputty/
It imports your PuTTY sessions too.
In case 1, because of order of operations you get:
(hello + ", world") + "!" which resolves to hello + "!" and finally to hello
In case 2, as James noted, you get:
("Hello" + ", world") + exclam which is the concat of 2 string literals.
Hope it's clear :)
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
Of course, it lays in the nature of your question, so answers are highly subjective.
The first response of a website is also only a small part of the time until a page is readable/usable.
I am annoyed by everything larger than 10 sec responses. I think a website should be rendered after 5-7 sec.
Btw: stackoverflow.com has an excellent response time!
With Swift 4.2 (Xcode 10), we can do this
#if targetEnvironment(simulator)
//simulator code
#else
#warning("Not compiling for simulator")
#endif
Below code work in php for all string with special character
// Encrypt text --
$token = "9611222007552";
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
echo $crypted_token;
//unset($token, $cipher_method, $enc_key, $enc_iv);
// Decrypt text --
list($crypted_token, $enc_iv) = explode("::", $crypted_token);
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest(php_uname(), 'SHA256', TRUE);
$token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
echo $token;
//unset($crypted_token, $cipher_method, $enc_key, $enc_iv);
Lets assume we have a graph which has n number of nodes and m number of edges,
Adjacency Matrix: We are creating a matrix that has n number of rows and columns so in memory it will take space that is proportional to n2. Checking if two nodes named as u and v has an edge between them will take T(1) time. For example checking for (1, 2) is an edge will look like as follows in the code:
if(matrix[1][2] == 1)
If you want to identify all edges, you have to iterate over matrix at this will require two nested loops and it will take T(n2). (You may just use the upper triangular part of the matrix to determine all edges but it will be again T(n2))
Adjacency List: We are creating a list that each node also points to another list. Your list will have n elements and each element will point to a list that has number of items that is equal to number of neighbors of this node (look image for better visualization). So it will take space in memory that is proportional to n+m. Checking if (u, v) is an edge will take O(deg(u)) time in which deg(u) equals number of neighbors of u. Because at most, you have to iterate over the list that is pointed by the u. Identifying all edges will take T(n+m).
Adjacency list of example graph
You should make your choice according to your needs.
Because of my reputation I couldn't put image of matrix, sorry for that
I'm also looking for the same solution. And I think of
BtnventCss.CssClass = BtnventCss.CssClass + " hom_but_a";
It seems working fine but I'm not sure if it is a good practice
Late to this one, but I just discovered an alternative way of doing it:
On your template,
<a (click)="navigateAssociates()">Associates</a>
And on your component.ts, you can use serializeUrl
to convert the route into a string, which can be used with window.open()
navigateAssociates() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/page1'])
);
window.open(url, '_blank');
}
HTML 5 invites you give add a lot of semantic value to your code. What's more, there are natives solution to embed multimedia content.
The rest is important, but it's more technical sugar that will save you from doing the same stuff with a client programming language.
If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:
tsc a.ts --target es6 --module commonjs
More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
If you use tsconfig.json
, then like this:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
}
}
More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json
In visual studio for .Net 4.0 framework,
System.Runtime.Serialization
. using System.Runtime.Serialization
. And the error will not be shown. Get the value for an array of associative arrays's property when the property name is an integer:
Starting with an Associative Array where the property names are integers:
var categories = [
{"1":"Category 1"},
{"2":"Category 2"},
{"3":"Category 3"},
{"4":"Category 4"}
];
Push items to the array:
categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});
Loop through array and do something with the property value.
for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
var category = categories[i][categoryid];
// log progress to the console
console.log(categoryid + " : " + category);
// ... do something
}
}
Console output should look like this:
1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301
As you can see, you can get around the associative array limitation and have a property name be an integer.
NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.
Issue:
.Net application code aborts before it starts its execution [Console application or Windows application]
Error received: Aborted with Error code "E0434352"
Exception: Unknown exception
Scenario 1:
When an application is already executed, which have used some of the dependent resources and those resources are still in use with the application executed, when another application or the same exe is triggered from some other source then one of the app throws the error
Scenario 2:
When an application is triggered by scheduler or automatic jobs, it may be in execution state at background, meanwhile when you try to trigger the same application again, the error may be triggered.
Solution:
Create an application, when & where the application release all its resources as soon as completed Kill all the background process once the application is closed Check and avoid executing the application from multiple sources like Batch Process, Task Scheduler and external tools at same time. Check for the Application and resource dependencies and clean up the code if needed.
As you're generating the image dynamically, set the onload
property before the src
.
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";
Fiddle - tested on latest Firefox and Chrome releases.
You can also use the answer in this post, which I adapted for a single dynamically generated image:
var img = new Image();
// 'load' event
$(img).on('load', function() {
alert("image is loaded");
});
img.src = "img.jpg";
Recently I started using the Mac Pc for android development. When I go to
Android Studio => File => Other setting => Preference for New Projects..
I was not able to find plugin option in the setting page.
Later while clicking option on the toolbar, I clicked on "SDK Manager" it prompted the Settings where the Plugin option was visible and I was able to add the plugins from here.
[
OpenCV uses something like:
/* in the header file */
#ifdef __cplusplus
/* in case the compiler is a C++ compiler */
#define DEFAULT_VALUE(value) = value
#else
/* otherwise, C compiler, do nothing */
#define DEFAULT_VALUE(value)
#endif
void window_set_size(unsigned int width DEFAULT_VALUE(640),
unsigned int height DEFAULT_VALUE(400));
If the user doesn't know what he should write, this trick can be helpful:
I tried everything. Reinstalling Tomcat is what finally worked. Here's what I've checked before reinstalling.
Make sure your environmental variables look like this.
$ echo $JAVA_HOME
C:\Program Files\Java\jdk1.7.0_51\
$ echo $JRE_HOME
C:\Program Files\Java\jdk1.7.0_51\jre\bin
Make sure Eclipse is using the same jre you set JAVA_HOME to (if JAVA_HOME is not set it will look at JRE_HOME). Window > Prefrences > Java > Installed JREs
(the checked one is the default one)
If you made any changes to any of your tomcat files especially catalina.bat or startup.bat, then you may be telling tomcat to look at a different version of java than the one you set to JAVA_HOME C:\Program Files (x86)\Apache\apache-tomcat-7.0.26\bin
db.<collectionName>.find({"IMAGE URL":{"$exists":"true"}, "IMAGE URL": {$ne: null}})
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
If performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days
is unintuitive because rounding will depend on the hour component of StartDate
and EndDate
.
(EndDate - StartDate).TotalDays
.(EndDate.Date - StartDate.Date).Days
(EndDate.Date - StartDate.Date).Days + 1
As many others have said, htmlentities()
will do the trick... but it will look like shit.
Wrap it up with a <pre>
tag and you'll preserve your indentation.
echo '<pre>';
echo htmlspecialchars($YOUR_HTML);
echo '</pre>';
May be this will help someone:
<?php
$string = "Your line of text";
$spl = preg_match("/([, \.\d\-''\"\"_()]*\w+[, \.\d\-''\"\"_()]*){50}/", $string, $matches);
if (isset($matches[0])) {
$matches[0] .= "...";
echo "<br />" . $matches[0];
} else {
echo "<br />" . $string;
}
?>
Another thing to keep in mind is that the string itself might be null.
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
Earlier when I wasn't granted permission to access the repo, I had also added the SSH pubkey to gitlab. At the point I could access the repo and run go mod vendor, the same problem as your happens. (maybe because of cache)
go mod vendor
go: errors parsing go.mod:
/Users/macos/Documents/sample/go.mod:22: git ls-remote -q https://git.aaa.team/core/some_repo.git in /Users/macos/go/pkg/mod/cache/vcs/a94d20a18fd56245f5d0f9f1601688930cad7046e55dd453b82e959b12d78369: exit status 128:
fatal: could not read Username for 'https://git.aaa.team': terminal prompts disabled
After a while trying, I decide to remove the SSH key and terminal prompts filling in username and password. Everything is fine then!
This works for me (reference):
# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off
# Disable display of all other errors
php_flag display_errors off
# Disable HTML markup of errors
php_flag html_errors off
# Enable logging of errors
php_flag log_errors on
# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off
# Disable ignoring of unique source errors
php_flag ignore_repeated_source off
# Enable logging of PHP memory leaks
php_flag report_memleaks on
# Preserve most recent error via php_errormsg
php_flag track_errors on
# Disable formatting of error reference links
php_value docref_root 0
# Disable formatting of error reference links
php_value docref_ext 0
# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1
# Disable max error string length
php_value log_errors_max_len 0
# Protect error log by preventing public access
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
Visual Studio 2003 doesn't seem to allow you to set environment variables for debugging.
What I do in C/C++ is use _putenv()
in main()
and set any variables. Usually I surround it with a #if defined DEBUG_MODE / #endif
to make sure only certain builds have it.
_putenv("MYANSWER=42");
I believe you can do the same thing with C# using os.putenv(), i.e.
os.putenv('MYANSWER', '42');
These will set the envrironment variable for that shell process only, and as such is an ephemeral setting, which is what you are looking for.
By the way, its good to use process explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx), which is a sysinternals tool. You can see what a given process' copy of the environment variables is, so you can validate that what you set is what you got.
Based on zenpoy's answer:
import Image
import numpy
def image2pixelarray(filepath):
"""
Parameters
----------
filepath : str
Path to an image file
Returns
-------
list
A list of lists which make it simple to access the greyscale value by
im[y][x]
"""
im = Image.open(filepath).convert('L')
(width, height) = im.size
greyscale_map = list(im.getdata())
greyscale_map = numpy.array(greyscale_map)
greyscale_map = greyscale_map.reshape((height, width))
return greyscale_map
To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:
select profile from DBA_USERS where username = '<username>';
Then you can change the limit to never expire using:
alter profile <profile_name> limit password_life_time UNLIMITED;
If you want to previously check the limit you may use:
select resource_name,limit from dba_profiles where profile='<profile_name>';
Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo_locations);
// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);
String country = gpsTracker.getCountryName(this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText(country);
String city = gpsTracker.getLocality(this);
textview = (TextView)findViewById(R.id.fieldCity);
textview.setText(city);
String postalCode = gpsTracker.getPostalCode(this);
textview = (TextView)findViewById(R.id.fieldPostalCode);
textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText(addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
return true;
}
}
GPS Tracker
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
/**
* Create this Class from tutorial :
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
*
* For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
*
*/
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* @return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* @return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.
Article: Getting the Last Known Location
Assuming that EXIT_CODE is referring to System . exit
( exit_code ) then you could do
enum ExitCode
{
NORMAL_SHUTDOWN ( 0 ) , EMERGENCY_SHUTDOWN ( 10 ) , OUT_OF_MEMORY ( 20 ) , WHATEVER ( 30 ) ;
private int value ;
ExitCode ( int value )
{
this . value = value ;
}
public void exit ( )
{
System . exit ( value ) ;
}
}
Then you can put the following at appropriate spots in your code
ExitCode . NORMAL_SHUTDOWN . exit ( ) '
In HTML4.01:
Name Attribute
<a>
, <form>
, <iframe>
, <img>
, <map>
, <input>
, <select>
, <textarea>
getElementsByName()
id
attributename
attribute are submitted to the serverId Attribute
<base>
, <html>
, <head>
, <meta>
, <param>
, <script>
, <style>
, <title>
#
signgetElementById()
, and jQuery by $(#<id>)
_
), dashes (-
), colons (:
), or periods (.
)In (X)HTML5, everything is the same except:
Name Attribute
<form>
anymoreId Attribute
This question was written when HTML4.01 was the norm, and many browsers and features were different from today.
Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer
C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks()
method to it, in particular, to do exactly what you require).
On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer
, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).
I see a lot of complicated answers, while this is super simple in Bootstrap 3:
Step 1: Use the official example code to create your radio button group, and give the container an id:
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
</label>
</div>
Step 2: Use this jQuery handler:
$("#myButtons :input").change(function() {
console.log(this); // points to the clicked input button
});
declare @sql nvarchar(max);
set @sql = N'select cast(''master'' as sysname) as db_name, name collate Latin1_General_CI_AI, object_id, schema_id, cast(1 as int) as database_id from master.sys.tables ';
select @sql = @sql + N' union all select ' + quotename(name,'''')+ ', name collate Latin1_General_CI_AI, object_id, schema_id, ' + cast(database_id as nvarchar(10)) + N' from ' + quotename(name) + N'.sys.tables'
from sys.databases where database_id > 1
and state = 0
and user_access = 0;
exec sp_executesql @sql;
An alternative to using the PGPASSWORD
environment variable is to use the conninfo
string according to the documentation:
An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.
$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"
postgres=>
casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:
List<? extends TestA> myList = new ArrayList<TestA>();
You still have type checking to do when you are using the objects in the list.
function stripTrailingSlash(text) {
return text
.split('/')
.filter(Boolean)
.join('/');
}
another solution.
Read the spec for the attributes and for CSS.
id
must be unique. class
does not have to beid
has higher (highest!) specificity in CSSid
id
can be used as an anchor target (using the fragment of the request) for any element. name
only works with anchors (<a>
)First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
If there is a root layout like RelativeLayout or LinearLayout which contain all of the adapter item's component in CardView, you have to set background attribute in that root layout. like:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="122dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/touch_bg"/>
</android.support.v7.widget.CardView>
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)
$value = (float) $xml->code[0]->lat;
Also, (int)
for integer number:
$value = (int) $xml->code[0]->distance;
Yep I would say thirtydot has it, there is no way to do it unless you use a js method. You are talking about a complex set of rendering conditions that you will have to define. e.g. what happens when both cells are getting too big for their apartments you will have to decide who has priority or simply just give them a percentage of the area and if they are overfull they will both take up that area and only if one has whitespace will you stretch your legs in the other cell, either way there is no way to do it with css. Although there are some pretty funky things people do with css that I have not thought of. I really doubt you can do this though.
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
Had the same issue; validated HTML & found I was missing a name="email"
attribute from an <input />
. Always validate the HTML to be positive your HTML is valid. After I added it, validate()
worked perfectly.
In my case
Solution:
Go to itunes inside the page of my app and inside the first tab "App Information" under the right hand side has a section "Others Information" click on the "edit user permission" and grant xcode user the permission to read the information of the app.
DONE
$(document).keydown(function(e) {_x000D_
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))_x000D_
{_x000D_
e.preventDefault();_x000D_
alert("Ctrl-s pressed");_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Try pressing ctrl+s somewhere.
_x000D_
This is an up-to-date version of @AlanBellows's answer, replacing which
with key
. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
itertools.combinations is in general the fastest way to get combinations from a Python container (if you do in fact want combinations, i.e., arrangements WITHOUT repetitions and independent of order; that's not what your code appears to be doing, but I can't tell whether that's because your code is buggy or because you're using the wrong terminology).
If you want something different than combinations perhaps other iterators in itertools, product
or permutations
, might serve you better. For example, it looks like your code is roughly the same as:
for val in itertools.product(np.arange(0, 1, 0.1), repeat=6):
print F(val)
All of these iterators yield tuples, not lists or numpy arrays, so if your F is picky about getting specifically a numpy array you'll have to accept the extra overhead of constructing or clearing and re-filling one at each step.
Can also use the following code to check the nginx status:
sudo /etc/init.d/nginx status
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
Remember that you can look up the definition of Prelude functions!
http://www.haskell.org/onlinereport/standard-prelude.html
Looking there, the definition of words
is,
words :: String -> [String]
words s = case dropWhile Char.isSpace s of
"" -> []
s' -> w : words s''
where (w, s'') = break Char.isSpace s'
So, change it for a function that takes a predicate:
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
"" -> []
s' -> w : wordsWhen p s''
where (w, s'') = break p s'
Then call it with whatever predicate you want!
main = print $ wordsWhen (==',') "break,this,string,at,commas"
In .net core you can make post-call with following code, here I added some extra features to this code so can make your code work behind a proxy and with network credentials if any, also here I mention that you can change the encoding of your message. I hope this explains all and help you in coding.
HttpClient client = GetHttpClient(_config);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
}
client.BaseAddress = new Uri(baseAddress);
Encoding encoding = Encoding.UTF8;
var result = await client.PostAsync(url, new StringContent(body, encoding, "application/json")).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
return new RequestResponse { severity = "Success", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}
else
{
return new RequestResponse { severity = "failure", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}
public HttpClient GetHttpClient(IConfiguration _config)
{
bool ProxyEnable = Convert.ToBoolean(_config["GlobalSettings:ProxyEnable"]);
HttpClient client = null;
if (!ProxyEnable)
{
client = new HttpClient();
}
else
{
string ProxyURL = _config["GlobalSettings:ProxyURL"];
string ProxyUserName = _config["GlobalSettings:ProxyUserName"];
string ProxyPassword = _config["GlobalSettings:ProxyPassword"];
string[] ExceptionURL = _config["GlobalSettings:ExceptionURL"].Split(';');
bool BypassProxyOnLocal = Convert.ToBoolean(_config["GlobalSettings:BypassProxyOnLocal"]);
bool UseDefaultCredentials = Convert.ToBoolean(_config["GlobalSettings:UseDefaultCredentials"]);
WebProxy proxy = new WebProxy
{
Address = new Uri(ProxyURL),
BypassProxyOnLocal = BypassProxyOnLocal,
UseDefaultCredentials = UseDefaultCredentials,
BypassList = ExceptionURL,
Credentials = new NetworkCredential(ProxyUserName, ProxyPassword)
};
HttpClientHandler handler = new HttpClientHandler { Proxy = proxy };
client = new HttpClient(handler,true);
}
return client;
}
var groupedCustomerList = CustomerList.GroupBy(u => u.GroupID)
.Select(grp =>new { GroupID =grp.Key, CustomerList = grp.ToList()})
.ToList();
Why don't you use a for loop instead of using foreach. In this scenario, there is no way you can get the index of the current iteration of the foreach loop.
The name of the file can be added to the string[] in this way,
private string[] ColeccionDeCortes(string Path)
{
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion=new string[listaDeArchivos.Length];
for (int i = 0; i < listaDeArchivos.Length; i++)
{
Coleccion[i] = listaDeArchivos[i].Name;
}
return Coleccion;
}
Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern
You can change the decorator at runtime with one that has different properties when an event occurs.
Self-referencing as example
public class Employee {
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int ManagerId { get; set; }
public virtual Employee Manager { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public Employee() {
Employees = new HashSet<Employee>();
}
}
HasMany(e => e.Employees)
.WithRequired(e => e.Manager)
.HasForeignKey(e => e.ManagerId)
.WillCascadeOnDelete(false);
Step 1: Go to the the first column of the first line you want to comment.
Step 2: Press: Ctrl+v and select the lines you want to comment:
Step 3: Shift-I
#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)
Step 4: Esc
Just complementing, I implemented this way and usually worked in my Service class
In my Service
@Override
public void onCreate()
{
mHandler = new Handler(Looper.getMainLooper());
mHandler.post(this);
super.onCreate();
}
@Override
public void onDestroy()
{
mHandler.removeCallbacks(this);
super.onDestroy();
}
@Override
public void run()
{
InciarGPSTracker();
}
I simply created a file called code:
#!/bin/bash
open /Applications/Visual\ Studio\ Code.app $1
Make it executable:
$ chmod 755 code
Then put that in /usr/local/bin
$ sudo mv code /usr/local/bin
As long as the file sits someplace that is in your path you can open a file by just typing: code
before you get too excited this was written in 2011
if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011
Date.getTimezoneOffset()
The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.
For example, If your time zone is GMT+2, -120 will be returned.
Note: This method is always used in conjunction with a Date object.
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11
Another subtlety that I don't believe has been covered by the other answers is for when you have a class and namespace with the same name.
When you have the import inside the namespace then it will find the class. If the import is outside the namespace then the import will be ignored and the class and namespace have to be fully qualified.
//file1.cs
namespace Foo
{
class Foo
{
}
}
//file2.cs
namespace ConsoleApp3
{
using Foo;
class Program
{
static void Main(string[] args)
{
//This will allow you to use the class
Foo test = new Foo();
}
}
}
//file2.cs
using Foo; //Unused and redundant
namespace Bar
{
class Bar
{
Bar()
{
Foo.Foo test = new Foo.Foo();
Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
}
}
}
Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:
INSERT INTO TABLE tweet_table VALUES ('data');
Use this code:
<div class="hidden"><li><a href="somehwere">Link text</a></li></div>
%RANDOM%
gives you a random number between 0 and 32767.
Using an expression like SET /A test=%RANDOM% * 100 / 32768 + 1
, you can change the range to anything you like (here the range is [1…100] instead of [0…32767]).
This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I faced the same problem ant it took me tow days to figure out a solution that worked for me :
google-play-services_lib
(right click on the project delete )MainActivity
in my case ) if you have oneYou should see something like this :
Note : You should not have something like this ( the project should be referred from your workspace ):
I think that the problem is that tow projects are referencing the same library
I've been using some simple CSS and it seems to remove them and work fine.
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
This tutorial from CSS Tricks explains in detail & also shows how to style them
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame:
JFrame
extends Component
and Container
.
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel:
JPanel
extends Component
, Container
and JComponent
It is a generic class used to group other Component
s together.
It is useful when working with LayoutManager
s e.g. GridLayout
f.i adding components to different JPanel
s which will then be added to the JFrame
to create the gui. It will be more manageable in terms of Layout
and re-usability.
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
You just need to add one more attribute to your DIV tag which is
data-interval="false"
no need to touch JS!
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector("input").addEventListener("keypress", function (evt) {
if (evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
In JDK 1.7, you can get system CPU and memory usage via com.sun.management.OperatingSystemMXBean
. This is different than java.lang.management.OperatingSystemMXBean
.
long getCommittedVirtualMemorySize()
Returns the amount of virtual memory that is guaranteed to be available to the running process in bytes, or -1 if this operation is not supported.
long getFreePhysicalMemorySize()
Returns the amount of free physical memory in bytes.
long getFreeSwapSpaceSize()
Returns the amount of free swap space in bytes.
double getProcessCpuLoad()
Returns the "recent cpu usage" for the Java Virtual Machine process.
long getProcessCpuTime()
Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.
double getSystemCpuLoad()
Returns the "recent cpu usage" for the whole system.
long getTotalPhysicalMemorySize()
Returns the total amount of physical memory in bytes.
long getTotalSwapSpaceSize()
Returns the total amount of swap space in bytes.
Foo foo2();
change to
Foo foo2;
You get the error because compiler thinks of
Foo foo2()
as of function declaration with name 'foo2' and the return type 'Foo'.
But in that case If we change to Foo foo2
, the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous"
.
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.
A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.
Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1
I think this is the simplest solution. Pure shell builtins, no inline math. It borrows from previous answers.
Just substrings and the ${#...} meta-variable.
A="[>---------------------<]";
# Strip excess padding from the right
#
B="A very long header"; echo "${A:0:-${#B}} $B"
B="shrt hdr" ; echo "${A:0:-${#B}} $B"
Produces
[>----- A very long header
[>--------------- shrt hdr
# Strip excess padding from the left
#
B="A very long header"; echo "${A:${#B}} $B"
B="shrt hdr" ; echo "${A:${#B}} $B"
Produces
-----<] A very long header
---------------<] shrt hdr
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators
a -> b
is member b of object pointed to by a
pg_hba.conf
entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf
in order to get proper help.
Change this line:
host all all <my-ip-address>/32 md5
To reflect your local network settings. So, if your IP is 192.168.16.78
(class C) with a mask of 255.255.255.0
, then put this:
host all all 192.168.16.0/24 md5
Make sure your WINDOWS MACHINE is in that network 192.168.16.0
and try again.
To convert a string to lower case in Python, use something like this.
list.append(sentence.lower())
I found this in the first result after searching for "python upper to lower case".
using Android KTX library u can parse easily
val uri = myUriString.toUri()
Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.
Ammend your while statement to this...
for(var iIndex = 1; iIndex <= data.length; iIndex++){
if (data[iIndex][0] === name){
break;
};
Logger.log(data[i][0]);
};
Just to clarify in complete detail. This is what works with the current version of jQuery Ui
$( "#tabs" ).tabs( "option", "active", # );
where # is the index of the tab you want to make active.
WhatsApp does not have a API available for public use. As you put it, it's a closed system.
However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.
// CREATE anim
// CREATE animation,animation2 xml // animation like fade out
Intent myIntent1 = new Intent(getApplicationContext(), Attend.class);
Bundle bndlanimation1 = ActivityOptions.makeCustomAnimation(getApplicationContext(),
R.anim.animation, R.anim.animation2).toBundle();
tartActivity(myIntent1, bndlanimation1);
As I can see: http://itsolutionstuff.com/post/laravel-5-clear-cache-from-route-view-config-and-all-cache-data-from-applicationexample.html
is it possible to use the code below with the new clear cache commands:
//Clear Cache facade value:
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('cache:clear');
return '<h1>Cache facade value cleared</h1>';
});
//Reoptimized class loader:
Route::get('/optimize', function() {
$exitCode = Artisan::call('optimize');
return '<h1>Reoptimized class loader</h1>';
});
//Route cache:
Route::get('/route-cache', function() {
$exitCode = Artisan::call('route:cache');
return '<h1>Routes cached</h1>';
});
//Clear Route cache:
Route::get('/route-clear', function() {
$exitCode = Artisan::call('route:clear');
return '<h1>Route cache cleared</h1>';
});
//Clear View cache:
Route::get('/view-clear', function() {
$exitCode = Artisan::call('view:clear');
return '<h1>View cache cleared</h1>';
});
//Clear Config cache:
Route::get('/config-cache', function() {
$exitCode = Artisan::call('config:cache');
return '<h1>Clear Config cleared</h1>';
});
It's not necessary to give the possibility to clear the caches to everyone, especially in a production enviroment, so I suggest to comment that routes and, when it's needed, to de-comment the code and run the routes.
I just created a simple jQuery plugin for that. Try it ;)
Use the following methods
1: Method one
var count = 123;
var message = $"Rows count is: {count}";
2: Method two
var count = 123;
var message = "Rows count is:" + count;
3: Method three
var count = 123;
var message = string.Format("Rows count is:{0}", count);
4: Method four
var count = 123;
var message = @"Rows
count
is:{0}" + count;
5: Method five
var count = 123;
var message = $@"Rows
count
is: {count}";
In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmd
header looks like
---
title : French TER (regional train) monthly regularity
subtitle : since January 2013
author : brigasnuncamais
job : Business Intelligence / Data Scientist consultant
framework : impressjs # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
knit : slidify::knit2slides
subdirs are:
/assets /css /impress-demo.css
/fig /unnamed-chunk-1-1.png (generated by included R code)
/img /SS850452.png (my image used as background)
/js /impress.js
/layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
/libraries /frameworks /impressjs
/io2012
/highlighters /highlight.js
/impress.js
index.Rmd
A slide with image in background code snippet would be in my .Rmd:
<div id="bg">
<img src="assets/img/SS850452.png" alt="">
</div>
Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.
Your Best Approach is to install Wireshark, reboot the device wait for the TCP/UDP stream , broadcasts will announce the IP address for both Ethernet ports This is especially useful when the device connected does not have DHCP Client enabled, then you can go from there.
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:
var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
For example, something like:
player p;
showInventory(p);
I'm guessing you have something like this:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
int main()
{
player p;
toDo(p);
}
and
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName'
AND TABLE_SCHEMA = SchemaName)
BEGIN
ALTER TABLE TableName DROP COLUMN ColumnName;
END;
'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basically if a cast can be made) and returns null if the check fails.
These two are equivalent:
Using 'as':
string s = o as string;
Using 'is':
if(o is string)
s = o;
else
s = null;
On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.
Just to add an important fact:
The 'as' keyword only works with reference types. You cannot do:
// I swear i is an int
int number = i as int;
In those cases you have to use casting.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.
It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)
This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.
In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.
Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.
I created some methods based Daniel's reply above.
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
CGSize maximumLabelSize = CGSizeMake(290, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
return expectedLabelSize.height;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label
{
CGRect newFrame = label.frame;
newFrame.size.height = [self heightForLabel:label withText:label.text];
label.frame = newFrame;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
label.text = text;
[self resizeHeightToFitForLabel:label];
}
Error parsing XML: unbound prefix
Resource '/playteddy/res' does not exist.
I got the above two errors and finally I solved it.
Right click your project -> properties -> java build path -> googleadmobadsdk (select and put it top), then you run and problem solved. It is solved my runtime error.
In a single-byte ASCII-compatible encoding (e.g. Latin-1), ASCII characters are simply bytes in the range 0 to 127. So you can use something like [\x80-\xFF]
to detect non-ASCII characters.
If none of the above suggestions works for you, try using the style
attribute.
**Notes**
<p style="color:red;">ERROR: Setting focus didn't work for me when I tried from jupyter. However it worked well when I ran it from the terminal</p>
This gives me the following result
With a BorderLayout you need to use setPreferredSize
instead of setSize
def reverse(text):
reversed = ''
for i in range(len(text)-1, -1, -1):
reversed += text[i]
return reversed
print("reverse({}): {}".format("abcd", reverse("abcd")))
Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010"
. But you would have to parse the value on the server.
OK, as others note, the best thing to do is to use java.util.concurrent
package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.
As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.
Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.
If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start()
method at least. You should construct the object (you can instantiate the Thread
object), and then call start()
to start the thread.
Edit: ExecutorService
have their own queue so this can be confusing.. Here's something to get you started.
public class Main {
public static void main(String[] args) {
//The numbers are just silly tune parameters. Refer to the API.
//The important thing is, we are passing a bounded queue.
ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));
//No need to bound the queue for this executor.
//Use utility method instead of the complicated Constructor.
ExecutorService producer = Executors.newSingleThreadExecutor();
Runnable produce = new Produce(consumer);
producer.submit(produce);
}
}
class Produce implements Runnable {
private final ExecutorService consumer;
public Produce(ExecutorService consumer) {
this.consumer = consumer;
}
@Override
public void run() {
Pancake cake = Pan.cook();
Runnable consume = new Consume(cake);
consumer.submit(consume);
}
}
class Consume implements Runnable {
private final Pancake cake;
public Consume(Pancake cake){
this.cake = cake;
}
@Override
public void run() {
cake.eat();
}
}
Further EDIT:
For producer, instead of while(true)
, you can do something like:
@Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//do stuff
}
}
This way you can shutdown the executor by calling .shutdownNow()
. If you'd use while(true)
, it won't shutdown.
Also note that the Producer
is still vulnerable to RuntimeExceptions
(i.e. one RuntimeException
will halt the processing)
Get-ADUser -Filter {Enabled -eq $true} -Properties Name,Manager,LastLogon |
Select-Object Name,Manager,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}
I know these answers are enough, but I'll show the place that's throwing an error.
If you have the structure like the below:
./Src/Master.cs
- (Master Form Page)./Invoice/SubFolder/InvoiceEdit.aspx
- (Sub Form Page)If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png")
.
Now ResolveClientUrl
is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png
. This is the wrong way.
Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../
.
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
Above provided answer is good for extracting single property, what if you want to extract more than one property from array of objects. Here is the solution!! In case of that we can simply use _.pick(object, [paths])
_.pick(object, [paths])
Lets assume objArray has objects with three properties like below
objArray = [ { foo: 1, bar: 2, car:10}, { foo: 3, bar: 4, car:10}, { foo: 5, bar: 6, car:10} ];
Now we want to extract foo and bar property from every object and store them in a separate array. First we will iterate array elements using map and then we apply Lodash Library Standard _.pick() method on it.
Now we are able to extract 'foo' and 'bar' property.
var newArray = objArray.map((element)=>{ return _.pick(element, ['foo','bar'])})
console.log(newArray);
and result would be [{foo: 1, bar: 2},{foo: 3, bar: 4},{foo: 5, bar: 6}]
enjoy!!!
This worked.
var s = Path.Combine(@"C:\some\location", @"..\other\file.txt");
s = Path.GetFullPath(s);
Normally i use a class for this:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray
if you really need an array:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Note that i've presumed that the first column is a string
and the second an integer
. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY
methods.
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
If someone used this:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
PreferenceManager is now depricated, refactor to this:
val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)
I was having this issue because gradle
and Android Studio
were using a different path for the jvm
. In the Event Log
there was an option for AS and gradle
to use the same path. Selecting this and then doing an invalidate cache & restart
resolved the issue for me.
with 2008 Server 2008 and 2008 R2
Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100
with 2012 and 2014
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
What you mean is either
SELECT DISTINCT a, b FROM pairs;
or
SELECT a, b FROM pairs GROUP BY a, b;
Set box-sizing
property to border-box
:
div {_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 20px solid #f00;_x000D_
background: #00f;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div + div {_x000D_
border: 10px solid red;_x000D_
}
_x000D_
<div>Hello!</div>_x000D_
<div>Hello!</div>
_x000D_
It works on IE8 & above.
For verbose
> 0, fit
method logs:
Note: If regularization mechanisms are used, they are turned on to avoid overfitting.
if validation_data
or validation_split
arguments are not empty, fit
method logs:
Note: Regularization mechanisms are turned off at testing time because we are using all the capabilities of the network.
For example, using verbose
while training the model helps to detect overfitting which occurs if your acc
keeps improving while your val_acc
gets worse.
Have you tried like:
[HttpGet("Summary")]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet("FullDetails")]
public HttpResponseMessage FullDetails()
{
return null;
}
No exact equivalent. However there exist a native DOS command "more" that has a +n option that will start outputting the file after the nth line:
DOS Prompt:
C:\>more +2 myfile.txt
The above command will output everything after the first 2 lines.
This is actually the inverse of Unix head:
Unix console:
root@server:~$ head -2 myfile.txt
The above command will print only the first 2 lines of the file.
You can also set language at runtime
sqldeveloper.exe --AddVMOption=-Duser.language=en
to avoid editing sqldeveloper.conf every time you install new version.
public class Factorial {
public static void main(String[] args) {
int n = 7;
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
System.out.println("The factorial of 7 is " + result);
}
}
InetAddress.getLocalHost().getHostName()
is better (as explained by Nick), but still not very good
One host can be known under many different hostnames. Usually you'll be looking for the hostname your host has in a specific context.
For example, in a web application, you might be looking for the hostname used by whoever issued the request you're currently handling. How to best find that one depends on which framework you're using for your web application.
In some kind of other internet-facing service, you'll want the hostname your service is available through from the 'outside'. Due to proxies, firewalls etc this might not even be a hostname on the machine your service is installed on - you might try to come up with a reasonable default, but you should definitely make this configurable for whoever installs this.
Vue
allows for you to specify a default prop
value and type
directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):
props: {
year: {
default: 2016,
type: Number
}
}
If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:
Just to propose a sed
alternative. :) To skip first one million lines, try |sed '1,1000000d'
.
Example:
$ perl -wle 'print for (1..1_000_005)'|sed '1,1000000d'
1000001
1000002
1000003
1000004
1000005
The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:
export class FilterPipe implements PipeTransform {
transform(items: any[], filterBy: string): any {
return items.filter(item => item.id.indexOf(filterBy) !== -1);
}
}
And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:
export class ProductFilterPipe implements PipeTransform {
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
}
And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
I found the path of the SDK (Preferences* ? Android ? SDK Location) was the cause. My SDK path was the following:
C:\Program Files (x86)\Android\android-sdk
The spaces in the path is the problem. To get it to work, you must change Program Files (x86)
to Progra~2
The complete right path is C:\Progra~2\Android\android-sdk
.
Now it should work.
I've commented on some of the other answers here, so I figured I would weigh in too. At the end of the day, since PHP doesn't support typed enumerations, you can go one of two ways: hack out typed enumerations, or live with the fact that they're extremely difficult to hack out effectively.
I prefer to live with the fact, and instead use the const
method that other answers here have used in some way or another:
abstract class Enum
{
const NONE = null;
final private function __construct()
{
throw new NotSupportedException(); //
}
final private function __clone()
{
throw new NotSupportedException();
}
final public static function toArray()
{
return (new ReflectionClass(static::class))->getConstants();
}
final public static function isValid($value)
{
return in_array($value, static::toArray());
}
}
An example enumeration:
final class ResponseStatusCode extends Enum
{
const OK = 200;
const CREATED = 201;
const ACCEPTED = 202;
// ...
const SERVICE_UNAVAILABLE = 503;
const GATEWAY_TIME_OUT = 504;
const HTTP_VERSION_NOT_SUPPORTED = 505;
}
Using Enum
as a base class from which all other enumerations extend allows for helper methods, such as toArray
, isValid
, and so on. To me, typed enumerations (and managing their instances) just end up too messy.
If, there existed a __getStatic
magic method (and preferably an __equals
magic method too) much of this could be mitigated with a sort of multiton pattern.
(The following is hypothetical; it won't work, though perhaps one day it will)
final class TestEnum
{
private static $_values = [
'FOO' => 1,
'BAR' => 2,
'QUX' => 3,
];
private static $_instances = [];
public static function __getStatic($name)
{
if (isset(static::$_values[$name]))
{
if (empty(static::$_instances[$name]))
{
static::$_instances[$name] = new static($name);
}
return static::$_instances[$name];
}
throw new Exception(sprintf('Invalid enumeration value, "%s"', $name));
}
private $_value;
public function __construct($name)
{
$this->_value = static::$_values[$name];
}
public function __equals($object)
{
if ($object instanceof static)
{
return $object->_value === $this->_value;
}
return $object === $this->_value;
}
}
$foo = TestEnum::$FOO; // object(TestEnum)#1 (1) {
// ["_value":"TestEnum":private]=>
// int(1)
// }
$zap = TestEnum::$ZAP; // Uncaught exception 'Exception' with message
// 'Invalid enumeration member, "ZAP"'
$qux = TestEnum::$QUX;
TestEnum::$QUX == $qux; // true
'hello world!' == $qux; // false
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
I did not want to add style to <body>
tag and <html>
tag.
.quodrant{
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}
.qtop,
.qbottom{
width: 100%;
height: 50vh;
}
.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
display: inline;
float: left;
width: 50%;
height: 100%;
}
.quodrant1{
top: 0;
left: 50vh;
background-color: red;
}
.quodrant2{
top: 0;
left: 0;
background-color: yellow;
}
.quodrant3{
top: 50vw;
left: 0;
background-color: blue;
}
.quodrant4{
top: 50vw;
left: 50vh;
background-color: green;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<div class='quodrant'>
<div class='qtop'>
<div class='quodrant1'></div>
<div class='quodrant2'></div>
</div>
<div class='qbottom'>
<div class='quodrant3'></div>
<div class='quodrant4'></div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
Or making it looks nicer.
.quodrant{
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
}
.qtop,
.qbottom{
width: 96%;
height: 46vh;
}
.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
display: inline;
float: left;
width: 46%;
height: 96%;
border-radius: 30px;
margin: 2%;
}
.quodrant1{
background-color: #948be5;
}
.quodrant2{
background-color: #22e235;
}
.quodrant3{
background-color: #086e75;
}
.quodrant4{
background-color: #7cf5f9;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<div class='quodrant'>
<div class='qtop'>
<div class='quodrant1'></div>
<div class='quodrant2'></div>
</div>
<div class='qbottom'>
<div class='quodrant3'></div>
<div class='quodrant4'></div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
Your user.jsp:
<form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
---
---
</form:form>
In your controller class:
(make it as a meaning full method name..Hear i think you are insert record in DB.)
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String proffessionalDetails(
@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("PROFESSIONAL", professionalForm);
return "Your Professional Details Updated";
}
Now that I've separated the classes to .h and .cpp files do I need to use a makefile or can I still use the "g++ main.cpp" command?
Compiling several files at once is a poor choice if you are going to put that into the Makefile.
Normally in a Makefile (for GNU/Make), it should suffice to write that:
# "all" is the name of the default target, running "make" without params would use it
all: executable1
# for C++, replace CC (c compiler) with CXX (c++ compiler) which is used as default linker
CC=$(CXX)
# tell which files should be used, .cpp -> .o make would do automatically
executable1: file1.o file2.o
That way make
would be properly recompiling only what needs to be recompiled. One can also add few tweaks to generate the header file dependencies - so that make would also properly rebuild what's need to be rebuilt due to the header file changes.
const changedArray = array.filter( function(value) {
return value !== 'B'
});
or you can use :
const changedArray = array.filter( (value) => value === 'B');
The changedArray will contain the without value 'B'
I had this problem using GitExtensions on windows. Fixed by granting full permission for the current user (me) on the folder that contained the repo.
Another time, I even though I was getting the error from Git Extensions, I was able to commit the same files from Visual Studio 2015.
Another time I had to delete the "index" file from the .git folder
echo date('Y-m-d H:i:s.') . gettimeofday()['usec'];
output:
2016-11-19 15:12:34.346351
As Admin, create directory:
mkdir c:\mongo\data\db
As Admin, install service:
.\mongod.exe --install --logpath c:\mongo\logs --logappend --bind_ip 127.0.0.1 --dbpath c:\mongo\data\db --directoryperdb
Start MongoDB:
net start MongoDB
Start Mongo Shell:
c:\mongo\bin\mongo.exe