You should use Console.ReadLine() if you want to read some input from the console.
To see your code running in Console:
In Solution Explorer (View - Solution Explorer from the menu), right click on your project, select Open Folder in File Explorer, to find where your project path is.
Supposedly the path is C:\code\myProj .
Open the Command Prompt app in Windows.
Change to your folder path. cd C:\code\myProj
Change to the debug folder, where you should find your program executable. cd bin\debug
Run your program executable, it should end in .exe extension.
Example:
myproj.exe
You should see what you output in Console.Out.WriteLine() .
Calling a REST API when using .NET 4.5 or .NET Core
I would suggest DalSoft.RestClient (caveat: I created it). The reason being, because it uses dynamic typing, you can wrap everything up in one fluent call including serialization/de-serialization. Below is a working PUT example:
dynamic client = new RestClient("http://jsonplaceholder.typicode.com");
var post = new Post { title = "foo", body = "bar", userId = 10 };
var result = await client.Posts(1).Put(post);
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
Just to add my two cents. I've put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has "only" limited permissions like:
ALTER ANY DATABASE
P.S. I've spent hours trying to figure out why the "ALTER DATABASE.." does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here's my MSDN thread!
This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation. See the example from java 5: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html or java 7 (same example): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
Adding nan to list, and the below works for me:
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456',np.nan]
any([i for i in [x for x in some_list if str(x) != 'nan'] if "abc" in i])
This is definitely a bug specially while it's FireFox. I searched alot tried all the above answers and finally got it as bug by many experts over SO. So, I finally came up with this idea by declaring variable like
var called = false;
$("#ColorPalete li").click(function() {
if(!called)
{
called = true;
setTimeout(function(){ //<-----This can be an ajax request but keep in mind to set called=false when you get response or when the function has successfully executed.
alert('I am called');
called = false;
},3000);
}
});
In this way it first checks rather the function was previously called or not.
-(void)showAlert{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
message:"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
[self showAlert];
// calling Method
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
If you are using posix sed
Selection for any case for a pattern (converting the searched pattern with this sed than use the converted pattern in you wanted command using regex:
echo "${MyOrgPattern} | sed "s/[aA]/[aA]/g;s/[bB]/[bB]/g;s/[cC]/[cC]/g;s/[dD]/[dD]/g;s/[eE]/[eE]/g;s/[fF]/[fF]/g;s/[gG]/[gG]/g;s/[hH]/[hH]/g;s/[iI]/[iI]/g;s/[jJ]/[jJ]/g;s/[kK]/[kK]/g;s/[lL]/[lL]/g;s/[mM]/[mM]/g;s/[nN]/[nN]/g;s/[oO]/[oO]/g;s/[pP]/[pP]/g;s/[qQ]/[qQ]/g;s/[rR]/[rR]/g;s/[sS]/[sS]/g;s/[tT]/[tT]/g;s/[uU]/[uU]/g;s/[vV]/[vV]/g;s/[wW]/[wW]/g;s/[xX]/[xX]/g;s/[yY]/[yY]/g;s/[zZ]/[zZ]/g" | read -c MyNewPattern
YourInputStreamCommand | egrep "${MyNewPattern}"
convert in lower case
sed "s/[aA]/a/g;s/[bB]/b/g;s/[cC]/c/g;s/[dD]/d/g;s/[eE]/e/g;s/[fF]/f/g;s/[gG]/g/g;s/[hH]/h/g;s/[iI]/i/g;s/j/[jJ]/g;s/[kK]/k/g;s/[lL]/l/g;s/[mM]/m/g;s/[nN]/n/g;s/[oO]/o/g;s/[pP]/p/g;s/[qQ]/q/g;s/[rR]/r/g;s/[sS]/s/g;s/[tT]/t/g;s/[uU]/u/g;s/[vV]/v/g;s/[wW]/w/g;s/[xX]/x/g;s/[yY]/y/g;s/[zZ]/z/g"
same for uppercase replace lower letter between // by upper equivalent in the sed
Have fun
AssemblyVersion
pretty much stays internal to .NET, while AssemblyFileVersion
is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the AssemblyFileVersion
is what you'll see up top. If you sort files by version, this is what's used by Explorer.
The AssemblyInformationalVersion
maps to the "Product Version" and is meant to be purely "human-used".
AssemblyVersion
is certainly the most important, but I wouldn't skip AssemblyFileVersion
, either. If you don't provide AssemblyInformationalVersion
, the compiler adds it for you by stripping off the "revision" piece of your version number and leaving the major.minor.build.
It's a better idea to put your configuration variables in a configuration file.
In your case, I would suggest putting your variables in config/mail.php like:
'imap_hostname' => env('IMAP_HOSTNAME_TEST', 'imap.gmail.com')
And refer to them by
config('mail.imap_hostname')
It first tries to get the configuration variable value in the .env file and if it couldn't find the variable value in the .env file, it will get the variable value from file config/mail.php.
With Microsoft Sql Server:
--
-- Create test case
--
DECLARE @myDateTime DATETIME
SET @myDateTime = '2008-05-03'
--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
There are several ways to create a favicon. The best way for you depends on various factors:
If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.
Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.
As you suggest, you can create a favicon.ico
file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).
Then, declare it in your HTML code:
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.
About your suggestion of placing the favicon.ico
file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).
In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico
file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.
You can achieve a good compatibility with:
favicon.ico
, see above.Declare them with
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">
This is not the full story, but it's good enough in most cases.
The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.
To auto-generate the "source.list" file I suggest to use:
https://debgen.simplylinux.ch/
Where you can select the country, the distribution, ..etc After that, all you need to do is to replace (take a backup of the file first) your original source.list file with the generated one and do as mentioned in other answers:
sudo apt-get update
sudo apt-get install build-essential
-(IBAction)Method
{
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[ViewMain addGestureRecognizer:panRecognizer];
[panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [recognizer velocityInView:self.view];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
[UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
}
To import files from OS X Finder into Android Studio, just drag the relevant files to your resource folder.
Don't find a permanent config option for this, but this is the workaround I'm using
In modern browsers, you need only very little to code to create a collapsible tree :
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
tree[i].addEventListener('click', function(e) {_x000D_
var parent = e.target.parentElement;_x000D_
var classList = parent.classList;_x000D_
if(classList.contains("open")) {_x000D_
classList.remove('open');_x000D_
var opensubs = parent.querySelectorAll(':scope .open');_x000D_
for(var i = 0; i < opensubs.length; i++){_x000D_
opensubs[i].classList.remove('open');_x000D_
}_x000D_
} else {_x000D_
classList.add('open');_x000D_
}_x000D_
e.preventDefault();_x000D_
});_x000D_
}
_x000D_
body {_x000D_
font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
list-style-type: none;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
color: black;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
height: 1em;_x000D_
padding:0 .1em;_x000D_
font-size: .8em;_x000D_
display: block;_x000D_
position: absolute;_x000D_
left: -1.3em;_x000D_
top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
<li><a href="#">Part 1</a>_x000D_
<ul>_x000D_
<li><a href="#">Item A</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item B</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item C</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item D</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item E</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#">Part 2</a>_x000D_
<ul>_x000D_
<li><a href="#">Item A</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item B</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item C</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item D</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item E</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#">Part 3</a>_x000D_
<ul>_x000D_
<li><a href="#">Item A</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item B</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item C</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item D</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Item E</a>_x000D_
<ul>_x000D_
<li><a href="#">Sub-item 1</a></li>_x000D_
<li><a href="#">Sub-item 2</a></li>_x000D_
<li><a href="#">Sub-item 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
(see also this Fiddle)
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
I had the similar issue and the problem was in the config file pg_hba.conf. I had earlier made some changes which was causing the server to error out while trying to start it. Commenting out the extra additions solved the problem.
The function is fine IMO, clear and intuitive. But just to give you (another) answer, here is my go:
def compare_dict(dict1, dict2):
for x1 in dict1.keys():
z = dict1.get(x1) == dict2.get(x1)
if not z:
print('key', x1)
print('value A', dict1.get(x1), '\nvalue B', dict2.get(x1))
print('-----\n')
Can be useful for you or for anyone else..
EDIT:
I have created a recursive version of the one above.. Have not seen that in the other answers
def compare_dict(a, b):
# Compared two dictionaries..
# Posts things that are not equal..
res_compare = []
for k in set(list(a.keys()) + list(b.keys())):
if isinstance(a[k], dict):
z0 = compare_dict(a[k], b[k])
else:
z0 = a[k] == b[k]
z0_bool = np.all(z0)
res_compare.append(z0_bool)
if not z0_bool:
print(k, a[k], b[k])
return np.all(res_compare)
Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.
With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:
width: calc(100% - 200px);
Would work as expected with the strict math option enabled.
However, note that Strict Math is applied globally, not only inside calc()
. That means, if you have:
font-size: 12px + 2px;
The math will no longer be processed by Less -- it will output font-size: 12px + 2px
which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:
font-size: (12px + 2px);
Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.
Combining some features of @HYRY and @arun's answers, you can print the top correlations for dataframe df
in a single line using:
df.corr().unstack().sort_values().drop_duplicates()
Note: the one downside is if you have 1.0 correlations that are not one variable to itself, the drop_duplicates()
addition would remove them
declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Try this
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'form_params' => array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
)
);
Question is little old. As this question is very noisy so posting what I did solved with static method as a util. Just copy, paste and use it!
public static String getFormattedDate(Date date){
Calendar cal=Calendar.getInstance();
cal.setTime(date);
//2nd of march 2015
int day=cal.get(Calendar.DATE);
if(!((day>10) && (day<19)))
switch (day % 10) {
case 1:
return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
case 2:
return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
case 3:
return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
default:
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
For testing purose
Example: calling it from main method!
Date date = new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
for(int i=0;i<32;i++){
System.out.println(getFormattedDate(cal.getTime()));
cal.set(Calendar.DATE,(cal.getTime().getDate()+1));
}
Output:
22nd of February 2018
23rd of February 2018
24th of February 2018
25th of February 2018
26th of February 2018
27th of February 2018
28th of February 2018
1st of March 2018
2nd of March 2018
3rd of March 2018
4th of March 2018
5th of March 2018
6th of March 2018
7th of March 2018
8th of March 2018
9th of March 2018
10th of March 2018
11th of March 2018
12th of March 2018
13th of March 2018
14th of March 2018
15th of March 2018
16th of March 2018
17th of March 2018
18th of March 2018
19th of March 2018
20th of March 2018
21st of March 2018
22nd of March 2018
23rd of March 2018
24th of March 2018
25th of March 2018
typedef
defines a new data type. So you can have:
typedef char* my_string;
typedef struct{
int member1;
int member2;
} my_struct;
So now you can declare variables with these new data types
my_string s;
my_struct x;
s = "welcome";
x.member1 = 10;
For enum
, things are a bit different - consider the following examples:
enum Ranks {FIRST, SECOND};
int main()
{
int data = 20;
if (data == FIRST)
{
//do something
}
}
using typedef enum
creates an alias for a type:
typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
Order data = (Order)20; // Must cast to defined type to prevent error
if (data == FIRST)
{
//do something
}
}
Change
mAdapter = new RecordingsListAdapter(this, recordings);
to
mAdapter = new RecordingsListAdapter(getActivity(), recordings);
and also make sure that recordings!=null
at mAdapter = new RecordingsListAdapter(this, recordings);
suppose you need a label with text customername than you can achive it using 2 ways
[1]@Html.Label("CustomerName")
[2]@Html.LabelFor(a => a.CustomerName) //strongly typed
2nd method used a property from your model. If your view implements a model then you can use the 2nd method.
More info please visit below link
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
OR operator:
<div ng-repeat="k in items">
<div ng-if="k || 'a' or k == 'b'">
<!-- SOME CONTENT -->
</div>
</div>
Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..
For Example:
<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
<li ng-if="user.groups.admin || group.title == 'Home Pages'">
<!--Content-->
</li>
</div>
Another OR example
<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>
AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)
<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
<li ng-if="user.groups.admin && group.title == 'Home Pages'">
<!--Content-->
</li>
</div>
If you're using jQuery, you can use $.inArray() instead.
Yes it is safe.
There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.
Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:
void somefunc(void)
{
SomeType *pst = 0;
AnotherType *pat = 0;
…
pst = new SomeType;
…
if (…)
{
pat = new AnotherType[10];
…
}
if (…)
{
…code using pat sometimes…
}
delete[] pat;
delete pst;
}
There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete
operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.
It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
Some situation would arise where you would have to abandon recursion in a problem where recursion appears to be to your advantage, this is because for problems where your recursion would have to occur thousand of times this would result in a stackoverflow error even though your code did not get stuck in an infinite recursion. Most programming languages limits you to a number of stack calls, so if your recursion goes beyond this limit, then you might consider not using recursion.
var arr1 = [_x000D_
{name: 'a', Val: 1}, _x000D_
{name: 'b', Val: 2}, _x000D_
{name: 'c', Val: 3}_x000D_
];_x000D_
_x000D_
var arr2 = [_x000D_
{name: 'c', Val: 3},_x000D_
{name: 'x', Val: 4}, _x000D_
{name: 'y', Val: 5}, _x000D_
{name: 'z', Val: 6}_x000D_
];_x000D_
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array_x000D_
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1 _x000D_
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2 _x000D_
console.log(_isEqual);// common in both array_x000D_
console.log(_difference1);//difference from array1 _x000D_
console.log(_difference2);//difference from array2
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
I don't know why my web service has the same structure with you but it doesn't need Class for parameter, just is array.
For example: - My WSDL:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns="http://www.kiala.com/schemas/psws/1.0">
<soapenv:Header/>
<soapenv:Body>
<ns:createOrder reference="260778">
<identification>
<sender>5390a7006cee11e0ae3e0800200c9a66</sender>
<hash>831f8c1ad25e1dc89cf2d8f23d2af...fa85155f5c67627</hash>
<originator>VITS-STAELENS</originator>
</identification>
<delivery>
<from country="ES" node=””/>
<to country="ES" node="0299"/>
</delivery>
<parcel>
<description>Zoethout thee</description>
<weight>0.100</weight>
<orderNumber>10K24</orderNumber>
<orderDate>2012-12-31</orderDate>
</parcel>
<receiver>
<firstName>Gladys</firstName>
<surname>Roldan de Moras</surname>
<address>
<line1>Calle General Oraá 26</line1>
<line2>(4º izda)</line2>
<postalCode>28006</postalCode>
<city>Madrid</city>
<country>ES</country>
</address>
<email>[email protected]</email>
<language>es</language>
</receiver>
</ns:createOrder>
</soapenv:Body>
</soapenv:Envelope>
I var_dump:
var_dump($client->getFunctions());
var_dump($client->getTypes());
Here is result:
array
0 => string 'OrderConfirmation createOrder(OrderRequest $createOrder)' (length=56)
array
0 => string 'struct OrderRequest {
Identification identification;
Delivery delivery;
Parcel parcel;
Receiver receiver;
string reference;
}' (length=130)
1 => string 'struct Identification {
string sender;
string hash;
string originator;
}' (length=75)
2 => string 'struct Delivery {
Node from;
Node to;
}' (length=41)
3 => string 'struct Node {
string country;
string node;
}' (length=46)
4 => string 'struct Parcel {
string description;
decimal weight;
string orderNumber;
date orderDate;
}' (length=93)
5 => string 'struct Receiver {
string firstName;
string surname;
Address address;
string email;
string language;
}' (length=106)
6 => string 'struct Address {
string line1;
string line2;
string postalCode;
string city;
string country;
}' (length=99)
7 => string 'struct OrderConfirmation {
string trackingNumber;
string reference;
}' (length=71)
8 => string 'struct OrderServiceException {
string code;
OrderServiceException faultInfo;
string message;
}' (length=97)
So in my code:
$client = new SoapClient('http://packandship-ws.kiala.com/psws/order?wsdl');
$params = array(
'reference' => $orderId,
'identification' => array(
'sender' => param('kiala', 'sender_id'),
'hash' => hash('sha512', $orderId . param('kiala', 'sender_id') . param('kiala', 'password')),
'originator' => null,
),
'delivery' => array(
'from' => array(
'country' => 'es',
'node' => '',
),
'to' => array(
'country' => 'es',
'node' => '0299'
),
),
'parcel' => array(
'description' => 'Description',
'weight' => 0.200,
'orderNumber' => $orderId,
'orderDate' => date('Y-m-d')
),
'receiver' => array(
'firstName' => 'Customer First Name',
'surname' => 'Customer Sur Name',
'address' => array(
'line1' => 'Line 1 Adress',
'line2' => 'Line 2 Adress',
'postalCode' => 28006,
'city' => 'Madrid',
'country' => 'es',
),
'email' => '[email protected]',
'language' => 'es'
)
);
$result = $client->createOrder($params);
var_dump($result);
but it successfully!
You can try this one:
String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
You have to add
<script>jQuery.noConflict();</script>
after
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
_values = pd.read_csv("C:\Users\Mujeeb\Desktop\file.xlxs")
^This line resulted in the same error because I am reading an excel file using
read_csv()
method. Useread_excel()
for reading .xlxs
The #include <filename>
is used when a system file is being referred to. That is a header file that can be found at system default locations like /usr/include
or /usr/local/include
. For your own files that needs to be included in another program you have to use the #include "filename"
syntax.
ASP.NET Version:4.0.30319.18408 belongs to .Net4.5 and System.Web.Http Version=4.0.0.0 is compatible for .NET4.0. So the versions that you have are not compatible. You should update you System.Web.Http to version 5.0.0.0, which is compatible with .Net4.5
Identify "project navigator"
or "package explorer"
view.
Right click on your project, select Build Path --> Configure build Path
.
In the emerging window, you will find four tabs, select "Libraries"
.There, under "Web app libraries"
(expand it), you will see the libraries added to the project's classpath. Check if all of them are available. If one or more are not (they'll have "missing" beside their name and a red mark on their icon), check if you need them (perhaps you don't); if you don't need them, remove it, if you need them, exit this window, look out for the missing jar and IMPORT it into your project.
Copy Pasting @Lichtamberg's comments to gotoalberto's answer
Works also for Java 1.8:
# in ~/.zshrc and ~/.bashrc
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
This fixed my issue on java 8.
str.isspace() returns False
for a valid and empty string
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
Therefore, checking with not
will also evaluate None
Type and ''
or ""
(empty string)
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
Give radio buttons, same name but different IDs.
var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
//condition
final_answer = verified1;
}
else
{
if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
//condition
final_answer = verified2;
}
else
{
return false;
}
}
Try this:
public class ConnectionProvider
{
DbConnection conn;
string connectionString;
DbProviderFactory factory;
// Constructor that retrieves the connectionString from the config file
public ConnectionProvider()
{
this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString.ToString();
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[0].ProviderName.ToString());
}
// Constructor that accepts the connectionString and Database ProviderName i.e SQL or Oracle
public ConnectionProvider(string connectionString, string connectionProviderName)
{
this.connectionString = connectionString;
factory = DbProviderFactories.GetFactory(connectionProviderName);
}
// Only inherited classes can call this.
public DbConnection GetOpenConnection()
{
conn = factory.CreateConnection();
conn.ConnectionString = this.connectionString;
conn.Open();
return conn;
}
}
This is really late to the party, but maybe it will help someone. My solution seems similar to what the OP described as problematic, but maybe it's a feature that Chrome offers now, but not then. I tried right-clicking and saving the .log file after the object was written to the console, but all that gave me was a text file with this:
console.js:230 Done: Array(50000)[0 … 9999][10000 … 19999][20000 … 29999][30000 … 39999][40000 … 49999]length: 50000__proto__: Array(0)
which was of no use to anyone.
What I ended up doing was finding the console.log(data)
in the code, dropped a breakpoint on it and then typed JSON.Stringify(data)
in the console which displayed the entire object as a JSON string and the Chrome console actually gives you a button to copy it. Then paste into a text editor and there's your JSON
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
// Make option have a "selected" attribute using jQuery
var yourValue = "Gateway 2";
$("#gate").find('option').each(function( i, opt ) {
if( opt.value === yourValue )
$(opt).attr('selected', 'selected');
});
I adapted this from http://snook.ca/archives/html_and_css/css-text-rotation :
<style> .Rotate-90 { display: block; position: absolute; right: -5px; top: 15px; -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); } </style> <!--[if IE]> <style> .Rotate-90 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); right:-15px; top:5px; } </style> <![endif]-->
I used this config:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v2.0"/>
<supportedRuntime version="v4.0"/>
</startup>
Worked for me
Answering your question in Dhara's answer comments: "I would like on the second x-axis these tics: (7,8,99) corresponding to the x-axis position 10, 30, 40. Is that possible in some way?" Yes, it is.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
a = np.cos(2*np.pi*np.linspace(0, 1, 60.))
ax1.plot(range(60), a)
ax1.set_xlim(0, 60)
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax2 = ax1.twiny()
ax2.set_xlabel("x-transformed")
ax2.set_xlim(0, 60)
ax2.set_xticks([10, 30, 40])
ax2.set_xticklabels(['7','8','99'])
plt.show()
You'll get:
Yes it is possible. I have achieved using below implementation. for that I am getting array in response which I want in an object as list of attributes.
response = {
"equityMonths": [
{
"id": 1,
"month": "JANUARY",
"isEligible": false
},
{
"id": 2,
"month": "FEBRUARY",
"isEligible": true
},
{
"id": 3,
"month": "MARCH",
"isEligible": false
},
{
"id": 4,
"month": "APRIL",
"isEligible": true
},
{
"id": 5,
"month": "MAY",
"isEligible": false
},
{
"id": 6,
"month": "JUNE",
"isEligible": true
},
{
"id": 7,
"month": "JULY",
"isEligible": true
},
{
"id": 8,
"month": "AUGUST",
"isEligible": false
},
{
"id": 9,
"month": "SEPTEMBER",
"isEligible": true
},
{
"id": 10,
"month": "OCTOBER",
"isEligible": false
},
{
"id": 11,
"month": "NOVEMBER",
"isEligible": true
},
{
"id": 12,
"month": "DECEMBER",
"isEligible": false
}
]
}
here, I want equityMonths
as an object and Jan to Dec it's key and isEligible
as value. for that we have to use Object class's defineProperty()
method which allows to add dynamic property into objects.
code for adding property dynamically to the object.
let equityMonth = new Object();
response.equityMonths.forEach(element => {
Object.defineProperty(equityMonth, element['month'], {
value: element['isEligible'],
writable: true,
enumerable: true,
configurable: true
});
});
console.log("DATA : " + JSON.stringify(equityMonth));
in above code we have array of equityMonths
which we have converted as property into the object.
output:
DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String date = simpleDateFormat.format(newDate.getTime());
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
And use this style:
<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/colorPrimary</item>
</style>
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
To preserve the order:
l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]
Once you've edited a file, you need to commit your changes to git. When you execute this command it will ask for a commit message - which is just a simple bit of text that tells everyone what you've changed.
$ git commit source/main.c
Will commit the file main.c in the directory ./source/
$ git commit -a # the -a flag pulls in all modified files
will commit all changed files (but not new files, those need to be added to the index with git-add). If you want to commit only certain files then you will need to stage them first with git-add and then commit without the -a flag.
Commiting only changes your local repository though not the remote repositories. If you want to send the commits to the remote repository then you will need to do a push.
$ git push <remote> <branch> # push new commits to the <branch> on the <remote> repository
For someone coming from CVS or SVN this is a change since the commit to the central repository now requires two steps.
You can use this in settings.json
"javascript.preferences.quoteStyle": "single"
First of all this is JavaScript and not C#
Then you cannot disable a div because it normally has no functionality. To disable a click event, you simply have to remove the event from the dom object. (bind and unbind)...
Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.
If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.
That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.
I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them
Thank you Cassiopeia for code. I change his code to work with local addresses and made little changes to his conditions. I removed following conditions:
http:/
to file:///
Sub HyperAddForLocalLinks()
Dim CellsWithSpaces As String
'Converts each text hyperlink selected into a working hyperlink
Application.ScreenUpdating = False
Dim NotPresent As Integer
NotPresent = 0
For Each xCell In Selection
xCell.Formula = Trim(xCell.Formula)
If InStr(xCell.Formula, "file:///") <> 0 Then
Hyperstring = Trim(xCell.Formula)
Else
Hyperstring = "file:///" & Trim(xCell.Formula)
End If
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring
i = i + 1
If i = 100000 Then Exit Sub
Nextxcell:
Next xCell
Application.ScreenUpdating = True
End Sub
I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.
That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.
Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:
print("Why, hello there wonderful "
"stackoverflow people!")
Ignoring the fact that base is a reserved word you cannot do inheritance of enum.
The best thing you could do is something like that:
public enum Baseenum
{
x, y, z
}
public enum Consume
{
x = Baseenum.x,
y = Baseenum.y,
z = Baseenum.z
}
public void Test()
{
Baseenum a = Baseenum.x;
Consume newA = (Consume) a;
if ((Int32) a == (Int32) newA)
{
MessageBox.Show(newA.ToString());
}
}
Since they're all the same base type (ie: int) you could assign the value from an instance of one type to the other which a cast. Not ideal but it work.
The $_post
function need the name value
like:
<input type="submit" value"Submit" name="example">
Call
$var = strip_tags($_POST['example']);
if (isset($var)){
// your code here
}
Remember to put not only the tag but also the repository in which that tag is, this way:
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
elixir 1.7-centos7_3 e15e6bf57262 20 hours ago 925MB
You should reference it this way:
elixir:1.7-centos7_3
Below code handles upper and lower cases as well and leaves other character as it is.
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int length = Integer.parseInt(in.nextLine());
String str = in.nextLine();
int k = Integer.parseInt(in.nextLine());
k = k % 26;
System.out.println(encrypt(str, length, k));
in.close();
}
private static String encrypt(String str, int length, int shift)
{
StringBuilder strBuilder = new StringBuilder();
char c;
for (int i = 0; i < length; i++)
{
c = str.charAt(i);
// if c is letter ONLY then shift them, else directly add it
if (Character.isLetter(c))
{
c = (char) (str.charAt(i) + shift);
// System.out.println(c);
// checking case or range check is important, just if (c > 'z'
// || c > 'Z')
// will not work
if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
|| (Character.isUpperCase(str.charAt(i)) && c > 'Z'))
c = (char) (str.charAt(i) - (26 - shift));
}
strBuilder.append(c);
}
return strBuilder.toString();
}
}
No one has mentioned that
In default settings, Floats (System.Single) and doubles (System.Double) will never use overflow checking while Decimal (System.Decimal) will always use overflow checking.
I mean
decimal myNumber = decimal.MaxValue;
myNumber += 1;
throws OverflowException.
But these do not:
float myNumber = float.MaxValue;
myNumber += 1;
&
double myNumber = double.MaxValue;
myNumber += 1;
Don't forget to add the
CONFIG += console
flag in the qmake .pro file.
For the rest is just using some of Qt classes. One way I use it is to spawn processes cross-platform.
Since git 1.7.9 version you can also use git commit --amend --no-edit
to get your result.
Note that this will not include metadata from the other commit such as the timestamp which may or may not be important to you.
I myself wondered how I could change the color of the modal-header.
In my solution to the problem I attempted to follow in the path of how my interpretation of the Bootstrap vision was. I added marker classes to tell what the modal dialog box does.
modal-success, modal-info, modal-warning and modal-error tells what they do and you don't trap your self by suddenly having a color you can't use in every situation if you change some of the modal classes in bootstrap. Of course if you make your own theme you should change them.
.modal-success {
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#dff0d8), to(#c8e5bc));
background-image: -webkit-linear-gradient(#dff0d8 0%, #c8e5bc 100%);
background-image: -moz-linear-gradient(#dff0d8 0%, #c8e5bc 100%);
background-image: -o-linear-gradient(#dff0d8 0%, #c8e5bc 100%);
background-image: linear-gradient(#dff0d8 0%, #c8e5bc 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
border-color: #b2dba1;
border-radius: 6px 6px 0 0;
}
In my solution I actually just copied the styling from alert-success
in bootstrap and added the border-radius to keep the rounded corners.
I have had the same issue, but in a class that was not a part of the service layer. In my case, the transaction manager was simply obtained from the context by the getBean()
method, and the class belonged to the view layer - my project utilizes OpenSessionInView
technique.
The sessionFactory.getCurrentSession()
method, has been causing the same exception as the author's. The solution for me was rather simple.
Session session;
try {
session = sessionFactory.getCurrentSession();
} catch (HibernateException e) {
session = sessionFactory.openSession();
}
If the getCurrentSession()
method fails, the openSession()
should do the trick.
Expanding on the answer given by @user175104 ...
std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
// uses opendir, readdir, and struct dirent.
// left as an exercise to the reader, as it isn't the point of this OP and answer.
}
bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
// uses ifstream to read entire contents
// left as an exercise to the reader, as it isn't the point of this OP and answer.
}
std::vector<std::string> GetAllMacAddresses()
{
std::vector<std::string> macs;
std::string address;
// from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
// ... just read /sys/class/net/eth0/address
// NOTE: there may be more than one: /sys/class/net/*/address
// (1) so walk /sys/class/net/* to find the names to read the address of.
std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
for (auto it = nets.begin(); it != nets.end(); ++it)
{
// we don't care about the local loopback interface
if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
continue;
address.clear();
if (ReadFileContents(*it, "address", address))
{
if (!address.empty())
{
macs.push_back(address);
}
}
}
return macs;
}
If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
But with different length lists, zip truncates each item to the length of the shortest list:
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e')]
You can use map with no function to fill empty results with None:
>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]
zip() is marginally faster though.
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
Above Answers are also correct
There are two Approach
- Use webhooks
- Run script for every specific minute to get fresh pull of docker images
I am just sharing script may be it will helpful for you! You can use it with cronjob, I tried succesfully on OSX
#!/bin/bash
##You can use below commented line for setting cron tab for running cron job and to store its O/P in one .txt file
#* * * * * /usr/bin/sudo -u admin -i bash -c /Users/Swapnil/Documents/checkimg.sh > /Users/Swapnil/Documents/cron_output.log 2>&1
# Example for the Docker Hub V2 API
# Returns all images and tags associated with a Docker Hub organization account.
# Requires 'jq': https://stedolan.github.io/jq/
# set username, password, and organization
# Filepath where your docker-compose file is present
FILEPATH="/Users/Swapnil/Documents/lamp-alpine"
# Your Docker hub user name
UNAME="ur username"
# Your Docker hub user password
UPASS="ur pwd"
# e.g organisation_name/image_name:image_tag
ORG="ur org name"
IMGNAME="ur img name"
IMGTAG="ur img tag"
# Container name
CONTNAME="ur container name"
# Expected built mins
BUILDMINS="5"
#Generally cronjob frequency
CHECKTIME="5"
NETWORKNAME="${IMGNAME}_private-network"
#After Image pulling, need to bring up all docker services?
DO_DOCKER_COMPOSE_UP=true
# -------
echo "Eecuting Script @ date and time in YmdHMS: $(date +%Y%m%d%H%M%S)"
set -e
PIDFILE=/Users/Swapnil/Documents/$IMGNAME/forever.pid
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "Process already running"
exit 1
else
## Process not found assume not running
echo $$
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
else
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
# Check Docker is running or not; If not runing then exit
if docker info|grep Containers ; then
echo "Docker is running"
else
echo "Docker is not running"
rm $PIDFILE
exit 1
fi
# Check Container is running or not; and set variable
CONT_INFO=$(docker ps -f "name=$CONTNAME" --format "{{.Names}}")
if [ "$CONT_INFO" = "$CONTNAME" ]; then
echo "Container is running"
IS_CONTAINER_RUNNING=true
else
echo "Container is not running"
IS_CONTAINER_RUNNING=false
fi
# get token
echo "Retrieving token ..."
TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${UNAME}'", "password": "'${UPASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)
# get list of repositories
echo "Retrieving repository list ..."
REPO_LIST=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/?page_size=100 | jq -r '.results|.[]|.name')
# output images & tags
echo "Images and tags for organization: ${ORG}"
echo
for i in ${REPO_LIST}
do
echo "${i}:"
# tags
IMAGE_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${i}/tags/?page_size=100 | jq -r '.results|.[]|.name')
for j in ${IMAGE_TAGS}
do
echo " - ${j}"
done
#echo
done
# Check Perticular image is the latest or not
#imm=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100)
echo "-----------------"
echo "Last built date details about Image ${IMGNAME} : ${IMGTAG} for organization: ${ORG}"
IMAGE_UPDATED_DATE=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100 | jq -r '.results|.[]|select(.name | contains("'${IMGTAG}'")).last_updated')
echo "On Docker Hub IMAGE_UPDATED_DATE---$IMAGE_UPDATED_DATE"
echo "-----------------"
IMAGE_CREATED_DATE=$(docker image inspect ${ORG}/${IMGNAME}:${IMGTAG} | jq -r '.[]|.Created')
echo "Locally IMAGE_CREATED_DATE---$IMAGE_CREATED_DATE"
updatedDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_UPDATED_DATE:0:16}" +%Y%m%d%H%M%S)
createdDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_CREATED_DATE:0:16}" +%Y%m%d%H%M%S)
currentDate=$(date +%Y%m%d%H%M%S)
start_date=$(date -jf "%Y%m%d%H%M%S" "$currentDate" "+%s")
end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
updiffMins=$(( ($start_date - $end_date) / (60) ))
if [[ "$updiffMins" -lt $(($CHECKTIME+1)) ]]; then
if [ ! -d "${FILEPATH}" ]; then
mkdir "${FILEPATH}";
fi
cd "${FILEPATH}"
pwd
echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
echo "Found after regular checking time -> Docker hub's latest updated image is new; Diff ${updiffMins} mins" >> "ScriptOutput_${currentDate}.txt"
echo "Script is checking for latest updates after every ${CHECKTIME} mins" >> "ScriptOutput_${currentDate}.txt"
echo "Fetching all new"
echo "---------------------------"
if $IS_CONTAINER_RUNNING ; then
echo "Container is running"
else
docker-compose down
echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
fi
echo "Image_Created_Date=$currentDate" > ".env"
echo "ORG=$ORG" >> ".env"
echo "IMGNAME=$IMGNAME" >> ".env"
echo "IMGTAG=$IMGTAG" >> ".env"
echo "CONTNAME=$CONTNAME" >> ".env"
echo "NETWORKNAME=$NETWORKNAME" >> ".env"
docker-compose build --no-cache
echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
if $DO_DOCKER_COMPOSE_UP ; then
docker-compose up -d
echo "Docker services are up now, checked in" >> "ScriptOutput_${currentDate}.txt"
else
echo "Docker services are down, checked in" >> "ScriptOutput_${currentDate}.txt"
fi
elif [[ "$updatedDate" -gt "$createdDate" ]]; then
echo "Updated is latest"
start_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
end_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
diffMins=$(( ($start_date - $end_date) / (60) ))
if [[ "$BUILDMINS" -lt "$diffMins" ]]; then
if [ ! -d "${FILEPATH}" ]; then
mkdir "${FILEPATH}";
fi
cd "${FILEPATH}"
pwd
echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
echo "Found after comparing times -> Docker hub's latest updated image is new; Diff ${diffMins} mins" >> "ScriptOutput_${currentDate}.txt"
echo "Actual image built time is less i.e. ${diffMins} mins than MAX expexted BUILD TIME i.e. ${BUILDMINS} mins" >> "ScriptOutput_${currentDate}.txt"
echo "Fetching all new" >> "ScriptOutput_${currentDate}.txt"
echo "-----------------------------"
if $IS_CONTAINER_RUNNING ; then
echo "Container is running"
else
docker-compose down
echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
fi
echo "Image_Created_Date=$currentDate" > ".env"
echo "ORG=$ORG" >> ".env"
echo "IMGNAME=$IMGNAME" >> ".env"
echo "IMGTAG=$IMGTAG" >> ".env"
echo "CONTNAME=$CONTNAME" >> ".env"
echo "NETWORKNAME=$NETWORKNAME" >> ".env"
docker-compose build --no-cache
echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
if $DO_DOCKER_COMPOSE_UP ; then
docker-compose up -d
echo "Docker services are up now" >> "ScriptOutput_${currentDate}.txt"
else
echo "Docker services are down" >> "ScriptOutput_${currentDate}.txt"
fi
elif [[ "$BUILDMINS" -gt "$diffMins" ]]; then
echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
echo "Docker images not fetched"
else
echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
echo "Docker images not fetched"
fi
elif [[ "$createdDate" -gt "$updatedDate" ]]; then
echo "Created is latest"
start_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
echo "Docker hub has older docker image than local; Older than $(( ($start_date - $end_date) / (60) ))mins"
fi
echo
echo "------------end---------------"
rm $PIDFILE
Here is my docker-compose file
version: "3.2"
services:
lamp-alpine:
build:
context: .
container_name: "${CONTNAME}"
image: "${ORG}/${IMGNAME}:${IMGTAG}"
ports:
- "127.0.0.1:80:80"
networks:
- private-network
networks:
private-network:
driver: bridge
I think we can go with MessageFormat.format
as it should be good at both readability and also performance aspects.
I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat
to explain the performance numbers.
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
}
end = System.currentTimeMillis();
System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
}
Concatenation = 69 millisecond
Format = 1435 millisecond
MessageFormat = 200 millisecond
UPDATES:
As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)
Because printf-style
format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style
format strings to their arguments when calling the format(...) methods of java.util.Formatter
, java.lang.String
, java.io.PrintStream
, MessageFormat
, and java.io.PrintWriter
classes and the printf(...)
methods of java.io.PrintStream
or java.io.PrintWriter
classes.
I replace the printf-style with the curly-brackets and I got something interesting results as below.
Concatenation = 69 millisecond
Format = 1107 millisecond
Format:curly-brackets = 416 millisecond
MessageFormat = 215 millisecond
MessageFormat:curly-brackets = 2517 millisecond
My Conclusion:
As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.
You need to add a CDATA tag inside of the script tag, unless you want to manually go through and escape all XHTML characters (e.g. &
would need to become &
). For example:
<script>
//<![CDATA[
var el = document.getElementById("pacman");
if (Modernizr.canvas && Modernizr.localstorage &&
Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
window.setTimeout(function () { PACMAN.init(el, "./"); }, 0);
} else {
el.innerHTML = "Sorry, needs a decent browser<br /><small>" +
"(firefox 3.6+, Chrome 4+, Opera 10+ and Safari 4+)</small>";
}
//]]>
</script>
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
RadioButton rb=(RadioButton)findViewById(checkedId);
textViewChoice.setText("You Selected " + rb.getText());
//Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
}
});
Current answers are either incomplete or inefficient. Here is (perhaps) the shortest way to achieve the outcome (using theme_void()
:
data(diamonds) # Data example
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
theme_void() + theme(legend.position="none")
The outcome is:
If you are interested in just eliminating the labels, labs(x="", y="")
does the trick:
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
labs(x="", y="")
So the 50x50 size is a good choice.
This link has more information:
https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
Connections have a close
method as specified in PEP-249 (Python Database API Specification v2.0):
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
Since the pyodbc
connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!
See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.
Note that unlike the original code, this causes conn.commit()
to be called. Use the outer with
statement to control when you want commit
to be called.
Also note that regardless of whether or not you use the with
statements, per the docs,
Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [
conn.close()
], but you can explicitly close the connection if you wish.
and similarly for cursors (my emphasis):
Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [
csr.close()
] is not usually necessary.
https://jsfiddle.net/xk6Ut/256/
One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement) document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
..
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}
This way the component isn't re-rendered when the parameter is added.
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
If the Node
is not just any node, but actually an Element
(it could also be e.g. an attribute or a text node), you can cast it to Element
and use getElementsByTagName
.
To create/change a root password in a running container
docker exec -itu root {containerName} passwd
Replace this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">
with
<button value=" Send" class="btn btn-success" type="submit" id="submit">
The hottest - and arguably most scalable - approach to overcoming these challenges with large datasets is embodied by the approach of Ionic's collectionRepeat directive and of other implementations like it. A fancy term for this is 'occlusion culling', but you can sum it up as: don't just limit the count of rendered DOM elements to an arbitrary (but still high) paginated number like 50, 100, 500... instead, limit only to as many elements as the user can see.
If you do something like what's commonly known as "infinite scrolling", you're reducing the initial DOM count somewhat, but it bloats quickly after a couple refreshes, because all those new elements are just tacked on at the bottom. Scrolling comes to a crawl, because scrolling is all about element count. There's nothing infinite about it.
Whereas, the collectionRepeat
approach is to use only as many elements as will fit in viewport, and then recycle them. As one element rotates out of view, it's detached from the render tree, refilled with data for a new item in the list, then reattached to the render tree at the other end of the list. This is the fastest way known to man to get new information in and out of the DOM, making use of a limited set of existing elements, rather than the traditional cycle of create/destroy... create/destroy. Using this approach, you can truly implement an infinite scroll.
Note that you don't have to use Ionic to use/hack/adapt collectionRepeat
, or any other tool like it. That's why they call it open-source. :-) (That said, the Ionic team is doing some pretty ingenious things, worthy of your attention.)
There's at least one excellent example of doing something very similar in React. Only instead of recycling the elements with updated content, you're simply choosing not to render anything in the tree that's not in view. It's blazing fast on 5000 items, although their very simple POC implementation allows a bit of flicker...
Also... to echo some of the other posts, using track by
is seriously helpful, even with smaller datasets. Consider it mandatory.
I will provide a detailed differences between Visual Studio and Visual Studio Code below.
If you really look at it the most obvious difference is that .NET has been split into two:
All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.
The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!
The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.
Visual Studio Code:
Visual Studio:
Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.
In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).
In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.
Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code
I found This simpler yet powerful tutorial which uses the fileReader
Object. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input
function previewFile() {_x000D_
var preview = document.querySelector('img');_x000D_
var file = document.querySelector('input[type=file]').files[0];_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onloadend = function () {_x000D_
preview.src = reader.result;_x000D_
}_x000D_
_x000D_
if (file) {_x000D_
reader.readAsDataURL(file);_x000D_
} else {_x000D_
preview.src = "";_x000D_
}_x000D_
}
_x000D_
<input type="file" onchange="previewFile()"><br>_x000D_
<img src="" height="200" alt="Image preview...">
_x000D_
For me an explicit set on the arguments section of the external tools configuration in Eclipse was the problem.
Though asynchronous style may be the nature of node.js and generally you should not do this, there are some times you want to do this.
I'm writing a handy script to check an API and want not to mess it up with callbacks.
Javascript cannot execute synchronous requests, but C libraries can.
=Format(Now(), "MM/dd/yyyy hh:mm tt")
Output:
04/12/2013 05:09 PM
Bootstrap >= v4.0 dropped glyphicon support
Dropped the Glyphicons icon font. If you need icons, some options are:
the upstream version of Glyphicons
Source: https://v4-alpha.getbootstrap.com/migration/#components
If you are using Bootstrap >= v4.0 or newer, you can use existing style classes of bootstrap such as text-success
,text-warning
etc.
For example, if you are using fontawesome:
<i class="fa fa-tag text-danger" aria-hidden="true"></i>
In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.
@Output() public eventName:EventEmitter = new EventEmitter();
to emit this event:
this.eventName.emit(payloadDataObject);
Change this property and try this at design time:
FormBorderStyle = FormBorderStyle.FixedDialog;
Designer view before the change:
This would also happen when you are trying to restore a newer version backup in a older SQL database. For example when you try to restore a DB backup that is created in 2012 with 110 compatibility and you are trying to restore it in 2008 R2.
You can update a Hive partition by, for example:
ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18)
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';
This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.
To drop a partition, you can do
ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);
Hope it helps!
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
"Are there any arguments I could use to help me convince him the for loop is acceptable to use?"
No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry.
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. You can use
$(window).on('load', function() {
// your code here
});
Which will wait until the page is loaded. $(document).ready()
waits until the DOM is loaded.
In plain JS:
window.addEventListener('load', function() {
// your code here
})
Template
<span date-now="MM/dd/yyyy"></span>
Directive
.directive('dateNow', ['$filter', function($filter) {
return {
link: function( $scope, $element, $attrs) {
$element.text($filter('date')(new Date(), $attrs.dateNow));
}
};
}])
Because you can't access the Date
object direcly in a template (for an inline solution), I opteted for this Directive. It also keeps your Controllers clean and is reusable.
In my opinion the best practice is to place the CSS file in the header
<head>
<link rel="stylesheet" href="css/layout.css" type="text/css">
</head>
and the Javascript file before the closing </body>
tag
<script type="text/javascript" src="script.js"></script>
</body>
Also if you have, like you said two CSS files. The browser would use both. If there were any selectors, ie. .content {}
that were the same in both CSS files the browser would overwrite the similar properties of the first one with the second one's properties. If that makes sense.
KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python
This answer from another forum solved the problem.
(substitute your own range for the "I:I" shown here)
Re: CountA not working in VBA
Should be:
Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))
You have to refer to ranges in the vba format, not the in-excel format.
element: HTMLElement;
constructor() {}
fakeClick(){
this.element = document.getElementById('ButtonX') as HTMLElement;
this.element.click();
}
That's the SHOW CREATE TABLE query. You can query the SCHEMA TABLES, too.
SHOW CREATE TABLE YourTableName;
Another possible solution: create an object containing the group names and indexes.
var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };
Then, use the object keys to reference the groups:
var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];
This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Even more, you can inherit generics :)
@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
return (T) somethingHolderMap.get(clazz);
}
You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.
http://www.cplusplus.com/reference/stl/vector/vector/
int size = 5; // declare the size of the vector
vector<int> myvector(size, 0); // create a vector to hold "size" int's
// all initialized to zero
myvector[0] = 1234; // assign values like a c++ array
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
select @i:=uuid();
update some_table set guid = (@i:=uuid());
I encountered today quite a similar problem : mysqldump dumped my utf-8 base encoding utf-8 diacritic characters as two latin1 characters, although the file itself is regular utf8.
For example : "é" was encoded as two characters "é". These two characters correspond to the utf8 two bytes encoding of the letter but it should be interpreted as a single character.
To solve the problem and correctly import the database on another server, I had to convert the file using the ftfy (stands for "Fixes Text For You). (https://github.com/LuminosoInsight/python-ftfy) python library. The library does exactly what I expect : transform bad encoded utf-8 to correctly encoded utf-8.
For example : This latin1 combination "é" is turned into an "é".
ftfy comes with a command line script but it transforms the file so it can not be imported back into mysql.
I wrote a python3 script to do the trick :
#!/usr/bin/python3
# coding: utf-8
import ftfy
# Set input_file
input_file = open('mysql.utf8.bad.dump', 'r', encoding="utf-8")
# Set output file
output_file = open ('mysql.utf8.good.dump', 'w')
# Create fixed output stream
stream = ftfy.fix_file(
input_file,
encoding=None,
fix_entities='auto',
remove_terminal_escapes=False,
fix_encoding=True,
fix_latin_ligatures=False,
fix_character_width=False,
uncurl_quotes=False,
fix_line_breaks=False,
fix_surrogates=False,
remove_control_chars=False,
remove_bom=False,
normalization='NFC'
)
# Save stream to output file
stream_iterator = iter(stream)
while stream_iterator:
try:
line = next(stream_iterator)
output_file.write(line)
except StopIteration:
break
By using T-SQL and cursors like this :
DECLARE @MyCursor CURSOR;
DECLARE @MyField YourFieldDataType;
BEGIN
SET @MyCursor = CURSOR FOR
select top 1000 YourField from dbo.table
where StatusID = 7
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @MyField
WHILE @@FETCH_STATUS = 0
BEGIN
/*
YOUR ALGORITHM GOES HERE
*/
FETCH NEXT FROM @MyCursor
INTO @MyField
END;
CLOSE @MyCursor ;
DEALLOCATE @MyCursor;
END;
TO give the prefill value in HTML Side as below:
HTML:
<input type="text" id="abc" value="any value">
JQUERY:
$(document).ready(function ()
{
$("#abc").val('any value');
});
Your code is blanking out your file:
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)
if you want to read the file in, you will need to use csv.reader and open the file for reading.
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
print line
If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).
For MySQL, use:
DESCRIBE name_of_table;
This also works for Oracle as long as you are using SQL*Plus, or Oracle's SQL Developer.
You can try joda-time.
You need to pass the variable into the function:
$data = 'My data';
function menugen($data)
{
echo $data;
}
When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:
{1, "one"}
{2, "two"}
{30, "thirty"}
You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.
After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.
This works perfectly in 2 steps.
Set your body tag to be like this <body ontouchstart="">
. I'm not a fan of this "hack", but it allows Safari on iOS to react to touches instantly. Not sure how, but it works.
Set up your touchable class like this:
// I did this in SASS, but this should work with normal CSS as well
// Touchable class
.example {
// Default styles
background: green;
// Default hover styles
// (Think of this as Desktop and larger)
&:hover {
background: yellow;
}
// Default active styles
&:active {
background: red;
}
// Setup breakpoint for smaller device widths
@media only screen and (max-width: 1048px) {
// Important!
// Reset touchable hover styles
// You may want to use the same exact styles as the Default styles
&:hover {
background: green;
}
// Important!
// Touchable active styles
&:active {
background: red;
}
}
}
You may want to remove any animation on your touchable class as well. Android Chrome seems to be a little slower than iOS.
This will also result in the active state being applied if the user scrolls the page while touching your class.
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
How about some plain and straighforward Java
List<Customer> list ...;
List<Customer> newList = new ArrayList<>();
for (Customer c : list){
if (c.getName().equals("dd")) newList.add(c);
}
Simple, readable and easy (and works in Android!) But if you're using Java 8 you can do it in a sweet one line:
List<Customer> newList = list.stream().filter(c -> c.getName().equals("dd")).collect(toList());
Note that toList() is statically imported
Android now provides ExtendedFloatingActionButton which does the same thing for you.
The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066
, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).
However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>
. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.
The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:
$.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
$('#orderDetails').html(data);
}, 'script')
Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:
<% @restaurant.orders.each do |order| %>
<!-- you should add more class and id attr to help control the DOM -->
<tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id %>);">
<td class="order_id"><%= order.id %></td>
<td class="customer_id"><%= order.customer_id %></td>
<td class="status"><%= order.status %></td>
</tr>
<% end %>
js:
function orderModal(order_id){
var tr = $('#order_' + order_id);
// get the current info in html table
var customer_id = tr.find('.customer_id');
var status = tr.find('.status');
// U should work on lines here:
var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
$('#orderDetails').html(info_to_insert);
$('#orderModal').modal({
keyboard: true,
backdrop: "static"
});
};
That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.
RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone
<ListView
android:listSelector="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
/>
Taken directly from an answer to this post: How to get the screen size in Tkinter?
import tkinter as tk
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
XCode 11.0+.
It's really simple now. Just go to Project Navigator
left panel of the XCode window.
Press Enter
to make it active for rename, just like you change the folder name.
Just change the new name here, and XCode will ask you for renaming other pieces of stuff.
Tap on Rename
here and you are done.
If you are confused about your root folder name that why it's not changed, well it's just a folder. just renamed it with a new name.
Both provided solutions did not work for me;
> SELECT setval('seq', 0);
ERROR: setval: value 0 is out of bounds for sequence "seq" (1..9223372036854775807)
setval('seq', 1)
starts the numbering with 2, and ALTER SEQUENCE seq START 1
starts the numbering with 2 as well, because seq.is_called is true (Postgres version 9.0.4)
The solution that worked for me is:
> ALTER SEQUENCE seq RESTART WITH 1;
> UPDATE foo SET id = DEFAULT;
You can use COPY. You need to specify the directory explicitly. It won't be created by itself
COPY go /usr/local/go
Reference: Docker CP reference
This makes it so if before there was a scrollbar then it makes it so the scrollbar has a display of none so you can't see it anymore. You can replace html to body or a class or ID. Hope it works for you :)
html::-webkit-scrollbar {
display: none;
}
I would recommend using mysqldump and from php use the system command as suggested in the article you found.
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
I was getting the same error about the SSL certificate when Maven tried to download the necessary modules automatically.
As a remedy, I was attempting to implement Luke's answer above, but found that the DigiCert Global Root CA certificate is already in Java's trusted keystore.
What helped me was adding %JAVA_HOME%\bin
to the Path variable (I am running Windows). And %JAVA_HOME%
is a JDK location, not just a JRE location, since Maven needs a JDK.
I am not certain why it helped, but it did. I am absolutely sure that this was the only thing I changed.
The exact value is sizeof(a).
You might also take a risk and assume that it is in this case no less than 2 and no greater than 16.
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>
).
You want to deserialize into a single RootObject
.
Even though I am 3 years late, but to simplify Guffa's example, you don't even need to have the form on the page at all:
$('<form method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something">
...
</form>').submit();
Edited:
$('<form method="post" action="test.asp" target="TheWindow">
<input type="hidden" name="something" value="something">
...
</form>').appendTo('body').submit().remove();
Maybe a helpful tip for someone :)
$cfg['Servers'][$i]['AllowNoPassword'] = false;
The accepted answer didn't work for me, I had to add a value to the href attribute:
<link rel="shortcut icon" href="#" />
I have used RxPY which has some nice threading functions to solve this in a fairly clean manner. No queues, and I have provided a function that runs on the main thread after completion of the background thread. Here is a working example:
import rx
from rx.scheduler import ThreadPoolScheduler
import time
import tkinter as tk
class UI:
def __init__(self):
self.root = tk.Tk()
self.pool_scheduler = ThreadPoolScheduler(1) # thread pool with 1 worker thread
self.button = tk.Button(text="Do Task", command=self.do_task).pack()
def do_task(self):
rx.empty().subscribe(
on_completed=self.long_running_task,
scheduler=self.pool_scheduler
)
def long_running_task(self):
# your long running task here... eg:
time.sleep(3)
# if you want a callback on the main thread:
self.root.after(5, self.on_task_complete)
def on_task_complete(self):
pass # runs on main thread
if __name__ == "__main__":
ui = UI()
ui.root.mainloop()
Another way to use this construct which might be cleaner (depending on preference):
tk.Button(text="Do Task", command=self.button_clicked).pack()
...
def button_clicked(self):
def do_task(_):
time.sleep(3) # runs on background thread
def on_task_done():
pass # runs on main thread
rx.just(1).subscribe(
on_next=do_task,
on_completed=lambda: self.root.after(5, on_task_done),
scheduler=self.pool_scheduler
)
Save this xml and add as a background for the linear layout....
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
Hope this helps! :)
You have to put the selector.xml file in the drwable folder.
Then write:
android:background="@drawable/selector"
.
This takes care of the pressed and focussed states.
None of the solutions above worked for me because I was using Formik and I needed to mark the field "touched" along with changing the field value. Following code worked for me.
const emailField = orderPageWrapper.find('input[name="email"]')
emailField.simulate('focus')
emailField.simulate('change', { target: { value: '[email protected]', name: 'email' } })
emailField.simulate('blur')
I have handled back and Home button in Navigation Drawer like
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
NavigationView navigationView;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
//showing first fragment on Start
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//listener for home
if(id==android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Begin the transaction
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_companies_list) {
fragment = new FirstFragment();
// Handle the action
}
// Begin the transaction
if(fragment!=null){
if(item.isChecked()){
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.WikiCompany, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
drawerToggle.setDrawerIndicatorEnabled(false);
else
drawerToggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
and In each onViewCreated
I call
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).updateDrawerIcon();
((HomeActivity) getActivity()).setActionBarTitle("List");
}
If the files all have the same name or can be matched by find
, you can do (e.g.):
find . -name create.sh | xargs tail -n +1
to find, show the path of and cat each file.
ThreadLocal + SimpleDateFormat = SimpleDateFormatThreadSafe
package com.foocoders.text;
import java.text.AttributedCharacterIterator;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class SimpleDateFormatThreadSafe extends SimpleDateFormat {
private static final long serialVersionUID = 5448371898056188202L;
ThreadLocal<SimpleDateFormat> localSimpleDateFormat;
public SimpleDateFormatThreadSafe() {
super();
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat();
}
};
}
public SimpleDateFormatThreadSafe(final String pattern) {
super(pattern);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
}
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) {
super(pattern, formatSymbols);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern, formatSymbols);
}
};
}
public SimpleDateFormatThreadSafe(final String pattern, final Locale locale) {
super(pattern, locale);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern, locale);
}
};
}
public Object parseObject(String source) throws ParseException {
return localSimpleDateFormat.get().parseObject(source);
}
public String toString() {
return localSimpleDateFormat.get().toString();
}
public Date parse(String source) throws ParseException {
return localSimpleDateFormat.get().parse(source);
}
public Object parseObject(String source, ParsePosition pos) {
return localSimpleDateFormat.get().parseObject(source, pos);
}
public void setCalendar(Calendar newCalendar) {
localSimpleDateFormat.get().setCalendar(newCalendar);
}
public Calendar getCalendar() {
return localSimpleDateFormat.get().getCalendar();
}
public void setNumberFormat(NumberFormat newNumberFormat) {
localSimpleDateFormat.get().setNumberFormat(newNumberFormat);
}
public NumberFormat getNumberFormat() {
return localSimpleDateFormat.get().getNumberFormat();
}
public void setTimeZone(TimeZone zone) {
localSimpleDateFormat.get().setTimeZone(zone);
}
public TimeZone getTimeZone() {
return localSimpleDateFormat.get().getTimeZone();
}
public void setLenient(boolean lenient) {
localSimpleDateFormat.get().setLenient(lenient);
}
public boolean isLenient() {
return localSimpleDateFormat.get().isLenient();
}
public void set2DigitYearStart(Date startDate) {
localSimpleDateFormat.get().set2DigitYearStart(startDate);
}
public Date get2DigitYearStart() {
return localSimpleDateFormat.get().get2DigitYearStart();
}
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
return localSimpleDateFormat.get().format(date, toAppendTo, pos);
}
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
return localSimpleDateFormat.get().formatToCharacterIterator(obj);
}
public Date parse(String text, ParsePosition pos) {
return localSimpleDateFormat.get().parse(text, pos);
}
public String toPattern() {
return localSimpleDateFormat.get().toPattern();
}
public String toLocalizedPattern() {
return localSimpleDateFormat.get().toLocalizedPattern();
}
public void applyPattern(String pattern) {
localSimpleDateFormat.get().applyPattern(pattern);
}
public void applyLocalizedPattern(String pattern) {
localSimpleDateFormat.get().applyLocalizedPattern(pattern);
}
public DateFormatSymbols getDateFormatSymbols() {
return localSimpleDateFormat.get().getDateFormatSymbols();
}
public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) {
localSimpleDateFormat.get().setDateFormatSymbols(newFormatSymbols);
}
public Object clone() {
return localSimpleDateFormat.get().clone();
}
public int hashCode() {
return localSimpleDateFormat.get().hashCode();
}
public boolean equals(Object obj) {
return localSimpleDateFormat.get().equals(obj);
}
}
If you do not mind recursive functions, here is a solution. I have also taken the liberty to include an exclusion-parameter in case there are one or more values you wish to maintain.
Code:
def flatten_dict(dictionary, exclude = [], delimiter ='_'):
flat_dict = dict()
for key, value in dictionary.items():
if isinstance(value, dict) and key not in exclude:
flatten_value_dict = flatten_dict(value, exclude, delimiter)
for k, v in flatten_value_dict.items():
flat_dict[f"{key}{delimiter}{k}"] = v
else:
flat_dict[key] = value
return flat_dict
Usage:
d = {'a':1, 'b':[1, 2], 'c':3, 'd':{'a':4, 'b':{'a':7, 'b':8}, 'c':6}, 'e':{'a':1,'b':2}}
flat_d = flatten_dict(dictionary=d, exclude=['e'], delimiter='.')
print(flat_d)
Output:
{'a': 1, 'b': [1, 2], 'c': 3, 'd.a': 4, 'd.b.a': 7, 'd.b.b': 8, 'd.c': 6, 'e': {'a': 1, 'b': 2}}
Hi if you are using react-router v-6.0.0-beta or V6 in This version Redirect Changes to Navigate like this
import { Navigate } from 'react-router-dom'; // like this CORRECT in v6 import { Redirect } from 'react-router-dom'; // like this CORRECT in v5
import { Redirect } from 'react-router-dom'; // like this WRONG in v6 // This will give you error in V6 of react-router and react-router dom
please make sure use both same version in package.json { "react-router": "^6.0.0-beta.0", //Like this "react-router-dom": "^6.0.0-beta.0", // like this }
this above things only works well in react Router Version 6
Note: only use this approach for images that are private and will always be!
The ssh key remains stored within the image, even if you remove the key in a layer command after adding it (see comments in this post).
In my case this is ok, so this is what I am using:
# Setup for ssh onto github
RUN mkdir -p /root/.ssh
ADD id_rsa /root/.ssh/id_rsa
RUN chmod 700 /root/.ssh/id_rsa
RUN echo "Host github.com\n\tStrictHostKeyChecking no\n" >> /root/.ssh/config
You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
The source for the MultipartFile save to disk.
File file = new File(directory, filename);
// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);
// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
Here is another way. No intermediate variables are saved.
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
I had same Problem when i was trying to create executable from program that having no main() method. When i included sample main() method like this
int main(){
return 0;
}
It solved
Since all lists are already "sorted" by the order the items were added (FIFO ordering), you can "resort" them with another order, including the natural ordering of elements, using java.util.Collections.sort()
.
EDIT:
Lists as data structures are based in what is interesting is the ordering in which the items where inserted.
Sets do not have that information.
If you want to order by adding time, use List
. If you want to order by other criteria, use SortedSet
.
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
As others have noted, you need to declare a variable global
in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global
.
To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global
in the function.
Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global
in the function.
d = {}
l = []
o = type("object", (object,), {})()
def valid(): # these are all valid without declaring any names global!
d[0] = 1 # changes what's in d, but d still points to the same object
d[0] += 1 # ditto
d.clear() # ditto! d is now empty but it`s still the same object!
l.append(0) # l is still the same list but has an additional member
o.test = 1 # creating new attribute on o, but o is still the same object
I solve such queries using this pattern:
SELECT *
FROM t
WHERE t.field=(
SELECT MAX(t.field)
FROM t AS t0
WHERE t.group_column1=t0.group_column1
AND t.group_column2=t0.group_column2 ...)
That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:
WITH site_history AS (
SELECT sites.siteName, sites.siteIP, history.date
FROM sites
JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
SELECT MAX(date)
FROM site_history h0
WHERE h.siteName=h0.siteName)
ORDER BY siteName
It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date
field should be unique for each siteName
, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history
table has an unique index for (site, date)
, this query is also very fast, index range scan on the history
table scanning just the first item can be used.
This is what I use to upload the image through upload window:
//open upload window
upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
done
I needed this for SQL Server. Here it is:
UPDATE user_account
SET student_education_facility_id = cnt.education_facility_id
from (
SELECT user_account_id,education_facility_id
FROM user_account
WHERE user_type = 'ROLE_TEACHER'
) as cnt
WHERE user_account.user_type = 'ROLE_STUDENT' and cnt.user_account_id = user_account.teacher_id
I think it works with other RDBMSes (please confirm). I like the syntax because it's extensible.
The format I needed was this actually:
UPDATE table1
SET f1 = cnt.computed_column
from (
SELECT id,computed_column --can be any complex subquery
FROM table1
) as cnt
WHERE cnt.id = table1.id
This incorporates the comments on Algorias' answer, and compares objects by a single attribute because I don't care about the whole dict. hasattr(other, "id")
must be true, but I know it is because I set it in the constructor.
def __eq__(self, other):
if other is self:
return True
if type(other) is not type(self):
# delegate to superclass
return NotImplemented
return other.id == self.id
In HTML there's an autofocus
attribute to all form fields. There's a good tutorial on it in Dive Into HTML 5. Unfortunately it's currently not supported by IE versions less than 10.
To use the HTML 5 attribute and fall back to a JS option:
<input id="my-input" autofocus="autofocus" />
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("my-input").focus();
}
</script>
No jQuery, onload or event handlers are required, because the JS is below the HTML element.
Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers.
Edit 2: Firefox 4 now supports the autofocus
attribute, just leaving IE without support.
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()_x000D_
{_x000D_
// Get the src of the image_x000D_
var src = $(this).attr("src");_x000D_
_x000D_
// Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
$.post("/backend.php", {"img": src});_x000D_
});
_x000D_
CREATE TABLE sometable (t TIMESTAMP, d DATE);
INSERT INTO sometable SELECT '2011/05/26 09:00:00';
UPDATE sometable SET d = t; -- OK
-- UPDATE sometable SET d = t::date; OK
-- UPDATE sometable SET d = CAST (t AS date); OK
-- UPDATE sometable SET d = date(t); OK
SELECT * FROM sometable ;
t | d
---------------------+------------
2011-05-26 09:00:00 | 2011-05-26
(1 row)
Another test kit:
SELECT pg_catalog.date(t) FROM sometable;
date
------------
2011-05-26
(1 row)
SHOW datestyle ;
DateStyle
-----------
ISO, MDY
(1 row)
A simple solution would be to just write
this.date = new Date().toLocaleDateString();
date .toLocaleDateString()
time .toLocaleTimeString()
both .toLocaleString()
Hope this helps.
Put this in your header, so it will be available whenever you need it.
var base_url = "<?php echo base_url();?>";
You will get http://localhost:81/your-path-file
or http://localhost/your-path-file
.
This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.
Easier to use and good debugging tools.
This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.
this.print(false);
You can use this simply:
I'm using this function to check if the input int number is between 20 and 30
static boolean isValidInput(int input) {
return (input >= 20 && input <= 30);
}
npm-install-peers worked for me.
npm install -g npm-install-peers
A Null pointer has the value 0. void pointer is a generic pointer introduced by ANSI. Generic pointer can hold the address of any data type.
If more precisely, you should use this condition:
if (array_search(__FILE__, get_included_files()) === 0) {
echo 'direct access';
}
else {
echo 'included';
}
get_included_files() returns indexed array containing names of all included files (if file is beign executed then it was included and its name is in the array). So, when the file is directly accessed, its name is the first in the array, all other files in the array were included.
You can get the diff for a stash with "git show stash@{0}
" (or whatever the number of the stash is; see "git stash list"). It's easy to extract the section of the diff for a single file.
$model=User::where('id',$id)->delete();
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
Make as shown.
$(document).ready(function(){_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
$('#myBtn').on('click', function(){_x000D_
$('#myModal').modal('show');_x000D_
});_x000D_
_x000D_
});_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Activate Modal with JavaScript</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Yes Its a old question but it might help some
import csv
import uuid
# read and write csv files
with open('in_file','r') as r_csvfile:
with open('out_file','w',newline='') as w_csvfile:
dict_reader = csv.DictReader(r_csvfile,delimiter='|')
#add new column with existing
fieldnames = dict_reader.fieldnames + ['ADDITIONAL_COLUMN']
writer_csv = csv.DictWriter(w_csvfile,fieldnames,delimiter='|')
writer_csv.writeheader()
for row in dict_reader:
row['ADDITIONAL_COLUMN'] = str(uuid.uuid4().int >> 64) [0:6]
writer_csv.writerow(row)
Add the below dependency to your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
This answer is to iterate over selected columns as well as all columns in a DF.
df.columns
gives a list containing all the columns' names in the DF. Now that isn't very helpful if you want to iterate over all the columns. But it comes in handy when you want to iterate over columns of your choosing only.
We can use Python's list slicing easily to slice df.columns according to our needs. For eg, to iterate over all columns but the first one, we can do:
for column in df.columns[1:]:
print(df[column])
Similarly to iterate over all the columns in reversed order, we can do:
for column in df.columns[::-1]:
print(df[column])
We can iterate over all the columns in a lot of cool ways using this technique. Also remember that you can get the indices of all columns easily using:
for ind, column in enumerate(df.columns):
print(ind, column)
Guess I'm too late...
Came across the same problem today; here is my solution using FileSystemObject
:
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String
fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close
Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
Just install the m2e plugin for Eclipse. Then a new command in Eclipse's Import statement will be added called "Import existing maven projects".
Print the PDF header (using header() function) like:
header("Content-type: application/pdf");
and then just echo the content of the PDF file you created (instead of writing it to disk).
Javascript arrays have a length property. Use it like this:
st.itemb.length
Additionally there is a possibility to set a list of properties that will get transitioned by setting the property transition-property: width, height;
, more details here
For anyone who is reaching here and is not able to solve their issue, I used to make my widget horizontally center by setting both right and left to 0 like below:
Stack(
children: <Widget>[
Positioned(
top: 100,
left: 0,
right: 0,
child: Text("Search",
style: TextStyle(
color: Color(0xff757575),
fontWeight: FontWeight.w700,
fontFamily: "Roboto",
fontStyle: FontStyle.normal,
fontSize: 56.0),
textAlign: TextAlign.center),
),
]
)
To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?
Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.
In C++11 you can. A note beforehand: Don't new
the array, there's no need for that.
First, string[] strArray
is a syntax error, that should either be string* strArray
or string strArray[]
. And I assume that it's just for the sake of the example that you don't pass any size parameter.
#include <string>
void foo(std::string* strArray, unsigned size){
// do stuff...
}
template<class T>
using alias = T;
int main(){
foo(alias<std::string[]>{"hi", "there"}, 2);
}
Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
Note that this will only match stack arrays, like int x[5] = ...
. Or temporary ones, created by the use of alias
above.
int main(){
foo(alias<int[]>{1, 2, 3});
}
you also should specify def name in the project settings here:
Configuration > Properties/Input/Advanced/Module > Definition File
For texts in angular template (userType
is property of $scope, like $scope.userType):
<span>
{{userType=='admin' ? 'Edit' : 'Show'}}
</span>
HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:
DivX Web Player (NPAPI browsers only)
And here is the HTML:
<embed id="divxplayer" type="video/divx" width="1024" height="768"
src ="path_to_file" autoPlay=\"true\"
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.
You might have source code of a dependency accessible to Eclipse. But Eclipse does not know for source code for code that is dynamically loaded. E.g. through Maven.
In case of Maven, I recommend that you use run-jetty-run plugin:
http://code.google.com/p/run-jetty-run/
As a workaround you can also connect to a running JVM with the debugger and you will see the code. Alternatively you can use Dynamic Source Lookup plugin for Eclipse from here:
https://github.com/ifedorenko/com.ifedorenko.m2e.sourcelookup
Unfortunately it didn't helped me as it has issues with Windows paths with spaces.
I have filled an enhancement request on Eclipse Bugzilla and if you agree this issue "Source not found" should vanish forever, please vote for it here:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=384065
Thanks!
Sasa