Create this class as Extension:
public static class Extensiones
{
public static string FolderName(this OpenFileDialog ofd)
{
string resp = "";
resp = ofd.FileName.Substring(0, 3);
var final = ofd.FileName.Substring(3);
var info = final.Split('\\');
for (int i = 0; i < info.Length - 1; i++)
{
resp += info[i] + "\\";
}
return resp;
}
}
Then, you could use in this way:
//ofdSource is an OpenFileDialog
if (ofdSource.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(ofdSource.FolderName());
}
I wrote about it on my blog a long time ago, WPF's support for common file dialogs is really bad (or at least is was in 3.5 I didn't check in version 4) - but it's easy to work around it.
You need to add the correct manifest to your application - that will give you a modern style message boxes and folder browser (WinForms FolderBrowserDialog) but not WPF file open/save dialogs, this is described in those 3 posts (if you don't care about the explanation and only want the solution go directly to the 3rd):
Fortunately, the open/save dialogs are very thin wrappers around the Win32 API that is easy to call with the right flags to get the Vista/7 style (after setting the manifest)
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
CFAbsoluteTimeGetCurrent()
returns the absolute time as a double
value, but I don't know what its precision is -- it might only update every dozen milliseconds, or it might update every microsecond, I don't know.
In the fragment where you would like to handle your back button you should attach stuff to your view in the oncreateview
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
v.setOnKeyListener(pressed);
return v;
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if( keyCode == KeyEvent.KEYCODE_BACK ){
// back to previous fragment by tag
myfragmentclass fragment = (myfragmentclass) getActivity().getSupportFragmentManager().findFragmentByTag(TAG);
if(fragment != null){
(getActivity().getSupportFragmentManager().beginTransaction()).replace(R.id.cf_g1_mainframe_fm, fragment).commit();
}
return true;
}
return false;
}
};
The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC
See http://play.golang.org/p/vTidOlmb9P
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.
It will usually be mounted to /mnt but if not run
sudo mount /dev/xvda2 /mnt
To then create a swap file on this device do the following for a 4GB swapfile
sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096
Make sure no other user can view the swap file
sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile
Make and Flag as swap
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
Add/Make sure the following are in your /etc/fstab
/dev/xvda2 /mnt auto defaults,nobootwait,comment=cloudconfig 0 2
/mnt/swapfile swap swap defaults 0 0
lastly enable swap
sudo swapon -a
Verify that you can start your application like that:
java -cp myjarfile.jar snake.Controller
I just read when I double click on it - this sounds like a configuration issue with your operating system. You're double-clicking the file on a windows explorer window? Try to run it from a console/terminal with the command
java -jar myjarfile.jar
Further Reading
The manifest has to end with a new line. Please check your file, a missing new line will cause trouble.
The simplest solution is to add @Test annotated method to class where initialisation exception is present.
In our project we have main class with initial settings. I've added @Test method and exception has disappeared.
We can iterate object using in keyword and can perform any arithmetic operation.
// input
const sample = {
'a': 1,
'b': 2,
'c': 3
};
// var
let sum = 0;
// object iteration
for (key in sample) {
//sum
sum += (+sample[key]);
}
// result
console.log("sum:=>", sum);
_x000D_
This is how I base
ically think of the problem.
my.df <- data.frame(group = rep(c(1,2), each = 3),
score = runif(6), info = letters[1:6])
my.agg <- with(my.df, aggregate(score, list(group), max))
my.df.split <- with(my.df, split(x = my.df, f = group))
my.agg$info <- unlist(lapply(my.df.split, FUN = function(x) {
x[which(x$score == max(x$score)), "info"]
}))
> my.agg
Group.1 x info
1 1 0.9344336 a
2 2 0.7699763 e
In migration file check the public override void Up() method. May be you are trying to create a new db object which is already in database. So, you need to drop this object/table before creation of the db object. Just do like bellow-
DropTable("dbo.ABC");
CreateTable(
"dbo.ABC",
c => new
{
Id = c.Int(nullable: false, identity: true),
..
}
And now run your migration
Update-Database -TargetMigration: "2016_YourMigration"
Use TOP 1
if the query returns multiple rows.
SELECT TOP 1 @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.
The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
To clear a permanent redirect, go to chrome://settings/clearBrowserData and from there only clearing "cached images and files" cleared the redirect.
Go to chrome://net-internals. On the right of the top red status bar, click on the down arrow ? to open the drop-down menu, and under the "Tools" group, choose "Clear cache".
As of version 48, this was the only thing that worked for me to clear a cached 301.
I don't think you can at present: see this article on the Postgresql wiki.
The three workarounds from this article are:
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
To set the use of scientific notation in your entire R session, you can use the scipen
option. From the documentation (?options
):
‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.
So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999
:
options(scipen=999)
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
Let me use names a
(in place of XXX
and ZZZ
) and b
(in place of YYY
), since that makes the description a bit easier to read.
Say you want to merge repository a
into b
(I'm assuming they're located alongside one another):
cd a
git filter-repo --to-subdirectory-filter a
cd ..
cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a
For this you need git-filter-repo
installed (filter-branch
is discouraged).
An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731
More on it here.
Set the form property to open in maximized state.
this.WindowState = FormWindowState.Maximized;
You can still use installutil without visual studio, it is included with the .net framework
On your server, open a command prompt as administrator then:
CD C:\Windows\Microsoft.NET\Framework\v4.0.version (insert your version)
installutil "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)
To uninstall:
installutil /u "C:\Program Files\YourWindowsService\YourWindowsService.exe" (insert your service name/location)
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
I'm thinking something like, just give an idea, to convert the column to string, and work with string is easier. however this does not work with strings containing numbers, like bad123
. and ~
is taking the complement of selection.
df['a'] = df['a'].astype(str)
df[~df['a'].str.contains('0|1|2|3|4|5|6|7|8|9')]
df['a'] = df['a'].astype(object)
and using '|'.join([str(i) for i in range(10)])
to generate '0|1|...|8|9'
or using np.isreal()
function, just like the most voted answer
df[~df['a'].apply(lambda x: np.isreal(x))]
Numpy Array -> Panda Data Frame -> List from one Panda Column
Numpy Array
data = np.array([[10,20,30], [20,30,60], [30,60,90]])
Convert numpy array into Panda data frame
dataPd = pd.DataFrame(data = data)
print(dataPd)
0 1 2
0 10 20 30
1 20 30 60
2 30 60 90
pdToList = list(dataPd['2'])
One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.
If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.
If the variable is entered like a string (e.g. '2010'
):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
Before using this I worked it out with try/except
and checking for (int(variable))
, but it was longer code. I wonder if there's any difference in use of resources or speed.
For Retrofit retrofit:2.0.0-beta4
the code goes as follows:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.yourapp.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
I installed gem package mysql2.
gem install mysql2
and then I changed the adapter in mysql2 in database.yml.
I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:
function(a, b) {
if (typeof a == "undefined") {
a = 10;
}
if (typeof b == "undefined") {
a = 20;
}
alert("a: " + a + " b: " + b);
}
Use driver.save_screenshot('/path/to/file')
or driver.get_screenshot_as_file('/path/to/file')
:
import selenium.webdriver as webdriver
import contextlib
@contextlib.contextmanager
def quitting(thing):
yield thing
thing.quit()
with quitting(webdriver.Firefox()) as driver:
driver.implicitly_wait(10)
driver.get('http://www.google.com')
driver.get_screenshot_as_file('/tmp/google.png')
# driver.save_screenshot('/tmp/google.png')
Assuming that you don't have a library or system header that defines NULL
as for example (void*)0
or (char*)0
it's fine. I always tend to use 0 myself as it is by definition the null pointer. In c++0x you'll have nullptr
available so the question won't matter as much anymore.
Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.
In htaccess:
SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
in index.php
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
// instead of mapping:
$app->options('/(:x+)', function() use ($app) {
//...return correct headers...
$app->response->setStatus(200);
});
You would have to turn your font into a web font as shown in these SO questions:
However, you may run into copyright issues with this: Not every font allows distribution as a web font. Check your font license to see whether it is allowed.
One of the easiest free and legal ways to use web fonts is Google Web Fonts. However, sadly, they don't have Helvetica Neue in their portfolio.
One of the easiest non-free and legal ways is to purchase the font from a foundry that offers web licenses. I happen to know that the myFonts foundry does this; they even give you a full package with all the JavaScript and CSS pre-prepared. I'm sure other foundries do the same.
Edit: MyFonts have Helvetica neue in Stock, but apparently not with a web license. Check out this list of similar fonts of which some have a web license. Also, Ray Larabie has some nice fonts there, with web licenses, some of them are free.
Have you tried setting JButton.setOpaque(true)?
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);
The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.
As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:
Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.
What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.
By encode, do you mean: Convert all applicable characters to HTML entities?
htmlspecialchars
or
htmlentities
You can also use strip_tags if you want to remove all HTML tags :
Note: this will NOT stop all XSS attacks
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)
Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)
Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;
html {_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
_x000D_
a {_x000D_
text-decoration: none;_x000D_
color: black;_x000D_
} _x000D_
_x000D_
#down {_x000D_
margin-top: 100%;_x000D_
padding-bottom: 25%;_x000D_
}
_x000D_
<html>_x000D_
<a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
<div id="down">_x000D_
<h1>You are down!</h1>_x000D_
</div>_x000D_
</html
_x000D_
The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.
File
--> Setting
project
section --> Project interpreter
Project interpreter
[NOTE]:
Tested on Pycharm 2018 and 2017.
May also want to use "documentElement":
var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);
Today I had a scenario, where I was performing following:
myViewGroup.setVisibility(View.GONE);
Right on the next frame I was performing an if
check somewhere else for visibility state of that view. Guess what? The following condition was passing:
if(myViewGroup.getVisibility() == View.VISIBLE) {
// this `if` was fulfilled magically
}
Placing breakpoints you can see, that visibility changes to GONE
, but right on the next frame it magically becomes VISIBLE
. I was trying to understand how the hell this could happen.
Turns out there was an animation applied to this view, which internally caused the view to change it's visibility to VISIBLE
until finishing the animation:
public void someFunction() {
...
TransitionManager.beginDelayedTransition(myViewGroup);
...
myViewGroup.setVisibility(View.GONE);
}
If you debug, you'll see that myViewGroup
indeed changes its visibility to GONE
, but right on the next frame it would again become visible in order to run the animation.
So, if you come across with such a situation, make sure you are not performing an if
check in amidst of animating the view.
You can remove all animations on the view via View.clearAnimation()
.
Yes; functions (and methods) are first class objects in Python. The following works:
def foo(f):
print "Running parameter f()."
f()
def bar():
print "In bar()."
foo(bar)
Outputs:
Running parameter f().
In bar().
These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.
After some fiddling with a script I came to this action. Copy and save it in a .bat file:
FOR /F "usebackq tokens=5" %%i IN (`netstat -aon ^| find "3306"`) DO taskkill /F /PID %%i
Change 'find "3306"' in the port number which needs to be free. Then run the file as administrator. It will kill all the processes running on this port.
You can simply use %
twice, that is "%%"
Example:
printf("You gave me 12.3 %% of profit");
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
This means your google-services.json file either does not belong to your application(Did you download the google-services.json for another app?)...so to solve this do the following:
1:Sign in to Firebase and open your project. 2:Click the Settings icon and select Project settings. 3:In the Your apps card, select the package name of the app you need a config file for from the list. 4:Click google-services.json. After the download completes,add the new google-services.json to your project root folder,replacing the existing one..or just delete the old one. Its very normal to download the google-services.json for your first project and then assume or forget that this specific google-services.json is tailored for your current project alone,because not any other because all projects have a unique package name.
You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().
Example:
try {
int i = Integer.parseint(stringToParse);
//parseInt succeded
} catch(Exception e)
{
//parseInt failed
}
Is there an option like "treat ^M as newline when diffing" ?
There will be one with Git 2.16 (Q1 2018), as the "diff
" family of commands learned to ignore differences in carriage return at the end of line.
See commit e9282f0 (26 Oct 2017) by Junio C Hamano (gitster
).
Helped-by: Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 10f65c2, 27 Nov 2017)
diff:
--ignore-cr-at-eol
A new option
--ignore-cr-at-eol
tells the diff machinery to treat a carriage-return at the end of a (complete) line as if it does not exist.Just like other "
--ignore-*
" options to ignore various kinds of whitespace differences, this will help reviewing the real changes you made without getting distracted by spuriousCRLF<->LF
conversion made by your editor program.
Technically you don't need to install it globally if the node_modules
folder in your local installation is in your PATH
. Generally this isn't a good idea.
Alternatively if npm test
references gulp
then you can just type npm test
and it'll run the local gulp.
I've never installed gulp globally -- I think it's bad form.
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
Source article: Java: Calling super()
Yes. super(...)
will invoke the constructor of the super-class.
Illustration:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
In latest version of android studio ,We can change the appearance settings like font size and font style using following steps Android Studio ---->preference--font
ECONNREFUSED error
There are few reasons of this error in node :
Your port is already serving some service so it will refuse your connection.
go to command line and get pid by using following command
$ lsof -i:port_number
Now kill pid by using
$ kill -9 pid(which you will get by above command)
Your server is not running e.g. in this case please check your mongoose server is running or run by using following command.
$ mongod
There is also possibility your localhost
is not configured properly so use 127.0.0.1:27017
instead of localhost.
Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled
, .is(':disabled')
, .attr('disabled')
, .prop('disabled')
. But no one works for me.
Some, for example .disabled
or .is(':disabled')
returned undefined
and other like .attr('disabled')
returned the wrong result - false
when the button was actually disabled.
But only one technique works for me: .is('[disabled]')
(with square brackets).
So to determine if a button is disabled try this:
$("#myButton").is('[disabled]');
In Vim, use :insert
. This will keep all your formatting and not do autoindenting. For more information help :insert
.
This can also be done in later versions of handlebars using the key=value
notation:
{{> mypartial foo='bar' }}
Allowing you to pass specific values to your partial context.
Reference: Context different for partial #182
You can have one alternative of using placeholders as:
@Query("Select c from Registration c where c.place LIKE %?1%")
List<Registration> findPlaceContainingKeywordAnywhere(String place);
I had to do: c:\Users\xxxx>c:/python27/scripts/pip install openpyxl
I had to save the openpyxl files in the scripts folder.
I apologize if this is too late to reply, but since I've been doing something similar I thought I could contribute somehow.
Maybe with OpenCV you could use template matching. Assuming you're using a webcam as you said:
Tip: max_val (or min_val depending on the method used) will give you numbers, large numbers. To get the difference in percentage, use template matching with the same image -- the result will be your 100%.
Pseudo code to exemplify:
previous_screenshot = ...
current_screenshot = ...
# simplify both images somehow
# get the 100% corresponding value
res = matchTemplate(previous_screenshot, previous_screenshot, TM_CCOEFF)
_, hundred_p_val, _, _ = minMaxLoc(res)
# hundred_p_val is now the 100%
res = matchTemplate(previous_screenshot, current_screenshot, TM_CCOEFF)
_, max_val, _, _ = minMaxLoc(res)
difference_percentage = max_val / hundred_p_val
# the tolerance is now up to you
Hope it helps.
set print elements 0
set print elements
number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements
command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.
If you are using JQuery, since the 1.6 you have to use the .prop() method :
$('select option:nth(1)').prop("selected","selected");
For swift version
func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapDim: CGSize) -> Double {
var bounds = bounds
let WORLD_DIM = CGSize(width: 256, height: 256)
let ZOOM_MAX: Double = 21.0
func latRad(_ lat: Double) -> Double {
let sin2 = sin(lat * .pi / 180)
let radX2 = log10((1 + sin2) / (1 - sin2)) / 2
return max(min(radX2, .pi), -.pi) / 2
}
func zoom(_ mapPx: CGFloat,_ worldPx: CGFloat,_ fraction: Double) -> Double {
return floor(log10(Double(mapPx) / Double(worldPx) / fraction / log10(2.0)))
}
let ne = bounds.northEast
let sw = bounds.southWest
let latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / .pi
let lngDiff = ne.longitude - sw.longitude
let lngFraction = lngDiff < 0 ? (lngDiff + 360) : (lngDiff / 360)
let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
return min(latZoom, lngZoom, ZOOM_MAX)
}
I don't know what you consider pathological, but let me provide some alternatives you could have not seen before:
List<E> sl= list ;
while( ! sl.empty() ) {
E element= sl.get(0) ;
.....
sl= sl.subList(1,sl.size());
}
Or its recursive version:
void visit(List<E> list) {
if( list.isEmpty() ) return;
E element= list.get(0) ;
....
visit(list.subList(1,list.size()));
}
Also, a recursive version of the classical for(int i=0...
:
void visit(List<E> list,int pos) {
if( pos >= list.size() ) return;
E element= list.get(pos) ;
....
visit(list,pos+1);
}
I mention them because you are "somewhat new to Java" and this could be interesting.
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
private bool CheckAll()
{
if ( ....)
{
return true;
}
return false;
}
When the if-condition is false the method doesn't know what value should be returned (you probably get an error like "not all paths return a value").
As CQQL pointed out if you mean to return true when your if-condition is true you could have simply written:
private bool CheckAll()
{
return (your_condition);
}
If you have side effects, and you want to handle them before you return, the first (long) version would be required.
Here is an example of how you can do it in Spring 4.0+
application.properties
content:some.key=yes,no,cancel
@Autowire
private Environment env;
...
String[] springRocks = env.getProperty("some.key", String[].class);
See this.
In [14]: re.match("mandy", "MaNdY", re.IGNORECASE)
Out[14]: <_sre.SRE_Match object at 0x23a08b8>
To do this you can come up with a width you feel is ok for both buttons and then create a custom class with the width and add it to your buttons like so:
CSS
.custom {
width: 78px !important;
}
I can then use this class and add it to the buttons like so:
<p><button href="#" class="btn btn-primary custom">Save</button></p>
<p><button href="#" class="btn btn-success custom">Download</button></p>
Demo: http://jsfiddle.net/yNsxU/
You can take that custom class you create and place it inside your own stylesheet, which you load after the bootstrap stylesheet. We do this because any changes you place inside the bootstrap stylesheet might get accidentally lost when you update the framework, we also want your changes to take precedence over the default values.
I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.
If print it out in the console, or in a message box, does it show with two backslashes or one?
If you actually want to replace a double backslash with a single one, it's easy to do so:
text = text.Replace(@"\\", @"\");
... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.
EDIT: In response to the edited question, your stringToBeReplaced
only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length
and count the characters.
public static final long SECOND_IN_MILLIS = 1000;
public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
You could cast int but I would recommend using long.
new_data <- data %>% filter_all(any_vars(is.na(.)))
This should create a new data frame (new_data
) with only the missing values in it.
Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).
use this from your command line:
sudo install_name_tool -id /usr/local/mysql-connector-c-6.1.3-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/local/mysql-connector-c-6.1.3-osx10.7-x86_64/lib/libmysqlclient.18.dylib
tried on fews computers with maverick always works
This works for me.
void pause()
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::string dummy;
std::cout << "Press any key to continue . . .";
std::getline(std::cin, dummy);
}
Your program is still running. You have to kill it by closing the command line window. If you press control alt delete, task manager, process`s (kill the ones that match your filename).
For what it's worth: I just had the same problem, after editing the nginx.conf
file. I tried and tried restarting it by commanding sudo nginx restart
and various other commands. None of them produced any output. Commanding sudo nginx -t
to check the configuration file gave the output sudo: nginx: command not found
, which was puzzling. I was starting to think there were problems with the path.
Finally, I logged in as root (sudo su
) and commanded sudo nginx restart
. Now, the command displayed an error message concerning the configuration file. After fixing that, it restarted successfully.
Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.
All clockwise:
The endroid/QrCode library is easy to use, well maintained, and can be installed using composer. There is also a bundle to use directly with Symfony.
Installing :
$ composer require endroid/qrcode
Usage :
<?php
use Endroid\QrCode\QrCode;
$qrCode = new QrCode();
$qrCode
->setText('Life is too short to be generating QR codes')
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setLabel('Scan the code')
->setLabelFontSize(16)
->setImageType(QrCode::IMAGE_TYPE_PNG)
;
// now we can directly output the qrcode
header('Content-Type: '.$qrCode->getContentType());
$qrCode->render();
// or create a response object
$response = new Response($qrCode->get(), 200, array('Content-Type' => $qrCode->getContentType()));
Extract all real numbers using this.
public static ArrayList<Double> extractNumbersInOrder(String str){
str+='a';
double[] returnArray = new double[]{};
ArrayList<Double> list = new ArrayList<Double>();
String singleNum="";
Boolean numStarted;
for(char c:str.toCharArray()){
if(isNumber(c)){
singleNum+=c;
} else {
if(!singleNum.equals("")){ //number ended
list.add(Double.valueOf(singleNum));
System.out.println(singleNum);
singleNum="";
}
}
}
return list;
}
public static boolean isNumber(char c){
if(Character.isDigit(c)||c=='-'||c=='+'||c=='.'){
return true;
} else {
return false;
}
}
I wrote an article for that topic: DTO vs Value Object vs POCO.
In short:
I had similar problem with polish language
I tried:
$fileEndEnd = mb_convert_encoding($fileEndEnd, 'UTF-8', mb_detect_encoding($fileEndEnd, 'UTF-8', true));
I tried:
$fileEndEnd = utf8_encode ( $fileEndEnd );
I tried:
$fileEndEnd = iconv( "UTF-8", "UTF-8", $fileEndEnd );
And then -
$fileEndEnd = mb_convert_encoding($fileEndEnd, 'HTML-ENTITIES', "UTF-8");
This last worked perfectly !!!!!!
If you don't have avahi installed then it's probably cups.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id;
will display the ID of the last inserted row.
Hope this helps.
I just want to add something to Mark's comment. If you want to reuse array without additional allocation, just use it again and override existing values with new ones. It will work if you fill the array sequentially. In this case just remember the last initialized element and use array until this index. It is does not matter that there is some garbage in the end of the array.
100, it will hold the same references. Therefore if you make a change to a specific object in the list
, it will affect the same object in anotherList
.
Adding or removing objects in any of the list will not affect the other.
list
and anotherList
are two different instances, they only hold the same references of the objects "inside" them.
Ruby on rails uses ::
for namespace resolution.
class User < ActiveRecord::Base
VIDEOS_COUNT = 10
Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}
end
To use it :
User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"
Also, other usage is : When using nested routes
OmniauthCallbacksController
is defined under users.
And routed as:
devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
end
You've got all the necessary pieces somewhere in this thread:
if cv2.waitKey(): cv2.destroyAllWindows()
works fine for me in IDLE.
I was curious to see the performance difference between these
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x) / np.sum(np.exp(x), axis=0)
def softmaxv2(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
def softmaxv3(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / np.sum(e_x, axis=0)
def softmaxv4(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x - np.max(x)) / np.sum(np.exp(x - np.max(x)), axis=0)
x=[10,10,18,9,15,3,1,2,1,10,10,10,8,15]
Using
print("----- softmax")
%timeit a=softmax(x)
print("----- softmaxv2")
%timeit a=softmaxv2(x)
print("----- softmaxv3")
%timeit a=softmaxv2(x)
print("----- softmaxv4")
%timeit a=softmaxv2(x)
Increasing the values inside x (+100 +200 +500...) I get consistently better results with the original numpy version (here is just one test)
----- softmax
The slowest run took 8.07 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 17.8 µs per loop
----- softmaxv2
The slowest run took 4.30 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv3
The slowest run took 4.06 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23 µs per loop
----- softmaxv4
10000 loops, best of 3: 23 µs per loop
Until.... the values inside x reach ~800, then I get
----- softmax
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: overflow encountered in exp
after removing the cwd from sys.path.
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide
after removing the cwd from sys.path.
The slowest run took 18.41 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv2
The slowest run took 4.18 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.8 µs per loop
----- softmaxv3
The slowest run took 19.44 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 23.6 µs per loop
----- softmaxv4
The slowest run took 16.82 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 22.7 µs per loop
As some said, your version is more numerically stable 'for large numbers'. For small numbers could be the other way around.
Compare also the difference between {}
and set()
with a single word argument.
>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'}
>>> b = {'aardvark'}
>>> b
{'aardvark'}
but both a
and b
are sets of course.
Another option for Python users:
from jenkinsapi.jenkins import Jenkins
#get the server instance
jenkins_url = 'http://<jenkins-hostname>:<jenkins-port>/jenkins'
server = Jenkins(jenkins_url, username = '<user>', password = '<password>')
#get the installed plugins as list and print the pairs
plugins_dictionary = server.get_plugins().get_plugins_dict()
for key, value in plugins_dictionary.iteritems():
print "Plugin name: %s, version: %s" %(key, value.version)
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.
public static void installNumberCharacters(AbstractDocument document) {
document.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
try {
if (string.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, string, attr);
return;
}
Double.parseDouble(string);
super.insertString(fb, offset, string, attr);
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
try {
if (text.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, text, attrs);
return;
}
Double.parseDouble(text);
super.replace(fb, offset, length, text, attrs);
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
});
}
hr
{
background-color: #123455;
}
the background is the one you should try to change
You can also work with the borders color. i am not sure i think there are crossbrowser issues with this. you should test it in differrent browsers
Seems we could use a new HTML5 feature if the browser version is not a problem:
in HTML files :
<div class="centerBloc">
I will be in the center
</div>
And in CSS file, we write:
body .centerBloc {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
And so the div could be perfectly center in browser.
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
saved-username
-p;", then enter the saved password.This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted. Trying an npm install again won't save the problem.
Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.
The inherit
value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html
element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.
The font-family
property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.
If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family
set to inherit
or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.
This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.
Try this...
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
This bug cost me 2 days. I checked my Server log, the Preflight Option request/response between browser Chrome/Edge and Server was ok. The main reason is that GET/POST/PUT/DELETE server response for XHTMLRequest must also have the following header:
access-control-allow-origin: origin
"origin" is in the request header (Browser will add it to request for you). for example:
Origin: http://localhost:4221
you can add response header like the following to accept for all:
access-control-allow-origin: *
or response header for a specific request like:
access-control-allow-origin: http://localhost:4221
The message in browsers is not clear to understand: "...The requested resource"
note that: CORS works well for localhost. different port means different Domain. if you get error message, check the CORS config on the server side.
How about the SQuirreL SQL Client? As mentioned in another SO question, this programs has the capability to generate a simple ER diagram.
The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.
Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:
double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer
Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.
Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.
In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis
int a = fork();
Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.
The child getting 0 returned, and the parent getting the new pid.
Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.
At each fork
, only one value is modified - the return value from fork
.
Since Android version 4.4, you can't enable/disable gps programatically. If you try the code proposed on this answer, an exception will be fired.
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE
The equivalent is:
python3 -m http.server
I got the error by having multiple tables on the page and trying to initialize them all at once like this:
$('table').DataTable();
After a lot of trial and error, I initialized them separately and the error went away:
$("#table1-id").DataTable();
$("#table2-id").DataTable();
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
I have found this Multi-Device Hybrid Apps for Visual Studio Documentation for CTP1.1 Last updated: May 29, 2014 .
Some of the content from the documentation as follows.
This release supports building apps for the following device targets:
Android 4+ (4.4 providing the optimal developer experience) iOS 6 & 7 Windows 8.0 (Store) Windows Phone 8.0
Requirements: Windows 8.1
Visual Studio 2013 Update 2 - Professional, Ultimate, or Premium with the following optional features installed:
Tools for Maintaining Store apps for Windows 8 Windows Phone 8.0 SDK
Additional system requirements vary by device platform:
The Android emulator works best with PCs capable of installing the Intel HAXM driver
Windows Phone 8 requires a Hyper-V capable PC to run the emulator Building for iOS and using the iOS Simulator requires a Mac capable of running Xcode 5.1
Third Party Dependencies :
Joyent Node.js – Enables Visual Studio to integrate with the Apache Cordova Command Line Interface (CLI) and Apache Ripple™ Emulator Git CLI – Required only if you need to manually add git URIs for plugins
Google Chrome – Required to run the Apache Ripple emulator for iOS and Android
Apache Ant 1.8.0+ – Required as a dependency for the Android build process
Oracle Java JDK 7 – Required as a dependency for the Android build process
Android SDK – Required as a dependency for the Android build process and Ripple
SQLLite for Windows Runtime – required to add SQL connectivity to Windows apps (for the WebSQL Polyfill plugin)
Apple iTunes – Required for deploying an app to an iOS device connected to your Windows PC
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
Have you tried using the DataTable.Select(filterExpression, sortExpression) method?
inside your function toggleTable
when you do this line
document.getElementById("loginLink").onclick = toggleTable(....
you are actually calling the function again. so toggleTable
gets called again, and again and again, you're falling in an infinite recursive call.
make it simple.
function toggleTable()
{
var elem=document.getElementById("loginTable");
var hide = elem.style.display =="none";
if (hide) {
elem.style.display="table";
}
else {
elem.style.display="none";
}
}
see this fiddle
Alternatively to information_schema
it is possible to use pg_tables
:
select * from pg_tables where schemaname='public';
Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.
Then you can use Process.StandardOutput to read the program output.
The second link has a sample code how to do it.
We can handle the rejection at the individual promises level, so when we get the results in our result array, the array index which has been rejected will be undefined
. We can handle that situation as needed, and use the remaining results.
Here I have rejected the first promise, so it comes as undefined, but we can use the result of the second promise, which is at index 1.
const manyPromises = Promise.all([func1(), func2()]).then(result => {_x000D_
console.log(result[0]); // undefined_x000D_
console.log(result[1]); // func2_x000D_
});_x000D_
_x000D_
function func1() {_x000D_
return new Promise( (res, rej) => rej('func1')).catch(err => {_x000D_
console.log('error handled', err);_x000D_
});_x000D_
}_x000D_
_x000D_
function func2() {_x000D_
return new Promise( (res, rej) => setTimeout(() => res('func2'), 500) );_x000D_
}
_x000D_
I answered this question in another post:
How to get list of changed files since last build in Jenkins/Hudson
#!/bin/bash
set -e
job_name="whatever"
JOB_URL="http://myserver:8080/job/${job_name}/"
FILTER_PATH="path/to/folder/to/monitor"
python_func="import json, sys
obj = json.loads(sys.stdin.read())
ch_list = obj['changeSet']['items']
_list = [ j['affectedPaths'] for j in ch_list ]
for outer in _list:
for inner in outer:
print inner
"
_affected_files=`curl --silent ${JOB_URL}${BUILD_NUMBER}'/api/json' | python -c "$python_func"`
if [ -z "`echo \"$_affected_files\" | grep \"${FILTER_PATH}\"`" ]; then
echo "[INFO] no changes detected in ${FILTER_PATH}"
exit 0
else
echo "[INFO] changed files detected: "
for a_file in `echo "$_affected_files" | grep "${FILTER_PATH}"`; do
echo " $a_file"
done;
fi;
You can add the check directly to the top of the job's exec shell, and it will exit 0
if no changes are detected... Hence, you can always poll the top level for check-in's to trigger a build.
You can do this easily by using the library cryptocode
. Here is how you install:
pip install cryptocode
Encrypting a message (example code):
import cryptocode
encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")
Documentation can be found here
I rewrote David's answer using the with
statement, it allows you do do this:
with timeout(seconds=3):
time.sleep(4)
Which will raise a TimeoutError.
The code is still using signal
and thus UNIX only:
import signal
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
You can use this template for every file type:
ValidationExpression="^.+\.(([pP][dD][fF])|([jJ][pP][gG])|([pP][nN][gG])))$"
for ex: you can add ([rR][aA][rR]
) for Rar file type and etc ...
strtolower
is lacking in several of the proposed solutions, RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. The whole thing, not just the value part.
So suggestions like only parsing HTTP_ entries are wrong.
Better would be like this:
if (!function_exists('getallheaders')) {
foreach ($_SERVER as $name => $value) {
/* RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. */
if (strtolower(substr($name, 0, 5)) == 'http_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
$this->request_headers = $headers;
} else {
$this->request_headers = getallheaders();
}
Notice the subtle differences with previous suggestions. The function here also works on php-fpm (+nginx).
I've ran into the same issue and these two links solved for me:
The first one is this one: How do I retrieve the logged in Google account on android phones?
Which presents the code for retrieving the accounts associated with the phone. Basically you will need something like this:
AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
And to add the permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"></uses-permission>
Additionally, if you are using the Emulator the following link will help you to set it up with an account : Android Emulator - Trouble creating user accounts
Basically, it says that you must create an android device based on a API Level and not the SDK Version (like is usually done).
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
Here is a recursive solution:
def clear_folder(dir):
if os.path.exists(dir):
for the_file in os.listdir(dir):
file_path = os.path.join(dir, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
else:
clear_folder(file_path)
os.rmdir(file_path)
except Exception as e:
print(e)
Adding strings concatenates them:
> "1" + "1"
"11"
You have to parse them into numbers first:
/* parseFloat is used here.
* Because of it's not known that
* whether the number has fractional places.
*/
var a = parseFloat($('#a').val()),
b = parseFloat($('#b').val());
Also, you have to get the values from inside of the click handler:
$("submit").on("click", function() {
var a = parseInt($('#a').val(), 10),
b = parseInt($('#b').val(), 10);
});
Otherwise, you're using the values of the textboxes from when the page loads.
Requirements to fix this issue:
Image Format: 32-bit PNG (with alpha)
Image should be Transparent
Transparency Color Index: White (FFFFFF)
Source: http://gr1350.blogspot.com/2017/01/problem-with-setsmallicon.html
RecyclerView
is designed to be extensible, so there is no need to subclass the LayoutManager
(as droidev suggested) just to perform the scrolling.
Instead, just create a SmoothScroller
with the preference SNAP_TO_START
:
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
Now you set the position where you want to scroll to:
smoothScroller.setTargetPosition(position);
and pass that SmoothScroller to the LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
Try this:
<%= f.select :project_id, @project_select, :selected => f.object.project_id %>
This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
$pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
if ($status==0) {
$status = "alive";
} else {
$status = "dead";
}
$message .= '<div id="dialog-block-left">';
$message .= '<div id="ip-status">The IP address, '.$ip.', is '.$status.'</div><div style="clear:both"></div>';
return $message;
}
// Some IP Address
pingAddress("192.168.1.1");
This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/ Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }
Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
To add to the others, var_export might be handy too:
$email_text = var_export($_POST, true);
Recently i had the same problem (Compiling OpenCV with CMake and Qt/MinGW on WIN764)
And I think I solve this including on my environment variable PATH (through Control Panel\All Control Panel Items\System\Advanced Sytem Settings
) with the %MINGW_DIR%\bin and %CMAKE_DIR%/bin
Furthermore, I installed cmake2.8 on an easy directory (without blanks on it)
Add timeout of your SqlCommand
. Please note time is in second.
// Setting command timeout to 1 second
scGetruntotals.CommandTimeout = 1;
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
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);
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
Hope this will help someone in the future too. Source here.
int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();
These functions will return int values in hours and minutes.
If you're using the variable result:
result = result == "true";
The answer already been accepted, I just write a short technique for the same purpose.
var fieldPair = '';
$(":input").each(function(){
fieldPair += $(this).attr("name") + ':' + $(this).val() + ';';
});
console.log(fieldPair);
Using
<a href="foo.html"><div class="xyz"></div></a>
works in browsers, even though it violates current HTML specifications. It is permitted according to HTML5 drafts.
When you say that it does not work, you should explain exactly what you did (including jsfiddle code is a good idea), what you expected, and how the behavior different from your expectations.
It is unclear what you mean by “all the content in that div is in the css”, but I suppose it means that the content is really empty in HTML markup and you have CSS like
.xyz:before { content: "Hello world"; }
The entire block is then clickable, with the content text looking like link text there. Isn’t this what you expected?
There are several different ways you can handle this. You could add a RequiredFieldValidator as well as a RangeValidator (if that works for your case) or you could add a CustomFieldValidator.
Link to the CustomFieldValidator: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator%28VS.71%29.aspx
Link to MSDN Article on ASP.NET Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I also tried to make an executable jar file that I could run with the following command:
java -jar <jarfile>
After some searching I found the following link:
Packaging and Deploying Desktop Java Applications
I set the project's main class:
Then in the fodler dist the newly created jar should be executable with the command I mentioned above.
np.convolve
needs a flattened array as one of it's inputs, you can use numpy.ndarray.flatten()
which is quite fast, find it here.
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.
I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it
Edit: I just did a quick test with this:
<a href="test.html" style="{color: blue; background: white}
:visited {color: green}
:hover {background: yellow}
:visited:hover {color: purple}">Test</a>
And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
The command set-executionpolicy unrestricted
will allow any script you create to run as the logged in user. Just be sure to set the executionpolicy setting back to signed using the set-executionpolicy signed
command prior to logging out.
Set This in OkHttpClient.Builder() Object
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
This post has a method to achieve this
from (zvrba) You can do it by redirecting the output to a file first. For example:
echo zz > bla.txt
set /p VV=<bla.txt
echo %VV%
All the previous answers are correct. Following is the little deep dive into the problem and solution.
The driver constructor in Selenium for example
WebDriver driver = new ChromeDriver();
searches for the driver executable, in this case the Google Chrome driver searches for a Chrome driver executable. In case the service is unable to find the executable, the exception is thrown.
This is where the exception comes from (note the check state method)
/**
*
* @param exeName Name of the executable file to look for in PATH
* @param exeProperty Name of a system property that specifies the path to the executable file
* @param exeDocs The link to the driver documentation page
* @param exeDownload The link to the driver download page
*
* @return The driver executable as a {@link File} object
* @throws IllegalStateException If the executable not found or cannot be executed
*/
protected static File findExecutable(
String exeName,
String exeProperty,
String exeDocs,
String exeDownload) {
String defaultPath = new ExecutableFinder().find(exeName);
String exePath = System.getProperty(exeProperty, defaultPath);
checkState(exePath != null,
"The path to the driver executable must be set by the %s system property;"
+ " for more information, see %s. "
+ "The latest version can be downloaded from %s",
exeProperty, exeDocs, exeDownload);
File exe = new File(exePath);
checkExecutable(exe);
return exe;
}
The following is the check state method which throws the exception:
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*/
public static void checkState(
boolean b,
@Nullable String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (!b) {
throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
}
}
SOLUTION: set the system property before creating driver object as follows.
System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
The following is the code snippet (for Chrome and Firefox) where the driver service searches for the driver executable:
Chrome:
@Override
protected File findDefaultExecutable() {
return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
"https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
"http://chromedriver.storage.googleapis.com/index.html");
}
Firefox:
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
where CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver" and GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"
Similar is the case for other browsers, and the following is the snapshot of the list of the available browser implementation:
(as per http://java.sun.com/...ex/Pattern.html)
The backslash character ('\
') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\
matches a single backslash and { matches a left brace.
Other examples of usage :
\\ The backslash character<br>
\t The tab character ('\u0009')<br>
\n The newline (line feed) character ('\u000A')<br>
\r The carriage-return character ('\u000D')<br>
\f The form-feed character ('\u000C')<br>
\a The alert (bell) character ('\u0007')<br>
\e The escape character ('\u001B')<br>
\cx The control character corresponding to x <br>
List installed dependencies:
composer show -i
composer show -i -t
-i
short for --installed
.
-t
short for --tree
.
I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"
-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2
If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.
Regards.
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
Just Keep pressing ESC
key. It will stop the VBA. This methods works when you get infinite MsgBox
s
I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.
One easy way to map that country name that you have to an int
to be used in the setImageResource
method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
You may obtain the stream key via the API: https://github.com/justintv/twitch-api
You can use display: flex to position an element to the bottom, but I do not think you want to use flex in this case, as it will affect all of your elements.
To position an element to the bottom using flex try this:
.container {
display: flex;
}
.button {
align-self: flex-end;
}
Your best bet is to set position: absolute to the button and set it to bottom: 0
, or you can place the button outside the container and use negative transform: translateY(-100%)
to bring it in the container like this:
.content {
height: 400px;
background: #000;
color: #fff;
}
.button {
transform: translateY(-100%);
display: inline-block;
}
Check this JSFiddle
div {
display: flex;
justify-content: space-between;
}
_x000D_
<div>
<p>Item one</p>
<a>Item two</a>
</div>
_x000D_
You can run below commands. I believe this is what you want!
Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)
./catalina.sh run
You can use too
style="overflow-y: scroll; height:150px; width: auto;"
It's works for me
You could just use
DataGridView1.CurrentRow.Cells["ColumnName"].Value
If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.
sys.argv
to get the command-line parametersopen()
, read()
to manipulate fileUse:
git clean -df
It's not well advertised, but git clean
is really handy. Git Ready has a nice introduction to git clean
.
There are two problems with this question:
Assuming you have a gray scale bitmap, you have two factors to consider:
Answer those questions, and then you might be able to find your original answer.
I always use docker rmi $(docker ps -a -q)
to remove all images.
You can remove directory /var/lib/docker/graph
when docker rmi
failed.
You can using option --data with file.
Write xml content to a file named is soap_get.xml and using curl command to send request:
curl -X POST --header "Content-Type:text/xml;charset=UTF-8" --data @soap_get.xml your_url
Note: I will elaborate more my answer for Python 3 since the end of life of Python 2 is very close.
In Python 3
bytes
consists of sequences of 8-bit unsigned values, while str
consists of sequences of Unicode code points that represent textual characters from human languages.
>>> # bytes
>>> b = b'h\x65llo'
>>> type(b)
<class 'bytes'>
>>> list(b)
[104, 101, 108, 108, 111]
>>> print(b)
b'hello'
>>>
>>> # str
>>> s = 'nai\u0308ve'
>>> type(s)
<class 'str'>
>>> list(s)
['n', 'a', 'i', '¨', 'v', 'e']
>>> print(s)
nai¨ve
Even though bytes
and str
seem to work the same way, their instances are not compatible with each other, i.e, bytes
and str
instances can't be used together with operators like >
and +
. In addition, keep in mind that comparing bytes
and str
instances for equality, i.e. using ==
, will always evaluate to False
even when they contain exactly the same characters.
>>> # concatenation
>>> b'hi' + b'bye' # this is possible
b'hibye'
>>> 'hi' + 'bye' # this is also possible
'hibye'
>>> b'hi' + 'bye' # this will fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
>>> 'hi' + b'bye' # this will also fail
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "bytes") to str
>>>
>>> # comparison
>>> b'red' > b'blue' # this is possible
True
>>> 'red'> 'blue' # this is also possible
True
>>> b'red' > 'blue' # you can't compare bytes with str
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'bytes' and 'str'
>>> 'red' > b'blue' # you can't compare str with bytes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'bytes'
>>> b'blue' == 'red' # equality between str and bytes always evaluates to False
False
>>> b'blue' == 'blue' # equality between str and bytes always evaluates to False
False
Another issue when dealing with bytes
and str
is present when working with files that are returned using the open
built-in function. On one hand, if you want ot read or write binary data to/from a file, always open the file using a binary mode like 'rb' or 'wb'. On the other hand, if you want to read or write Unicode data to/from a file, be aware of the default encoding of your computer, so if necessary pass the encoding
parameter to avoid surprises.
In Python 2
str
consists of sequences of 8-bit values, while unicode
consists of sequences of Unicode characters. One thing to keep in mind is that str
and unicode
can be used together with operators if str
only consists of 7-bit ASCI characters.
It might be useful to use helper functions to convert between str
and unicode
in Python 2, and between bytes
and str
in Python 3.
As mentioned before, you cannot create free certificates for S3 buckets. However, you can create Cloud Front distribution and then assign the certificate for the Cloud Front instead. You request the certificate for your domain and then just assign it to the Cloud Front distribution in the Cloud Front settings. I've used this method to serve static websites via SSL as well as serve static files.
For static website creation Amazon is the go to place. It is really affordable to get a static website with SSL.
this works for me
String body = json.encode(data);
http.Response response = await http.post(
url: 'https://example.com',
headers: {"Content-Type": "application/json"},
body: body,
);
In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]
I had same problem, but I think I have simple solution(code is from my RoR app): Extract industry ids from yahoo.finance.sectors and add it to db:
select = "select * from yahoo.finance.sectors"
generate_query select
@data.each do |data|
data["industry"].each do |ind|
unless ind.kind_of?(Array)
unless ind["id"].nil?
id = ind["id"].to_i
if id > 0
Industry.where(id: id).first_or_create(name: ind["name"]).update_attribute(:name, ind["name"])
end
end
end
end
end
Extract all comanies with their symbols with industry ids:
ids = Industry.all.map{|ind| "'#{ind.id.to_s}'" }.join(",")
select = "select * from yahoo.finance.industry where id in"
generate_query select, ids
@data.each do |ts|
unless ts.kind_of?(Array) || ts["company"].nil?
if ts["company"].count == 2 && ts["company"].first[0] == "name"
t = ts["company"]
Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
else
ts["company"].each do |t|
Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
end
end
end
end
end
Connection hellper:
def generate_query(select, ids = nil)
if params[:form] || params[:action] == "sectors" || params[:controller] == "tickets"
if params[:action] == "sectors" || params[:controller] == "tickets"
if ids.nil?
query= select
else
query= "#{select} (#{ids})"
end
else
if params[:form][:ids]
@conditions = params_parse params[:form][:ids]
query = "#{select} (#{@conditions})"
end
end
yql_execut(query)
end
end
def yql_execut(query)
# TODO: OAuth ACCESS (http://developer.yahoo.com/yql/guide/authorization.html)
base_url = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="
dirty_data = JSON.parse(HTTParty.get(base_url + URI.encode(query)).body)
if dirty_data["query"]["results"] == nil
@data, @count, @table_head = nil
else
@data = dirty_data["query"]["results"].to_a[0][1].to_a
@count = dirty_data["query"]["count"]
if @count == 1
@table_head = @data.map{|h| h[0].capitalize}
else
@table_head = @data.to_a.first.to_a.map{|h| h[0].capitalize}
end
end
end
Sorry for mess, but this is first testing version for my project and I needed it very fast. There are some helpers variabels and other things for my app, sorry for it. But I have question: Have many symbols do you have? I have 5500.
I also face the same problem. do the simple steps
Also you can only set mediaPlayer.reset()
and in onDestroy
set it to release.
SOLVED
A simple way can be:
import os
current_dir = os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir
Use the following code:
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "Hello, errors!" );
Then watch the file:
tail -f /tmp/php-error.log
Or update php.ini
as described in this blog entry from 2008.
In case other readers look for information on the adduser
command.
Edit /etc/adduser.conf
Set DHOME
variable
This doesn't remove whitespace automatically before a commit, but it is pretty easy to effect. I put the following perl script in a file named git-wsf (git whitespace fix) in a dir in $PATH so I can:
git wsf | sh
and it removes all whitespace only from lines of files that git reports as a diff.
#! /bin/sh
git diff --check | perl -x $0
exit
#! /usr/bin/perl
use strict;
my %stuff;
while (<>) {
if (/trailing whitespace./) {
my ($file,$line) = split(/:/);
push @{$stuff{$file}},$line;
}
}
while (my ($file, $line) = each %stuff) {
printf "ex %s <<EOT\n", $file;
for (@$line) {
printf '%ds/ *$//'."\n", $_;
}
print "wq\nEOT\n";
}
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
Use the getTime
method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
At this point method
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();
is deprecated.
You should use
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
and getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
How about just multiplying by one like this?
var x = 1.234000*1; // becomes 1.234
var y = 1.234001*1; // stays as 1.234001
CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved"
and you define how it looks when it doesn't have the class "saved"
(it's normal look). When you remove the class "saved"
, it will transition to the other state according to the transition settings in place for the object without the "saved"
class.
If the CSS transition settings apply to the object (without the "saved"
class), then they will apply to both transitions.
We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.
My guess from looking at your HTML is that your transition CSS settings only apply to .saved
and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade"
that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.
Same way as @loonis suggested to use TransactionTemplate one may use this helper component (Kotlin):
@Component
class TransactionalUtils {
/**
* Execute any [block] of code (even private methods)
* as if it was effectively [Transactional]
*/
@Transactional
fun <R> executeAsTransactional(block: () -> R): R {
return block()
}
}
Usage:
@Service
class SomeService(private val transactionalUtils: TransactionalUtils) {
fun foo() {
transactionalUtils.executeAsTransactional { transactionalFoo() }
}
private fun transactionalFoo() {
println("This method is executed within transaction")
}
}
Don't know whether TransactionTemplate
reuse existing transaction or not but this code definitely do.
Using flexbox
#parent_div_1{
display:flex;
flex-wrap: wrap;
}
Device Sizes and class prefix:
.col-xs-
.col-sm-
.col-md-
.col-lg-
Grid options:
Reference: Grid System
i think this add new property in desired type without having to set a primitive value, like when property defined in class definition
var x = new ExpandoObject();
x.NewProp = default(string)
I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}
An example of how you might use this:
var test = JoinDataTables(transactionInfo, transactionItems,
(row1, row2) =>
row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));
One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.
Firefox 3 will display %20
s in URLs as spaces in the address bar.
CREATE ROLE blog WITH
LOGIN
SUPERUSER
INHERIT
CREATEDB
CREATEROLE
REPLICATION;
COMMENT ON ROLE blog IS 'Test';