GPL-compiled ffmpeg can be used from non-GPL program (commercial project) only if it is invoked in the separate process as command line utility; all wrappers that are linked with ffmpeg library (including Microsoft's FFMpegInterop) can use only LGPL build of ffmpeg.
You may try my .NET wrapper for FFMpeg: Video Converter for .NET (I'm an author of this library). It embeds FFMpeg.exe into the DLL for easy deployment and doesn't break GPL rules (FFMpeg is NOT linked and wrapper invokes it in the separate process with System.Diagnostics.Process).
The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:
var someString = @"The
quick
brown
fox...";
Yuck.
So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:
var someString = String.Join(
Environment.NewLine,
"The",
"quick",
"brown",
"fox...");
And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine
for " "
.
public static long GetDirSize(string path)
{
try
{
return Directory.EnumerateFiles(path).Sum(x => new FileInfo(x).Length)
+
Directory.EnumerateDirectories(path).Sum(x => GetDirSize(x));
}
catch
{
return 0L;
}
}
If you only want to ssh a few times, such as on a borrowed or shared computer, try:
ssh buck@hostname
or
ssh -l buck hostname
! pip install --user <package>
The !
tells the notebook to execute the cell as a shell command.
Although making a different layout for different screen sizes is theoretically a good idea, it can get very difficult to accommodate for all screen dimensions, and pixel densities. Having over 20+ different dimens.xml
files as suggested in the above answers, is not easy to manage at all.
How To Use:
To use sdp
:
implementation 'com.intuit.sdp:sdp-android:1.0.5'
in your build.gradle
,Replace any dp
value such as 50dp
with a @dimen/50_sdp
like so:
<TextView
android:layout_width="@dimen/_50sdp"
android:layout_height="@dimen/_50sdp"
android:text="Hello World!" />
How It Works:
sdp
scales with the screen size because it is essentially a huge list of different dimens.xml
for every possible dp
value.
See It In Action:
Here it is on three devices with widely differing screen dimensions, and densities:
Note that the sdp
size unit calculation includes some approximation due to some performance and usability constraints.
I usually use the following to to quickly create a small table from dicts.
Let's say you have a dict where the keys are filenames and the values their corresponding filesizes, you could use the following code to put it into a DataFrame (notice the .items() call on the dict):
files = {'A.txt':12, 'B.txt':34, 'C.txt':56, 'D.txt':78}
filesFrame = pd.DataFrame(files.items(), columns=['filename','size'])
print(filesFrame)
filename size
0 A.txt 12
1 B.txt 34
2 C.txt 56
3 D.txt 78
if you use Sql Server
delete from Table where id between 79 and 296
After your edit : you now clarified that you want :
ID (>79 AND < 296)
So use this :
delete from Table where id > 79 and id < 296
The simplest way to get the substrings array from the given array is to use filter and includes:
myArray.filter(element => element.includes("substring"));
The above one will return an array of substrings.
myArray.find(element => element.includes("substring"));
The above one will return the first result element from the array.
myArray.findIndex(element => element.includes("substring"));
The above one will return the index of the first result element from the array.
So I did with
sudo usermod -a -G dialout <my-username>
.
You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.
This will give you the second row of each group (zero indexed, nth(0) is the same as first()):
df.groupby('id').nth(1)
Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
The complete code with version checking.
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// do stuff for iOS 7 and newer
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}
else {
// do stuff for older versions than iOS 7
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
The easiest way to get the correct number of hours between two dates (datetimes), even across daylight saving time changes, is to use the difference in Unix timestamps. Unix timestamps are seconds elapsed since 1970-01-01T00:00:00 UTC, ignoring leap seconds (this is OK because you probably don't need this precision, and because it's quite difficult to take leap seconds into account).
The most flexible way to convert a datetime string with optional timezone information into a Unix timestamp is to construct a DateTime object (optionally with a DateTimeZone as a second argument in the constructor), and then call its getTimestamp method.
$str1 = '2006-04-12 12:30:00';
$str2 = '2006-04-14 11:30:00';
$tz1 = new DateTimeZone('Pacific/Apia');
$tz2 = $tz1;
$d1 = new DateTime($str1, $tz1); // tz is optional,
$d2 = new DateTime($str2, $tz2); // and ignored if str contains tz offset
$delta_h = ($d2->getTimestamp() - $d1->getTimestamp()) / 3600;
if ($rounded_result) {
$delta_h = round ($delta_h);
} else if ($truncated_result) {
$delta_h = intval($delta_h);
}
echo "?h: $delta_h\n";
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
Use:
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
And you can get the version code by using this
int verCode = pInfo.versionCode;
To change width is not that hard. Just remove the width
attribute from the tag and add width: 100%;
in the css for #canvas
#canvas{
border: solid 1px blue;
width: 100%;
}
Changing height is a bit harder: you need javascript. I have used jQuery because i'm more comfortable with.
you need to remove the height
attribute from the canvas tag and add this script:
<script>
function resize(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top- Math.abs($("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
}
$(document).ready(function(){
resize();
$(window).on("resize", function(){
resize();
});
});
</script>
You can see this fiddle: https://jsfiddle.net/1a11p3ng/3/
EDIT:
To answer your second question. You need javascript
0) First of all i changed your #border id into a class since ids must be unique for an element inside an html page (you can't have 2 tags with the same id)
.border{
border: solid 1px black;
}
#canvas{
border: solid 1px blue;
width: 100%;
}
1) Changed your HTML to add ids where needed, two inputs and a button to set the values
<div class="row">
<div class="col-xs-2 col-sm-2 border">content left</div>
<div class="col-xs-6 col-sm-6 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas"></canvas>
</div>
<div class="col-xs-2 col-sm-2 border">content right</div>
</div>
2) Set the canvas height and width so that it fits inside the container
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
3) Set the values of the width and height forms
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
4) Finally, whenever you click on the button you set the canvas width and height to the values set. If the width value is bigger than the container's width then it will resize the canvas to the container's width instead (otherwise it will break your layout)
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#canvas").outerWidth(Math.min($("#w-input").val(), $("#main-content").width()));
});
See a full example here https://jsfiddle.net/1a11p3ng/7/
UPDATE 2:
To have full control over the width you can use this:
<div class="container-fluid">
<div class="row">
<div class="col-xs-2 border">content left</div>
<div class="col-xs-8 border" id="main-content">
<div class="row">
<div class="col-xs-6">
Width <input id="w-input" type="number" class="form-control">
</div>
<div class="col-xs-6">
Height <input id="h-input" type="number" class="form-control">
</div>
<div class="col-xs-12 text-right" style="padding: 3px;">
<button id="set-size" class="btn btn-primary">Set</button>
</div>
</div>
canvas
<canvas id="canvas">
</canvas>
</div>
<div class="col-xs-2 border">content right</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
$("#h-input").val($("#canvas").outerHeight());
$("#w-input").val($("#canvas").outerWidth());
$("#set-size").click(function(){
$("#canvas").outerHeight($("#h-input").val());
$("#main-content").width($("#w-input").val());
$("#canvas").outerWidth($("#main-content").width());
});
});
</script>
https://jsfiddle.net/1a11p3ng/8/
the content left and content right columns will move above and belove the central div if the width is too high, but this can't be helped if you are using bootstrap. This is not, however, what responsive means. a truly responsive site will adapt its size to the user screen to keep the layout as you have intended without any external input, letting the user set any size which may break your layout does not mean making a responsive site.
The __init__.py
file makes Python treat directories containing it as modules.
Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it
--Version 2
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s
on p.ProductID = s.ProdctId
Make sure you don't have any syntax errors in your Dockerfile as this can cause this error as well. A correct example is:
RUN apt-get update \
&& apt-get -y install curl \
another-package
It was a combination of fixing a syntax error and adding apt-get update
that solved the problem for me.
line-height
is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px
to your ul.catBlock li
and it will be fine.
In this case you may have to add it to ul.catBlock li a
instead since all of the text inside the li
is also inside of an a
. I have seen some weird things happen when you do this, so try both and see which one works.
BreedId
in the Dog
table is obviously a foreign key to the corresponding row in the Breed
table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable<Dog>
, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):
public IEnumerable<Dog> GetDogs()
{
using (var db = new DogDataContext(ConnectString))
{
db.LoadOptions.LoadWith<Dog>(i => i.Breed);
return db.Dogs.ToArray();
}
}
It is then trivial to access the breed for each dog:
foreach (var dog in GetDogs())
{
Console.WriteLine("Dog's Name: {0}", dog.Name);
Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);
}
I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:
Using the enumerator method to match on sub-indices in a list of tuples. e.g.
li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]
# want pos of item having [22,44] in positions 1 and 3:
def getIndexOfTupleWithIndices(li, indices, vals):
# if index is a tuple of subindices to match against:
for pos,k in enumerate(li):
match = True
for i in indices:
if k[i] != vals[i]:
match = False
break;
if (match):
return pos
# Matches behavior of list.index
raise ValueError("list.index(x): x not in list")
idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals) # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals) # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals) # = 4
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount()==0) {
onResume();
}
}
});
Saty described the differences between them. For your practice, you can use datetime
in order to keep the output of NOW()
.
For example:
CREATE TABLE Orders
(
OrderId int NOT NULL,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (OrderId)
)
You can read more at w3schools.
For passing multiple parameters you can cast the string by concatenating it with the ASCII value. Like, for single quotes we can use '
:
var str = "'" + str + "'";
The same parameter you can pass to the onclick()
event. In most of the cases it works with every browser.
Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....
.select2-dropdown.select2-dropdown--below{
width: 148px !important;
}
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
In my case the file .git/HEAD was corrupted (contained only dots). So I edited it and replaced its content with:
ref: refs/heads/master
and it started working again.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
Extension for @Kleist answer:
Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB)
and file(GLOB_RECURSE)
. With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.
However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.
Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB)
or file(GLOB_RECURSE)
for collect the sources.
You Need to take same height and width
and simply use the border-radius:360px;
One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.
In [28]: im = Image.new(mode='RGB',size=(240,240))
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10))
In [35]: draw.textsize(t1, font), draw.textsize(t2, font) # handles multi-lined text
Out[35]: ((52, 10), (27, 24))
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
Completing the answer from @xanblax
private static string getUserName()
{
SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (System.Management.ManagementObject Process in searcher.Get())
{
if (Process["ExecutablePath"] != null &&
string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
return OwnerInfo[0];
}
}
}
return "";
}
Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be:
class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
You can use it like this:
root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"
If you need an arbitrary number of children per node, then use a list of children:
class Tree:
def __init__(self, data):
self.children = []
self.data = data
left = Tree("left")
middle = Tree("middle")
right = Tree("right")
root = Tree("root")
root.children = [left, middle, right]
You need to:
EditText in the xml file
EditText
in the activityEditText
If you are using SQL Server (starting with 2008), choose one of this:
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
Update 2nd table data in 1st table need to Inner join before SET :
`UPDATE `table1` INNER JOIN `table2` ON `table2`.`id`=`table1`.`id` SET `table1`.`name`=`table2`.`name`, `table1`.`template`=`table2`.`template`;
Wrap the content in a <pre>
(pre-formatted text) tag
<pre>hello ,
my name is x.</pre>
The following code works very good for me:
num.toString().match(/.\*\\..{0,2}|.\*/)[0];
You should check that what you are passing to foreach
is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This is not supported by Angular CLI and they are in no mood to include it any time soon.
Here is the link to the actual created issue - https://github.com/angular/angular-cli/issues/1776
Had similar problem. To resolve it, updated from svn trunk with option of priority of local files.
svn update path/ --accept=mine-full
After You could commit as usual. Of course, be careful using it.
A post back is anything that cause the page from the client's web browser to be pushed back to the server.
There's alot of info out there, search google for postbacks.
Most of the time, any ASP control will cause a post back (button/link click) but some don't unless you tell them to (checkbox/combobox)
# mutate/remove with a default
ret_val = body.pop('key', 5)
# no mutation with a default
ret_val = body.get('key', 5)
In case someone wants to get the data frame in a "long format" (leaf values have the same type) without multiindex, you can do this:
pd.DataFrame.from_records(
[
(level1, level2, level3, leaf)
for level1, level2_dict in user_dict.items()
for level2, level3_dict in level2_dict.items()
for level3, leaf in level3_dict.items()
],
columns=['UserId', 'Category', 'Attribute', 'value']
)
UserId Category Attribute value
0 12 Category 1 att_1 1
1 12 Category 1 att_2 whatever
2 12 Category 2 att_1 23
3 12 Category 2 att_2 another
4 15 Category 1 att_1 10
5 15 Category 1 att_2 foo
6 15 Category 2 att_1 30
7 15 Category 2 att_2 bar
(I know the original question probably wants (I.) to have Levels 1 and 2 as multiindex and Level 3 as columns and (II.) asks about other ways than iteration over values in the dict. But I hope this answer is still relevant and useful (I.): to people like me who have tried to find a way to get the nested dict into this shape and google only returns this question and (II.): because other answers involve some iteration as well and I find this approach flexible and easy to read; not sure about performance, though.)
Just make sure it is executable, using chmod +x
. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh
- or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh
, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh
.
You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:
alias script.sh='sh script.sh'
Which would allow you to use just simply script.sh
(literally - this won't work for any other *.sh
file) instead of sh script.sh
.
As @AlexanderN pointed out, you can now delete App IDs.
I know an answer has been ticked already, but for future reference, you could always use the device screen size to figure out which device it is like so:
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
CGSize result = [[UIScreen mainScreen] bounds].size;
if (result.height == 480) {
// 3.5 inch display - iPhone 4S and below
NSLog(@"Device is an iPhone 4S or below");
}
else if (result.height == 568) {
// 4 inch display - iPhone 5
NSLog(@"Device is an iPhone 5/S/C");
}
else if (result.height == 667) {
// 4.7 inch display - iPhone 6
NSLog(@"Device is an iPhone 6");
}
else if (result.height == 736) {
// 5.5 inch display - iPhone 6 Plus
NSLog(@"Device is an iPhone 6 Plus");
}
}
else if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
// iPad 9.7 or 7.9 inch display.
NSLog(@"Device is an iPad.");
}
At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.
You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.
This may be a bit controversial, but Gradle doesn't hide the fact that it's a fully-fledged programming language.
Ant + ant-contrib is essentially a turing complete programming language that no one really wants to program in.
Maven tries to take the opposite approach of trying to be completely declarative and forcing you to write and compile a plugin if you need logic. It also imposes a project model that is completely inflexible. Gradle combines the best of all these tools:
Gradle is the most configurable and flexible build tool I have yet to use. It requires some investment up front to learn the DSL and concepts like configurations but if you need a no-nonsense and completely configurable JVM build tool it's hard to beat.
In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.
More information can be found here
There is nothing built in afaik, but building it yourself should be easy. I would do as you suggest and use reflection to obtain the properties and use them to create the columns of the table. Then I would step through each item in the IEnumerable and create a row for each. The only caveat is if your collection contains items of several types (say Person and Animal) then they may not have the same properties. But if you need to check for it depends on your use.
Have a look at C++11 Features (Modern C++)
and section "Quick Reference Guide to Visual C++ Version Numbers" ...
Simply Update the Chrome browser to the latest version available.
1- run python manage.py makemigrations <appname>
2- run python manage.py sqlmigrate <appname> <migrationname>
- you will find migrationname in migration folder under appname (without '.py' extension of course)
3- copy all text of result # all sql commands that generated
4- go to your db ide and paste as new query and run it
now all changes are applied on your db
You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)
>>> for field, values in fields.iteritems():
... print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
Your problem was that you were looping over fields, which returns the keys of the dictionary.
>>> for field in fields:
... print field
...
first_names
last_name
A man-in-the-middle proxy, like suggested by other answers, is a good solution if you only want to see HTTP/HTTPS traffic. Burp Suite is pretty good. It may be a pain to configure though. I'm not sure how you would convince the simulator to talk to it. You might have to set the proxy on your local Mac to your instance of a proxy server in order for it to intercept, since the simulator will make use of your local Mac's environment.
The best solution for packet sniffing (though it only works for actual iOS devices, not the simulator) I've found is to use rvictl
. This blog post has a nice writeup. Basically you do:
rvictl -s <iphone-uid-from-xcode-organizer>
Then you sniff the interface it creates with with Wireshark (or your favorite tool), and when you're done shut down the interface with:
rvictl -x <iphone-uid-from-xcode-organizer>
This is nice because if you want to packet sniff the simulator, you're having to wade through traffic to your local Mac as well, but rvictl
creates a virtual interface that just shows you the traffic from the iOS device you've plugged into your USB port.
$("#pageCSS").attr('href', './css/new_css.css');
If you're using old Xcode and want to run onto devices with new version of iOS, then do this trick. This basically make a symbolic link from iOS Device Support in new Xcode to old Xcode
https://gist.github.com/steipete/d9b44d8e9f341e81414e86d7ff8fb62d
For Xcode 9.0 beta and iOS 11.0 beta (name your Xcode9.app
for Xcode 9 beta and Xcode.app
for Xcode 8)
sudo ln -s "/Applications/Xcode9.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\)" "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
This is now possible as of AngularJS 1.5.10, using ng-switch-when-separator
var app = angular.module("app", []); _x000D_
_x000D_
app.controller("ctrl", function($scope) {_x000D_
$scope.myDataSet = [{Name: 'Michelle', Gender: 'Female', DOB: '01/12/1986', Payment: [{Status: '0'}]},{Name: 'Steve', Gender: 'Male', DOB: '11/12/1982', Payment: [{Status: '1'}]},{Name: 'Dan', Gender: 'Male', DOB: '03/22/1976', Payment: [{Status: '2'}]},{Name: 'Doug', Gender: 'Male', DOB: '02/02/1980', Payment: [{Status: '3'}]},{Name: 'Mary', Gender: 'Female', DOB: '04/02/1976', Payment: [{Status: '4'}]},{Name: 'Cheyenne', Gender: 'Female', DOB: '07/10/1981', Payment: [{Status: '5'}]},{Name: 'Bob', Gender: 'Male', DOB: '02/16/1990', Payment: [{Status: '6'}]},{Name: 'Bad data', Gender: 'Blank', DOB: '01/01/1970', Payment: [{Status: '7'}]}];_x000D_
});
_x000D_
<script src="https://code.angularjs.org/1.5.10/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="ctrl">_x000D_
<div ng-repeat="details in myDataSet" ng-switch on="details.Payment[0].Status">_x000D_
_x000D_
<p>{{ details.Name }}</p>_x000D_
<p>{{ details.DOB }}</p>_x000D_
_x000D_
<div ng-switch-when="0">_x000D_
<p>No payment</p>_x000D_
</div>_x000D_
_x000D_
<div ng-switch-when="1|2" ng-switch-when-separator="|">_x000D_
<p>Late</p>_x000D_
</div>_x000D_
_x000D_
<div ng-switch-when="3|4|5" ng-switch-when-separator="|">_x000D_
<p>Some payment made</p>_x000D_
</div>_x000D_
_x000D_
<div ng-switch-when="6">_x000D_
<p>Late and further taken out</p>_x000D_
</div>_x000D_
_x000D_
<div ng-switch-default>_x000D_
<p>Error</p>_x000D_
</div>_x000D_
_x000D_
<p>{{ details.Gender}}</p>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.
# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12
(IN numRating_Chapter INT(11) UNSIGNED,
IN txtRating_Chapter VARCHAR(250),
IN chapterName VARCHAR(250),
IN addedBy VARCHAR(250)
)
BEGIN
DECLARE numRating_Chapter INT;
DECLARE txtRating_Chapter VARCHAR(250);
DECLARE chapterName1 VARCHAR(250);
DECLARE addedBy1 VARCHAR(250);
DECLARE chapterId INT;
DECLARE studentId INT;
SET chapterName1 = chapterName;
SET addedBy1 = addedBy;
SET chapterId = (SELECT chapterId
FROM chapters
WHERE chaptername = chapterName1);
SET studentId = (SELECT Id
FROM students
WHERE email = addedBy1);
SELECT chapterId;
SELECT studentId;
INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);
END //
//DELIMITER;
You could use the nth-child
pseudo-selector. For example:
table.align-right-3rd-column td:nth-child(3)
{
text-align: right;
}
Then in your table do:
<table class="align-right-3rd-column">
<tr>
<td></td><td></td><td></td>
...
</tr>
</table>
Edit:
Unfortunately, this only works in Firefox 3.5. However, if your table only has 3 columns, you could use the sibling selector, which has much better browser support. Here's what the style sheet would look like:
table.align-right-3rd-column td + td + td
{
text-align: right;
}
This will match any column preceded by two other columns.
NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:
[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];
In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__
. So if you don't define it in your class, you will get the one from the base.
Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__
, your class will inherit the first one only.
In such cases, you should really use super
if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).
If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super
):
class A:
def __init__(self):
print('A')
super().__init__()
class B:
def __init__(self):
print('B')
super().__init__()
class C(A, B):
pass
C()
#prints:
#A
#B
Notice how both base classes use super
even though they don't have their own base classes.
What super
does is: it calls the method from the next class in MRO (method resolution order). The MRO for C
is: (C, A, B, object)
. You can print C.__mro__
to see it.
So, C
inherits __init__
from A
and super
in A.__init__
calls B.__init__
(B
follows A
in MRO).
So by doing nothing in C
, you end up calling both, which is what you want.
Now if you were not using super
, you would end up inheriting A.__init__
(as before) but this time there's nothing that would call B.__init__
for you.
class A:
def __init__(self):
print('A')
class B:
def __init__(self):
print('B')
class C(A, B):
pass
C()
#prints:
#A
To fix that you have to define C.__init__
:
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
The problem with that is that in more complicated MI trees, __init__
methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.
I've sorted this out using the cb.createQuery() (without the result type parameter):
public class Blah() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery query = criteriaBuilder.createQuery();
Root<Entity> root;
Predicate whereClause;
EntityManager entityManager;
Class<Entity> domainClass;
... Methods to create where clause ...
public Blah(EntityManager entityManager, Class<Entity> domainClass) {
this.entityManager = entityManager;
this.domainClass = domainClass;
criteriaBuilder = entityManager.getCriteriaBuilder();
query = criteriaBuilder.createQuery();
whereClause = criteriaBuilder.equal(criteriaBuilder.literal(1), 1);
root = query.from(domainClass);
}
public CriteriaQuery<Entity> getQuery() {
query.select(root);
query.where(whereClause);
return query;
}
public CriteriaQuery<Long> getQueryForCount() {
query.select(criteriaBuilder.count(root));
query.where(whereClause);
return query;
}
public List<Entity> list() {
TypedQuery<Entity> q = this.entityManager.createQuery(this.getQuery());
return q.getResultList();
}
public Long count() {
TypedQuery<Long> q = this.entityManager.createQuery(this.getQueryForCount());
return q.getSingleResult();
}
}
Hope it helps :)
The solutions given here fail on either directories or symlinks (or both). On Linux, you can test files, directories and symlinks with:
if [[ -f "$file" && -x $(realpath "$file") ]]; then .... fi
On OS X, you should be able to install coreutils with homebrew and use grealpath
.
isexec
functionYou can define a function for convenience:
isexec() {
if [[ -f "$1" && -x $(realpath "$1") ]]; then
true;
else
false;
fi;
}
Or simply
isexec() { [[ -f "$1" && -x $(realpath "$1") ]]; }
Then you can test using:
if `isexec "$file"`; then ... fi
I think you could set the headers and still use getJSON() like this:
$.ajaxSetup({
headers : {
'Authorization' : 'Basic faskd52352rwfsdfs',
'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
}
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); });
One way to debug this (and to make sure it is the protocol violation that is causing the problem), is to use Fiddler (Http Web Proxy) and see if the same error occurs. If it doesn't (i.e. Fiddler handled the issue for you) then you should be able to fix it using the UseUnsafeHeaderParsing flag.
If you are looking for a way to set this value programatically see the examples here: http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/
By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?
The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:
this.dispose();
If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.
((1,2,3,4),
(5,6,7,8),
(9,0,1,2))
Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.
If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)
From Apple documentations:
The presenting view controller is responsible for dismissing the view controller it presented
Thus, it is a bad practise to just invoke the dismiss method from it self.
What you should do if you're presenting it modal is:
presentingViewController?.dismiss(animated: true, completion: nil)
In my case, static fields will not be injected.
I'm late to the party, but the following is the Regular Expression I use:
(?:,"|^")(""|[\w\W]*?)(?=",|"$)|(?:,(?!")|^(?!"))([^,]*?)(?=$|,)|(\r\n|\n)
This pattern has three capturing groups:
This pattern handles all of the following:
If you have are using a more capable flavor of regex with named groups and lookbehinds, I prefer the following:
(?<quoted>(?<=,"|^")(?:""|[\w\W]*?)*(?=",|"$))|(?<normal>(?<=,(?!")|^(?!"))[^,]*?(?=(?<!")$|(?<!"),))|(?<eol>\r\n|\n)
Edit
(?:^"|,")(""|[\w\W]*?)(?=",|"$)|(?:^(?!")|,(?!"))([^,]*?)(?=$|,)|(\r\n|\n)
This slightly modified pattern handles lines where the first column is empty as long as you are not using Javascript. For some reason Javascript will omit the second column with this pattern. I was unable to correctly handle this edge-case.
I also had issues with this part of the tutorial (used tutorial for version 1.7).
My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.
This is the line from django/contrib/admin/templates/admin/base_site.html:
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).
Example manual:
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
I just had this issue as well on a server I own, and the root cause was APC. I commented out the "apc.so" extension in the php.ini file, reloaded Apache, and the sites came right back up.
#!/usr/bin/python
import subprocess
p = subprocess.Popen(["tail", "-n 3", "passlist"], stdout=subprocess.PIPE)
output, err = p.communicate()
print output
This Method Worked for me
What good is a timestamp with its granularity given in seconds? I find it much more practical working with Time.now.to_f
. Heck, you may even throw a to_s.sub('.','')
to get rid of the decimal point, or perform a typecast like this: Integer(1e6*Time.now.to_f)
.
There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.
Demo site: https://brendandahl.github.io/trapeze-reader/demos/
Github page: https://github.com/brendandahl/trapeze-reader
Disclaimer: I'm the author.
I have found this way of reading strings from files to work best for me
String st, full;
full="";
BufferedReader br = new BufferedReader(new FileReader(URL));
while ((st=br.readLine())!=null) {
full+=st;
}
"full" will be the completed combination of all of the lines. If you want to add a line break between the lines of text you would do
full+=st+"\n";
You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe
has been deprecated.
Instead, you'll want to do something like this:
<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>
In your controller, inject the $sce
service, and mark the HTML as "trusted":
myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
$scope.preview_data.preview.embed.htmlSafe =
$sce.trustAsHtml(preview_data.preview.embed.html);
}
Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)
As a workaround, I've been using this:
# Fix Python 2.x.
try:
UNICODE_EXISTS = bool(type(unicode))
except NameError:
unicode = lambda s: str(s)
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.
My solution was to use DOSKEY to set up some aliases to for the commands I use the most:
DOSKEY svc=TortoiseProc.exe /command:commit /path:.
DOSKEY svu=TortoiseProc.exe /command:update /path:.
DOSKEY svl=TortoiseProc.exe /command:log /path:.
DOSKEY svd=TortoiseProc.exe /command:diff /path:$*
Google "doskey persist" for tips on how to set up a .cmd file that runs every time you open the command prompt like a .*rc file in Unix.
In my case, I didnt have the Apple Root certificate. It can be found here:
You're looking for the JavaScriptSerializer
class, which is used internally by JsonResult:
string json = new JavaScriptSerializer().Serialize(jsonResult.Data);
Edit the build path in this order, this worked for me.
Make sure the /gen
is before /src
To make it work I build my directory like this:
Project Public Restrict
So I edited my webconfig for my public folder:
<location path="Project/Public">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
And for my Restricted folder:
<location path="Project/Restricted">
<system.web>
<authorization>
<allow users="*"/>
</authorizatio>
</system.web>
</location>
See here for the spec of * and ?:
https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add
I hope I have helped.
Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.
From that post (by David):
to also check blank string, I suggest following
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty fn:trim(var1)}">
</c:if>
It also handles nulls
You can use boost::array to do that:
boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);
Edit:
Or you can use a vector of vectors as shown below:
char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));
I have used pdflib for this.
p = new pdflib();
/* Open the input PDF */
indoc = p.open_pdi_document("myTestFile.pdf", "");
pageCount = (int) p.pcos_get_number(indoc, "length:pages");
You can use ToString() to convert the first enum to its name, and then Enum.Parse() to convert the string back to the other Enum. This will throw an exception if the value is not supported by the destination enum (i.e. for an "Unknown" value)
MySQL
SELECT * FROM `emails` WHERE `email`
NOT REGEXP '[-a-z0-9~!$%^&*_=+}{\\\'?]+(\\.[-a-z0-9~!$%^&*_=+}{\\\'?]+)*@([a-z0-9_][-a-z0-9_]*(\\.[-a-z0-9_]+)*\\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,5})?'
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
Here's how to do the same with Swift;
var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")
To get it back later;
if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
// Do something with savedValue
}
In Swift 3.0
var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")
if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {
}
The Taylor series is one way to approximate pi. As noted it converges slowly.
The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.
Other means of approximating pi have similar ways to calculate the max error.
We know this because we can prove it mathematically.
Two possible approaches:
I don't think popen()
is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command
).
On the off-chance that there is no popen()
, you can use system("./some_command >/tmp/some_command.out");
, then use the normal I/O functions to process the output file.
I had enough success just catchig socket.timeout
and socket.error
; although socket.error can be raised for lots of reasons. Be careful.
import socket
import logging
hostname='google.com'
port=443
try:
sock = socket.create_connection((hostname, port), timeout=3)
except socket.timeout as err:
logging.error(err)
except socket.error as err:
logging.error(err)
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash="btn_"+$(this).attr("id")
//return false;
});
});
Now the URL appears as page.aspx#btn_elementID
which is not a real ID on the page. I just remove "btn_" and get the actual element ID
I tried several of the suggested solutions, but none of them worked for me. After some research I stumbled upon a hint to move some apps from /data/app
to /system/app
. That freed up enough space to install new apps and update existing ones.
I can recommend the free utility SystemCleanup for moving the apps.
My solution is to add this code to the app.php
define('WEB_DIRECTORY', __DIR__);
The problem is that in command line code that uses the constant will break. You can also add the constant to app/console file and the other environment front controllers
Another solution may be add an static method at AppKernel that returns DIR.'/../web/' So you can access everywhere
This is best solution : https://developer.android.com/studio/write/tool-attributes
This is design attributes we can set activty context in xml like
tools:context=".activity.ActivityName"
Adapter:
tools:context="com.PackegaName.AdapterName"
You can navigate to java class when clicking on the marked icon and tools have more features like
tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view
etx
In httpd.conf
on /Applications/MAMP/conf/apache
, find:
<Directory />
Options Indexes FollowSymLinks
AllowOverride None
</Directory>
Replace None
with All
.
Restart MAMP servers.
This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a)
. A more stringent test might be to check that the name is actually defined in the list:
foo <- list(a=42, b=NULL)
foo
is.null(foo[["a"]]) # FALSE
is.null(foo[["b"]]) # TRUE, but the element "exists"...
is.null(foo[["c"]]) # TRUE
"a" %in% names(foo) # TRUE
"b" %in% names(foo) # TRUE
"c" %in% names(foo) # FALSE
...and foo[["a"]]
is safer than foo$a
, since the latter uses partial matching and thus might also match a longer name:
x <- list(abc=4)
x$a # 4, since it partially matches abc
x[["a"]] # NULL, no match
[UPDATE] So, back to the question why exists('foo$a')
doesn't work. The exists
function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a"
is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE
...
foo <- list(a=42, b=NULL) # variable "foo" with element "a"
"bar$a" <- 42 # A variable actually called "bar$a"...
ls() # will include "foo" and "bar$a"
exists("foo$a") # FALSE
exists("bar$a") # TRUE
Remove the panel background
<item name="android:windowBackground">@color/transparent_color</item>
<color name="transparent_color">#00000000</color>
This is Mystyle:
<style name="ThemeDialogCustom">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowBackground">@color/transparent_color</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">@null</item>
</style>
Which i have added to the constructor.
Add textColor :
<item name="android:textColor">#ff0000</item>
Handmade dll's collection folder
If you solution has a garbage folder for dll-files from different libraries
lib
, source
, libs
, etc.
You can get this trouble if you'll open your solution (for a firs time) in Visual Studio. And your dll's collecting folder is missed for somehow or a concrete dll-file is missed.
Visual Studio will try silently to substitute dll's reference for something on its own. If VS will succeed then a new reference will be persistent for your local solution. Not for other clones/checkouts.
I.e. your <HintPath>
will be ignored and you project file (.csproj) will not be changed.
As an example of me
<Reference Include="DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\DocumentFormat.OpenXml.dll</HintPath>
</Reference>
The DocumentFormat.OpenXml
will be referenced from C:\Program Files (x86)\Open XML SDK\V2.5\lib
not from a solution\..\lib
folder.
fast Workaround
right Workaround is to migrate to NuGet package manager.
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:top="-6dp"
android:left="-6dp"
android:right="-6dp"
android:bottom="0dp">
<shape android:shape="rectangle">
<solid android:color="#88FFFF00"/>
<stroke
android:width="5dp"
android:color="#FF000000"/>
</shape>
</item>
</layer-list>
this question asked in 2009 but i want to share my codes:
Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable
Dim x As Integer
Dim y As Integer
Dim bln As Boolean
Dim dttable2 As New DataTable
For x = 0 To dttable.Columns.Count - 1
dttable2.Columns.Add(dttable.Columns(x).ColumnName)
Next
For x = 0 To dttable.Rows.Count - 1
For y = 0 To searchcolumns.Length - 1
If String.IsNullOrEmpty(searchcolumns(y)) = False Then
If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
bln = True
Else
bln = False
Exit For
End If
End If
Next
If bln = True Then
dttable2.Rows.Add(dttable.Rows(x).ItemArray)
End If
Next
Return dttable2
End Function
You'll want to add a Symbolic Breakpoint
. Apple provides an excellent guide on how to do this.
cmd+7
(cmd+8
in Xcode 9)Add
button in the lower leftAdd Symbolic Breakpoint...
Symbol
just type in UIViewAlertForUnsatisfiableConstraints
You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.
What role do they play when exiting an application in C#?
The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.
But what is the difference?
One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.
[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .
System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
I have a solution for this but not sure on the reason why this would be different from one environment to the other - although one big difference between the two environments is WSS svc pack 1 was installed on the environment where the error was occurring.
To fix this issue I got a good clue from this link - http://silverlight.net/forums/t/22787.aspx ie to "please check the Xml Schema of your service" and "the sequence in the schema is sorted alphabetically"
Looking at the wsdl generated I noticed that for the serialized class that was causing the error, the properties of this class were not visible in the wsdl.
The Definition of the class had private setters for most of the properties, but not for CustomFields property ie..
[Serializable]
public class FileMetaDataDto
{
.
. a constructor... etc and several other properties edited for brevity
.
public int Id { get; private set; }
public string Version { get; private set; }
public List<MetaDataValueDto> CustomFields { get; set; }
}
On removing private from the setter and redeploying the service then looking at the wsdl again, these properties were now visible, and the original error was fixed.
So the wsdl before update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
</s:sequence>
</s:complexType>
The wsdl after update was
- <s:complexType name="ArrayOfFileMetaDataDto">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="FileMetaDataDto" nillable="true" type="tns:FileMetaDataDto" />
</s:sequence>
</s:complexType>
- <s:complexType name="FileMetaDataDto">
- <s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Name" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Title" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ContentType" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Icon" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="ModifiedBy" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="ModifiedDateTime" type="s:dateTime" />
<s:element minOccurs="1" maxOccurs="1" name="FileSizeBytes" type="s:int" />
<s:element minOccurs="0" maxOccurs="1" name="Url" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="RelativeFolderPath" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="DisplayVersion" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="Version" type="s:string" />
<s:element minOccurs="0" maxOccurs="1" name="CustomFields" type="tns:ArrayOfMetaDataValueDto" />
<s:element minOccurs="0" maxOccurs="1" name="CheckoutBy" type="s:string" />
</s:sequence>
</s:complexType>
vagrant destroy
vagrant up
Please add this to vagrant file:
config.ssh.username = 'vagrant'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'
Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at
<%GERONIMO_HOME%>/var/catalina/server.xml
.
The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize
still displays 2097152 (the default value)
Taking some of the answers .. making a single-line jquery.
$('#search').focus().val($('#search').val());
It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.
The easy way is to annotate your getters and setters.
Here is the original example modified to exclude the plain text password, but then annotate a new method that just returns the password field as encrypted text.
class User {
private String password;
public void setPassword(String password) {
this.password = password;
}
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty("password")
public String getEncryptedPassword() {
// encryption logic
}
}
This problem is because the machine can't find the the correct ISAM (indexed sequential driver method) registered that Access needs.
It's probably because the machine doesn't have MSACeesss installed? I would make sure you have the latest version of Jet, and if it still doesn't work, find the file Msrd3x40.dll from one of the other machines, copy it somewhere to the Vista machine and call regsvr32 on it (in Admin mode) that should sort it out for you.
step1 :open xampp control panel
step 2: then click apache module config button.
step 3. after that you able to see some config file list.
step 4: then click the php.ini file.it will be open into default editor.
I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).
Should IDs be unique? YES.
Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
Try this code which makes use of a cross product:
public bool isLeft(Point a, Point b, Point c){
return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0;
}
Where a = line point 1; b = line point 2; c = point to check against.
If the formula is equal to 0, the points are colinear.
If the line is horizontal, then this returns true if the point is above the line.
Changing import statement worked. From
import * as $ from 'jquery';
to:
declare var $ : any;
If you have previously installed node using brew, then you will have a bunch of extra files that you should clean up before installing node "the right way". Plus, I had to add a few settings to my startup script to make things work smoothly.
I wrote a script to make this easy.
# filename: install-nvm-npm-node
# author: Lex Sheehan
# purpose: To cleanly install NVM, NODE and NPM
# dependencies: brew
NOW=$(date +%x\ %H:%M:%S)
CR=$'\n'
REV=$(tput rev)
OFF=$(tput sgr0)
BACKUP_DIR=$HOME/backups/nvm-npm-bower-caches/$NOW
MY_NAME=$(basename $0)
NODE_VER_TO_INSTALL=$1
if [ "$NODE_VER_TO_INSTALL" == "" ]; then
NODE_VER_TO_INSTALL=v0.12.2
fi
if [ "`echo "$NODE_VER_TO_INSTALL" | cut -c1-1`" != "v" ]; then
echo """$CR""Usage: $ $MY_NAME <NODE_VERSION_TO_INSALL>"
echo "Example: $ $MY_NAME v0.12.1"
echo "Example: $ $MY_NAME $CR"
exit 1
fi
echo """$CR""First, run: $ brew update"
echo "Likely, you'll need to do what it suggests."
echo "Likely, you'll need to run: $ brew update$CR"
echo "To install latest node version, run the following command to get the latest version: $ nvm ls-remote"
echo "... and pass the version number you want as the only param to $MY_NAME. $CR"
echo "Are you ready to install the latest version of nvm and npm and node version $NODE_VER_TO_INSTALL ?$CR"
echo "Press CTL+C to exit --or-- Enter to continue..."
read x
echo """$REV""Uninstalling nvm...$CR$OFF"
# Making backups, but in all likelyhood you'll just reinstall them (and won't need these backups)
if [ ! -d "$BACKUP_DIR" ]; then
echo "Creating directory to store $HOME/.nvm .npm and .bower cache backups: $BACKUP_DIR"
mkdir -p $BACKUP_DIR
fi
set -x
mv $HOME/.nvm $BACKUP_DIR 2>/dev/null
mv $HOME/.npm $BACKUP_DIR 2>/dev/null
mv $HOME/.bower $BACKUP_DIR 2>/dev/null
{ set +x; } &>/dev/null
echo "$REV""$CR""Uninstalling node...$CR$OFF"
echo "Enter your password to remove user some node-related /usr/local directories"
set -x
sudo rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/lib/node
rm -rf /usr/local/include/node
rm -rf /usr/local/include/node_modules
rm /usr/local/bin/npm
rm /usr/local/lib/dtrace/node.d
rm -rf $HOME/.node
rm -rf $HOME/.node-gyp
rm /opt/local/bin/node
rm /opt/local/include/node
rm -rf /opt/local/lib/node_modules
rm -rf /usr/local/Cellar/nvm
brew uninstall node 2>/dev/null
{ set +x; } &>/dev/null
echo "$REV""$CR""Installing nvm...$CR$OFF"
echo "++brew install nvm"
brew install nvm
echo '$(brew --prefix nvm)/nvm.sh'
source $(brew --prefix nvm)/nvm.sh
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc):$CR$OFF"
echo "export NVM_DIR=\"\$(brew --prefix nvm)\"; [ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"$CR"
NVM_DIR="$(brew --prefix nvm)"
echo """$CR""Using nvm install node...$CR"
echo "++ nvm install $NODE_VER_TO_INSTALL"
nvm install $NODE_VER_TO_INSTALL
NODE_BINARY_PATH="`find /usr/local/Cellar/nvm -name node -type d|head -n 1`/$NODE_VER_TO_INSTALL/bin"
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc) and then restart your shell:$CR$OFF"
echo "export PATH=\$PATH:$NODE_BINARY_PATH:$HOME/.node/bin"
echo """$CR""Upgrading npm...$CR"
echo '++ install -g npm@latest'
npm install -g npm@latest
{ set +x; } &>/dev/null
echo "$REV""$CR""Insert following line in your $HOME/.npmrc file:$OFF"
echo """$CR""prefix=$HOME/.node$CR"
echo "Now, all is likley well if you can run the following without errors: npm install -g grunt-cli$CR"
echo "Other recommended global installs: bower, gulp, yo, node-inspector$CR"
I wrote a short article here that details why this is "the right way".
If you need to install iojs, do so using nvm like this:
nvm install iojs-v1.7.1
To install brew, just see its home page.
See alexpods answer for the rest.
Try this, It supports multi file uploading,
$('#multi_file_upload').change(function(e) {
var file_id = e.target.id;
var file_name_arr = new Array();
var process_path = site_url + 'public/uploads/';
for (i = 0; i < $("#" + file_id).prop("files").length; i++) {
var form_data = new FormData();
var file_data = $("#" + file_id).prop("files")[i];
form_data.append("file_name", file_data);
if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
$.ajax({
//url : site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
url: site_url + "inc/upload_contact_info.php",
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
type: 'post',
success: function(data) {
// display image
}
});
} else {
$("#" + html_div).html('');
alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
}
}
});
function check_multifile_logo(file) {
var extension = file.substr((file.lastIndexOf('.') + 1))
if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
return true;
} else {
return false;
}
}
Here #multi_file_upload is the ID of image upload field.
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
For Example you have the package "com.abc" and you have multiple packages inside it, You can use like
@ComponentScan("com.abc")
Here is an iterative solution using object-scan. The advantage is that you can easily do other processing in the filter function and specify the paths in a more readable format. There is a trade-off in introducing a dependency though, so it really depends on your use case.
// const objectScan = require('object-scan');
const search = (haystack, k, v) => objectScan([`list[*].${k}`], {
rtn: 'parent',
filterFn: ({ value }) => value === v
})(haystack);
const obj = { list: [ { name: 'my Name', id: 12, type: 'car owner' }, { name: 'my Name2', id: 13, type: 'car owner2' }, { name: 'my Name4', id: 14, type: 'car owner3' }, { name: 'my Name4', id: 15, type: 'car owner5' } ] };
console.log(search(obj, 'name', 'my Name'));
// => [ { name: 'my Name', id: 12, type: 'car owner' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
I am using mysql 8.0.12 and updating the mysql connector to mysql-connector-java-8.0.12 resolved the issue for me.
Hope it helps somebody.
email is your email-is.
public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
if os.path.exists(filePath):
#the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
#the file does not exists but write privileges are given
else:
#can not write there
Note that path.exists
can fail for more reasons than just the file is not there
so you might have to do finer tests like testing if the containing directory exists and so on.
After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.
Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}
You could also check using the age()
function
select * from mytable where age( mydate, now() ) > '1 year';
age()
wil return an interval.
For example age( '2015-09-22', now() )
will return -1 years -7 days -10:56:18.274131
setInterval
repeats the call, setTimeout
only runs it once.
The string
class's Replace
method can also be used to remove multiple characters from a string:
Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")
I can't fault any of the answers here for the OP accepted one of them as resolving their problem. However, I found them flawed in one respect. When you output the result of the assignment to the variable, it contains numerous blank lines, not just the sought after answer. Example:
PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
I'm a fan of two things in code, succinctness and correctness. brianary has the right of it for succinctness with a tip of the hat to Roger Lipscombe but both miss correctness due to the extra lines in the result. Here's what I think the OP was looking for since it's what got me over the finish line.
PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
Note the lack of extra lines, only the one that PowerShell uses to separate prompts. Now this can be assigned to a variable for comparison or, as in my case, stored in a file for reading and comparison in a later session.
Stop abusing private fields!!!
The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.
Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.
There are two cases you want to extend a class:
There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.
Consider a simple library that models cars:
class Car {
private screw;
public assembleCar() {
screw.install();
};
private putScrewsTogether() {
...
};
}
The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar()
right? Let's mark screw as private.
Well, the author is wrong. If you want to modify only the assembleCar()
method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw
field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.
Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.
The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected
so everyone would be happier later. At least don't abuse private field.
I very much support Nick's answer.
Disable Nvidia's nView Desktop Manager and the problem should resolve.
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
Simple way to converting SQL query to POJO class collection ,
Query query = getCurrentSession().createSQLQuery(sqlQuery).addEntity(Actors.class);
List<Actors> list = (List<Actors>) query.list();
return list;
The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:
<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>
unless x
x = y
end
unless x has a value (it's not nil or false), set it equal to y
is equivalent to
x ||= y
#python3
import datetime
print(
'1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
)
d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))
# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")
print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")
1: test-2018-02-14_16:40:52.txt
2a: March 04, 2018
2b: March 04, 2018
3: Today is 2018-11-11 yay
Description:
Using the new string format to inject value into a string at placeholder {}, value is the current time.
Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.
https://docs.python.org/3/library/string.html#formatexamples
You need to pass the values of the dict into the Bike
constructor before using like that. Or, see the namedtuple
-- seems more in line with what you're trying to do.
To begin with, I will try not to sound flamish here ;)
Sigh.. Why don't people get that file explorer integrated clients is the way to go? It is so much more efficient than opening terminals and typing. Simple math, ~two mouse clicks versus ~10+ key strokes. Though, I must point out that I love command line since I do lot's of administrative work and prefer to automate things as quickly and easy as possible.
Having been spoiled by TortoiseSVN on windows I was amazed by the lack of a tortoisesvn-like integrated client when I moved to ubuntu. For pure programmers an IDE integrated client might be enough but for general purpose use and for say graphics artists or other random office people, the client has to be integrated into the standard file explorer, else most people will not use it, at all, ever.
Some thought's on some clients:
kdesvn, The client I like the best this far, though there is one huge annoyance compared to TortoiseSVN - you have to enter the special subversion layout mode to get overlays indicating file status. Thus I would not call kdesvn integrated.
NautilusSVN, looks promising but as of 0.12 release it has performance problems with big repositories. I work with repositories where working copies can contain ~50 000 files at times, which TortoiseSVN handles but NautilusSVN does not. So I hope NautilusSVN will get a new optimized release soon.
RapidSVN is not integrated, but I gave it a try. It behaved quite weird and crashed a couple of times. It got uninstalled after ~20 minutes..
I really hope the NautilusSVN project will make a new performance optimized release soon.
NaughtySVN seems like it could shape up to be quite nice, but as of now it lacks icon overlays and has not had a release for two years... so I would say NautilusSVN is our only hope.
All the above mentioned answers will almost fullfill the purpose. However, You need to drop the temp table after all the operation on it. You can follow-
INSERT INTO #TempTable (ID, Date, Name) SELECT id, date, name FROM physical_table;
IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULL DROP TABLE #TempTable;
Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.
As example you could create your own bundle:
bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
And render it like this:
@Scripts.Render("~/bundles/mybundle")
One more advantage of @Scripts.Render("~/bundles/mybundle")
over the native <script src="~/bundles/mybundle" />
is that @Scripts.Render()
will respect the web.config
debug setting:
<system.web>
<compilation debug="true|false" />
If debug="true"
then it will instead render individual script tags for each source script, without any minification.
For stylesheets you will have to use a StyleBundle and @Styles.Render().
Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.
you can try checking out your fields as you are rendering email field which is not available in your ajax
$.ajax({_x000D_
url: "url",_x000D_
type: 'GET',_x000D_
success: function(data) {_x000D_
var new_data = {_x000D_
"data": data_x000D_
};_x000D_
console.log(new_data);_x000D_
}_x000D_
});
_x000D_
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
You could also flip your if test:
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}
Nested forms are not supported and are not part of the w3c standard ( as many of you have stated ).
However HTML5 adds support for inputs that don't have to be descendants of any form, but can be submitted in several forms - by using the "form" attribute. This doesn't exactly allow nested forms, but by using this method, you can simulate nested forms.
The value of the "form" attribute must be id of the form, or in case of multiple forms, separate form id's with space.
You can read more here
You need to do this:
exec procName
@parameter_1_Name = 'parameter_1_Value',
@parameter_2_name = 'parameter_2_value',
@parameter_z_name = 'parameter_z_value'
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
Another easy option to show Dialog is to use stacked_services package
_dialogService.showDialog(
title: "Title",
description: "Dialog message Tex",
);
});
You can try changing it to this:
If myTableData.Rows.Count > 0 Then
For i As Integer = 0 To myTableData.Rows.Count - 1
''Dim DataType() As String = myTableData.Rows(i).Item(1)
ListBox2.Items.Add(myTableData.Rows(i)(1))
Next
End If
Note: Your loop needs to be one less than the row count since it's a zero-based index.
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
I m not satisfied by the best answer by the Joseph, instead of fixing the correct problem, he told that this is wrong use case. In fact there are many places for example if you are converting an old codebase to ajaxified code and there you NEED it, then you NEED it. In programming there is no excuse because its not only you who is coding its all bad and good developers and you have to work side by side. So if I don't code redirection in ajax my fellow developer can force me to have a solution for it. Just like I like to use all AMD patterned sites or mvc4, and my company can keep me away from it for a year.
So let's talk on the solution now.
I have done hell heck of ajax request and response handling and the simplest way I found out was to send status codes to the client and have one standard javascript function to understand those codes. If i simply send for example code 13 it might meant a redirect.
So a json response like { statusCode: 13, messsage: '/home/logged-in' } of course there are tons of variations proposed like { status: 'success', code: 13, url: '/home/logged-in', message: 'You are logged in now' }
etc , so up to your own choice of standard messages
Usually I Inherit from base Controller class and put my choice of standard responses like this
public JsonResult JsonDataResult(object data, string optionalMessage = "")
{
return Json(new { data = data, status = "success", message = optionalMessage }, JsonRequestBehavior.AllowGet);
}
public JsonResult JsonSuccessResult(string message)
{
return Json(new { data = "", status = "success", message = message }, JsonRequestBehavior.AllowGet);
}
public JsonResult JsonErrorResult(string message)
{
return Json(new { data = "", status = "error", message = message }, JsonRequestBehavior.AllowGet);
}
public JsonResult JsonRawResult(object data)
{
return Json(data, JsonRequestBehavior.AllowGet);
}
About using $.ajax intead of Ajax.BeginForm I would love to use Jquery ajax and I do, but again its not me in the whole world to make decisions I have an application full of Ajax.BeginForm and of course I didnt do that. But i have to live with it.
So There is a success callback in begin form too, you don't need to use jquery ajax to use callbacks Something about it here Ajax.BeginForm, Calls Action, Returns JSON, How do I access JSON object in my OnSuccess JS Function?
Thanks
From W3Schools
The height in percent of the containing element (like "20%").
So I think they mean the element where the div is in?
The iPhoneOS does capture onscroll
events, except not the way you may expect.
One-finger panning doesn’t generate any events until the user stops panning—an
onscroll
event is generated when the page stops moving and redraws—as shown in Figure 6-1.
Similarly, scroll with 2 fingers fires onscroll
only after you've stopped scrolling.
The usual way of installing the handler works e.g.
window.addEventListener('scroll', function() { alert("Scrolled"); });
// or
$(window).scroll(function() { alert("Scrolled"); });
// or
window.onscroll = function() { alert("Scrolled"); };
// etc
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
If you are using zsh, you need to follow the steps below in mac.
$HOME
location of your mac..zshrc
file.nano ~/.zshrc
into iTerm2 terminal.PATH=$HOME/flutter/bin:$PATH
~/.zshrc
file.Passing no-sandbox to exec seems important for jenkins on windows in foreground or as service. Here's my solution
chromedriver fails on windows jenkins slave running in foreground
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
I used pyplot
's axes
object to manually adjust the sizes without using GridSpec
:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02
rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]
fig = plt.figure()
cones = plt.axes(rect_cones)
box = plt.axes(rect_box)
cones.plot(x, y)
box.plot(y, x)
plt.show()
If you just want to update the relative path you can also do
window.location.pathname = '/relative-link'
"http://domain.com" -> "http://domain.com/relative-link"
@Provider
public class BadURIExceptionMapper implements ExceptionMapper<NotFoundException> {
public Response toResponse(NotFoundException exception){
return Response.status(Response.Status.NOT_FOUND).
entity(new ErrorResponse(exception.getClass().toString(),
exception.getMessage()) ).
build();
}
}
Create above class. This will handle 404 (NotFoundException) and here in toResponse method you can give your custom response. Similarly there are ParamException etc. which you would need to map to provide customized responses.
The Event type input
did not work for me on <select>
but changing it to change
works
useEffect(() => {
var event = new Event('change', { bubbles: true });
selectRef.current.dispatchEvent(event); // ref to the select control
}, [props.items]);
You can accomplish this as follows:
if a_string.isdigit():
do_this()
else:
do_that()
https://docs.python.org/2/library/stdtypes.html#str.isdigit
Using .isdigit()
also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).
My try is combined solution.
string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;
First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.
Second line cleans numbers after dot.
I don't know if have other option but we can drop the value using:
select oid from pg_type where typname = 'fase';'
select * from pg_enum where enumtypid = 24773;'
select * from pg_enum where enumtypid = 24773 and enumsortorder = 6;
delete from pg_enum where enumtypid = 24773 and enumsortorder = 6;
You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);
Just unset the proxy host using :
unset HOST
This worked for me.
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
It's possible to prevent webpage scaling in safari on iOS 10, but it's going to involve more work on your part. I guess the argument is that a degree of difficulty should stop cargo-cult devs from dropping "user-scalable=no" into every viewport tag and making things needlessly difficult for vision-impaired users.
Still, I would like to see Apple change their implementation so that there is a simple (meta-tag) way to disable double-tap-to-zoom. Most of the difficulties relate to that interaction.
You can stop pinch-to-zoom with something like this:
document.addEventListener('touchmove', function (event) {
if (event.scale !== 1) { event.preventDefault(); }
}, false);
Note that if any deeper targets call stopPropagation on the event, the event will not reach the document and the scaling behavior will not be prevented by this listener.
Disabling double-tap-to-zoom is similar. You disable any tap on the document occurring within 300 milliseconds of the prior tap:
var lastTouchEnd = 0;
document.addEventListener('touchend', function (event) {
var now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
If you don't set up your form elements right, focusing on an input will auto-zoom, and since you have mostly disabled manual zoom, it will now be almost impossible to unzoom. Make sure the input font size is >= 16px.
If you're trying to solve this in a WKWebView in a native app, the solution given above is viable, but this is a better solution: https://stackoverflow.com/a/31943976/661418. And as mentioned in other answers, in iOS 10 beta 6, Apple has now provided a flag to honor the meta tag.
Update May 2017: I replaced the old 'check touches length on touchstart' method of disabling pinch-zoom with a simpler 'check event.scale on touchmove' approach. Should be more reliable for everyone.
You can do:
#!/bin/bash
if <command> ; then # TRY
<do-whatever-you-want>
else # CATCH
echo 'Exception'
<do-whatever-you-want>
fi
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler
html {background-color: grey}
Start from m2e 0.13.0 (if not earlier than), you can convert a Java project to Maven project from the context menu. Here is how:
Here is the detailed steps with screen shots.
$( this ).attr( 'checked', 'checked' )
just attr( 'checked' )
will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />
Edit:
Based on comments, a more appropriate manipulation would be:
$( this ).attr( 'checked', true )
And a straight javascript method, more appropriate and efficient:
this.checked = true;
Thanks @Andy E for that.
I had to convert timestamps inline in my bash history to make sense to me.
Maybe the following coming from an answer to How do I replace a substring by the output of a shell command with sed, awk or such? could be interesting to other readers too. Kudos for the original sed inline code go to @Gabriel.
cat ~/.bash_history | sed "s/^#\([0-9]\+\)$/echo -n '#'; date -u --d @\1 '\+\%Y-\%m-\%d \%T'/e" | less
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)
or
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
Try this
git clone ssh://[email protected]:11111/home/git/repo.git
Just in case someone only wishes to check if port 22 is open on a remote machine, this simple netcat command is useful. I used it because nmap and telnet were not available for me. Moreover, my ssh configuration uses keyboard password auth.
It is a variant of the solution proposed by GUESSWHOz.
nc -q 0 -w 1 "${remote_ip}" 22 < /dev/null &> /dev/null && echo "Port is reachable" || echo "Port is unreachable"
Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
import os
os.environ["PATH"] += os.pathsep + "/Macintosh HD?/anaconda3?/lib?/?python3.7?/site-packages?/sphinx?/templates?/graphviz"
This solved the PATH issue on MAC for me!
git add -A -n
will do what you want. -A
adds all untracked files to the repo, -n
makes it a dry-run
where the add isn't performed but the status output is given listing each file that would have been added.