I have faced similar issue when importing on mac.i have python 3.7.3 installed Following steps helped me resolve it:
Import dns
Import dns.resolver
You could try:
$j('div.contextualError.ckgcellphone').css('display')
Based upon your comments - your path
statement has been changed/is incorrect or the path
variable is being incorrectly used for another purpose.
This works for SQL Server Management Studio v18.0
The file "SqlStudio.bin" doesn't seem to exist any longer. Instead my settings are all stored in this file:
C:\Users\*********\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
<Element>.......</Element>
block
that surrounds it.To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program
Sub runpython()
Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub
In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
I did something very similar. I created my property behind the scenes that enabled the selection of a combobox ONLY if it had finished searching for data. When my window first appears, it launches an async loaded command but I do not want the user to click on the combobox while it is still loading data (would be empty, then would be populated). So by default the property is false so I return the inverse in the getter. Then when I'm searching I set the property to true and back to false when complete.
private bool _isSearching;
public bool IsSearching
{
get { return !_isSearching; }
set
{
if(_isSearching != value)
{
_isSearching = value;
OnPropertyChanged("IsSearching");
}
}
}
public CityViewModel()
{
LoadedCommand = new DelegateCommandAsync(LoadCity, LoadCanExecute);
}
private async Task LoadCity(object pArg)
{
IsSearching = true;
//**Do your searching task here**
IsSearching = false;
}
private bool LoadCanExecute(object pArg)
{
return IsSearching;
}
Then for the combobox I can bind it directly to the IsSearching:
<ComboBox ItemsSource="{Binding Cities}" IsEnabled="{Binding IsSearching}" DisplayMemberPath="City" />
I just tried to get path of shared preferences below like this.This is work for me.
File f = getDatabasePath("MyPrefsFile.xml");
if (f != null)
Log.i("TAG", f.getAbsolutePath());
Automatic Package Restore will fail for any of the following reasons:
The following article outlines in more detail how to go about points 1-3: https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore
Edit To reflect what @Marc said in the comment below.
You can do a loop through all the posted values.
HTML:
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
PHP:
foreach($_POST['check_list'] as $item){
// query to delete where item = $item
}
I had the same problem running on Windows 8 running on 64bit. Apache is really slow but when you press F5 many times it goes ok. In the end i after doing many things managed to solve it. Right now it works fast.
Try the following tasks to increase the performance:
Change listening port from 80 to 8080 to avoid conflicts with programs like Skype. Open your httpd.conf file and find the line that starts with Listen
(it's around line 62). Change it like the following:
Listen 127.0.0.1:8080
Change your power plan from Balanced to High Performance. You can do this in Control Panel\All Control Panel Items\Power Options
The credits of this particular task go to Jef where he pointed this out in his blog post. From the Windows 8 desktop, press the Windows Key
and the R key
at the same time
Type regedit in the Run dialog box and click OK
Use Registry Editor to expand the registry tree and browse to:
\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TCPIP6\Parameters
Right click on Parameters
, expand New
, and select DWORD (32-bit)
Value
Enter DisabledComponents
into the Name
field
Double click on the new DisabledComponents
value, enter ffffffff
into the Value data
dialog box, and click the OK
button
Confirm the new registry value contains the required data.
If you use virtual hosts don't add each virtual host on a new line. Instead list them like the following.
127.0.0.1 site-a site-b site-c
I also added 127.0.0.1 127.0.0.1
since I heard this somehow improves the lookup as well. (Can't confirm this but it can't hurt putting it there)
Your hosts file is located at C:\Windows\System32\Drivers\etc
In my case I had two apache processes running. Be sure you only have one running. You can check this by pressing CTRL+ALT+DEL
and press Task Manager
What I find to be working a bit as well was turning off the Base Filtering Engine. Since stopping or disabling the BFE service will significantly reduce the security of the system you should only do this when needed.
Go to Control Panel => Administrative Tools => Services => Base Filtering Engine
Stop the Base Filtering Engine by clicking on Stop
To to your task manager and change Apache's process priority from Normal to High by right clicking -> Set priority -> High
This is a bit of an ugly method but it does certainly work. It keeps Apache busy and will process your own requests faster. Insert your local web-address in the iframe location and save it in a html file, run it and just leave it there until you're done.
<html>
<head>
<script>
setTimeout(function(){
window.location.reload(1);
}, 2000);
</script>
</head>
<body>
<iframe name="iframe" id="iframe" src="http://mywebsite:8080"></iframe>
</body>
</html>
As a Windows 8 Pro user you are entitled to have downgrade rights to Windows 7. Read here more about this. For me that was the only solution that really did the job properly.
Good luck!
It looks like the documentation is just using readStream()
to mean:
Ok, we've shown you how to get the InputStream, now your code goes in
readStream()
So you should either write your own readStream()
method which does whatever you wanted to do with the data in the first place.
As explained in Nawaz's answer, you cannot sort your map by itself as you need it, because std::map
sorts its elements based on the keys only. So, you need a different container, but if you have to stick to your map, then you can still copy its content (temporarily) into another data structure.
I think, the best solution is to use a std::set
storing flipped key-value pairs as presented in ks1322's answer.
The std::set
is sorted by default and the order of the pairs is exactly as you need it:
3) If
lhs.first<rhs.first
, returnstrue
. Otherwise, ifrhs.first<lhs.first
, returnsfalse
. Otherwise, iflhs.second<rhs.second
, returnstrue
. Otherwise, returnsfalse
.
This way you don't need an additional sorting step and the resulting code is quite short:
std::map<std::string, int> m; // Your original map.
m["realistically"] = 1;
m["really"] = 8;
m["reason"] = 4;
m["reasonable"] = 3;
m["reasonably"] = 1;
m["reassemble"] = 1;
m["reassembled"] = 1;
m["recognize"] = 2;
m["record"] = 92;
m["records"] = 48;
m["recs"] = 7;
std::set<std::pair<int, std::string>> s; // The new (temporary) container.
for (auto const &kv : m)
s.emplace(kv.second, kv.first); // Flip the pairs.
for (auto const &vk : s)
std::cout << std::setw(3) << vk.first << std::setw(15) << vk.second << std::endl;
Output:
1 realistically
1 reasonably
1 reassemble
1 reassembled
2 recognize
3 reasonable
4 reason
7 recs
8 really
48 records
92 record
Note: Since C++17 you can use range-based for loops together with structured bindings for iterating over a map. As a result, the code for copying your map becomes even shorter and more readable:
for (auto const &[k, v] : m)
s.emplace(v, k); // Flip the pairs.
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.
There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.
Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.
HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.
Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.
The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.
(Updated to cover implications of making the connection SSL-only.)
Basically, an application pool is a way to create compartments in a web server through process boundaries, and route sets of URLs to each of these compartments. See more info here: http://technet.microsoft.com/en-us/library/cc735247(WS.10).aspx
Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .Add, target: self,
action: #selector(addNewFireflyRefernce))
}
func addNewFireflyReference() {
gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
}
To Enter into crontab :
crontab -e
write this into the file:
0 */2 * * * python/php/java yourfilepath
Example :0 */2 * * * python ec2-user/home/demo.py
and make sure you have keep one blank line after the last cron job in your crontab file
This means your nested SELECT returns more than one rows.
You need to add a proper WHERE clause to it.
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);
days + hours
. Minutes are not included.hh:mm
or x hours y minutes
, would require additional calculations and string formatting.timedelta
math, and is faster than using .astype('timedelta64[h]')
timedelta
objects: See supported operations.datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
.total_xx
methods.# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
dateutil
maintainer:
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
(df.from_date - df.to_date).dt.total_seconds() / 3600
dateutil
module provides powerful extensions to the standard datetime
module.%%timeit
testimport pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS
name to another DNS
name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).
A CNAME
record is for aliasing www.example.com
-> www.example.com.herokudns.com.
You can't use CNAME
for a naked domain (@
), i.e. example.com
(unless you find a name server that can do CNAME Flattening
- which is what I did).
But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record
that does this: www.example.com -> www.example.com.herokudns.com
.
And then create a permanent 301 redirect from example.com
to www.example.com
.
This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com
. @Jonathan Roy talks about this (above) but provides a bad link.
Weirdest way I can think of doing this is:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
Where:
My suggestion, use a while or for loop ;-)
You must write
<img src="theSource" style="width:30px;height:30px;" />
Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.
Besides from removing the framework from the Podfile
and Linked Frameworks and Libraries
, I also had to remove the reference to the framework in Other Linker Flags
.
If your browser supports CSS3, try using the CSS element Calc()
height: calc(100% - 65px);
you might also want to adding browser compatibility options:
height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */
also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622
For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual
CURDATE()
returns the DATE part of the current time. Manual on CURDATE()
NOW()
returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().
There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:
public class OptionalEx {
private boolean isPresent;
private OptionalEx(boolean isPresent) {
this.isPresent = isPresent;
}
public void orElse(Runnable runner) {
if (!isPresent) {
runner.run();
}
}
public static <T> OptionalEx ifPresent(Optional<T> opt, Consumer<? super T> consumer) {
if (opt.isPresent()) {
consumer.accept(opt.get());
return new OptionalEx(true);
}
return new OptionalEx(false);
}
}
Then you can use a static import elsewhere to get syntax that is close to what you're after:
import static com.example.OptionalEx.ifPresent;
ifPresent(opt, x -> System.out.println("found " + x))
.orElse(() -> System.out.println("NOT FOUND"));
If legend_out
is set to True
then legend is available thought g._legend
property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
sns.plt.show()
Another situation if legend_out
is set to False
. You have to define which axes has a legend (in below example this is axis number 0):
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = False)
# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
Moreover you may combine both situations and use this code:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# check axes and find which is have legend
for ax in g.axes.flat:
leg = g.axes.flat[0].get_legend()
if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend
# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
This code works for any seaborn plot which is based on Grid
class.
You used %H
(24 hour format) instead of %I
(12 hour format).
With angular 4 you can fix this issue by updating app.module.ts file as follows:
Add import statement at the top as below:
import {APP_BASE_HREF} from '@angular/common';
And add below line inside @NgModule
providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
I just done multi level sorting based on custom requirement.
//sort the values
[arrItem sortUsingComparator:^NSComparisonResult (id a, id b){
ItemDetail * itemA = (ItemDetail*)a;
ItemDetail* itemB =(ItemDetail*)b;
//item price are same
if (itemA.m_price.m_selling== itemB.m_price.m_selling) {
NSComparisonResult result= [itemA.m_itemName compare:itemB.m_itemName];
//if item names are same, then monogramminginfo has to come before the non monograme item
if (result==NSOrderedSame) {
if (itemA.m_monogrammingInfo) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}
return result;
}
//asscending order
return itemA.m_price.m_selling > itemB.m_price.m_selling;
}];
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.
In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.
Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.
If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.
Some applications will actually open up /dev/tty
to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty
(creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.
int val = '1' - '0';
This can be done using ascii codes where '0' is the lowest and the number characters count up from there
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};?
cd /the/lib/dir/of/your/perl/installation
perldoc $(find . -name perllocal.pod)
Windows users just do a Windows Explorer search to find it.
The Light,
You can configure the process acting as the client to use fiddler as a proxy.
Fiddler sets itself up as a proxy conveniently on 127.0.0.1:8888, and by default overrides the system settings under Internet Options in the Control Panel (if you've configured any) such that all traffic from the common protocols (http, https, and ftp) goes to 127.0.0.1:8888 before leaving your machine.
Now these protocols are often from common processes such as browsers, and so are easily picked up by fiddler. However, in your case, the process initiating the requests is probably not a browser, but one for a programming language like php.exe, or java.exe, or whatever language you are using.
If, say, you're using php, you can leverage curl. Ensure that the curl module is enabled, and then right before your code that invokes the request, include:
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
Hope this helps. You can also always lookup stuff like so from the fiddler documentation for a basis for you to build upon e.g. http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigurePHPcURL
Swift 3 / Swift 4 solution that also works with NIBs/XIB files in iOS 10+:
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
}
The above answers require you to malloc a new stream object.
public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {
for (final T z : c) {
if (p.test(z)) {
return true;
}
}
return false;
}
public boolean containsTabById(TabPane tabPane, String id) {
return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
...
}
You should be able to find your command with a ps
variant like:
ps -ef
ps -fubob # if your job's user ID is bob.
Then, once located, it should be a simple matter to use kill
to kill the process (permissions permitting).
If you're talking about getting rid of jobs in the at
queue (that aren't running yet), you can use atq
to list them and atrm
to get rid of them.
Take a look at http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
Basically you declare error handler which will call rollback
START TRANSACTION;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
EXIT PROCEDURE;
END;
COMMIT;
Actually a name can be used however it cannot have spaces so
window.open("../myPage","MyWindows",...)
should work with no problem (window.open).
No, there isn't such constant.
In RStudio, to increase:
file.edit(file.path("~", ".Rprofile"))
then in .Rprofile type this and save
invisible(utils::memory.limit(size = 60000))
To decrease: open .Rprofile
invisible(utils::memory.limit(size = 30000))
save and restart RStudio.
Assuming bash:
~> declare -a foo
~> foo[0]="foo"
~> foo[1]="bar"
~> foo[2]="baz"
~> echo ${#foo[*]}
3
So, ${#ARRAY[*]}
expands to the length of the array ARRAY
.
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
First, we need to filter the XML so as to parse that into an object
$response = strtr($xml_string, ['</soap:' => '</', '<soap:' => '<']);
$output = json_decode(json_encode(simplexml_load_string($response)));
var_dump($output->Body->PaymentNotification->payment);
Try this it will work --
if($('#EventStartTimeMin').val() === " ") {
alert("Please enter start time!");
}
In addition to what the asker's own answer already stated, it may be worth noting the following. The reason this happens is because it is possible for a class to have a method with the same signature as an interface method without implementing that method. The following code illustrates that:
public interface IFoo
{
void DoFoo();
}
public class Foo : IFoo
{
public void DoFoo() { Console.WriteLine("This is _not_ the interface method."); }
void IFoo.DoFoo() { Console.WriteLine("This _is_ the interface method."); }
}
Foo foo = new Foo();
foo.DoFoo(); // This calls the non-interface method
IFoo foo2 = foo;
foo2.DoFoo(); // This calls the interface method
There is a built in method for doing this:
numpy.where()
You can find out more about it in the excellent detailed documentation.
Firstly,the crash reason is decorView's index is -1,we can knew it from Android source code ,there is code snippet:
class:android.view.WindowManagerGlobal
file:WindowManagerGlobal.java
private int findViewLocked(View view, boolean required) {
final int index = mViews.indexOf(view);
//here, view is decorView,comment by OF
if (required && index < 0) {
throw new IllegalArgumentException("View=" + view + " not attached to window manager");
}
return index;
}
so we get follow resolution,just judge decorView's index,if it more than 0 then continue or just return and give up dismiss,code as follow:
try {
Class<?> windowMgrGloable = Class.forName("android.view.WindowManagerGlobal");
try {
Method mtdGetIntance = windowMgrGloable.getDeclaredMethod("getInstance");
mtdGetIntance.setAccessible(true);
try {
Object windownGlobal = mtdGetIntance.invoke(null,null);
try {
Field mViewField = windowMgrGloable.getDeclaredField("mViews");
mViewField.setAccessible(true);
ArrayList<View> mViews = (ArrayList<View>) mViewField.get(windownGlobal);
int decorViewIndex = mViews.indexOf(pd.getWindow().getDecorView());
Log.i(TAG,"check index:"+decorViewIndex);
if (decorViewIndex < 0) {
return;
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.
Regarding:
var button = document.getElementById(/* Button client id */);
button.click();
It should be like:
var button = document.getElementById('<%=formID.ClientID%>');
Where formID is the ASP.NET control ID in the .aspx file.
The best solution I found so far is setting a footer element at the bottom of the page and then evaluate the difference of the offset of the footer and the element we need to expand. e.g.
<div id="contents"></div>
<div id="footer"></div>
#footer {
position: fixed;
bottom: 0;
width: 100%;
}
var contents = $('#contents');
var footer = $('#footer');
contents.css('height', (footer.offset().top - contents.offset().top) + 'px');
You might also like to update the height of the contents element on each window resize, so...
$(window).on('resize', function() {
contents.css('height', (footer.offset().top -contents.offset().top) + 'px');
});
If you haven't commit the local changes yet since the last pull/clone, you can use:
git checkout *
git pull
checkout
will clear your local changes with the last local commit, and
pull
will sincronize it to the remote repository
Yes, it is case-sensitive. You can do a case-insensitive indexOf
by converting your String and the String parameter both to upper-case before searching.
String str = "Hello world";
String search = "hello";
str.toUpperCase().indexOf(search.toUpperCase());
Note that toUpperCase may not work in some circumstances. For instance this:
String str = "Feldbergstraße 23, Mainz";
String find = "mainz";
int idxU = str.toUpperCase().indexOf (find.toUpperCase ());
int idxL = str.toLowerCase().indexOf (find.toLowerCase ());
idxU will be 20, which is wrong! idxL will be 19, which is correct. What's causing the problem is tha toUpperCase() converts the "ß" character into TWO characters, "SS" and this throws the index off.
Consequently, always stick with toLowerCase()
You can use Visual Studio for Android Development. See a nice article on it here
Here is a kind of snippet for you:
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json').then(function(r) { return Session.data = r.data;});
}
};
Session.updateSession();
return Session;
});
Here is Plunker example how you can use that: http://plnkr.co/edit/Fg3uF4ukl5p88Z0AeQqU?p=preview
2020 Simple way :
git reset <commit_hash>
(The commit hash of the last commit you want to keep).
If the commit was pushed, you can then do :
git push -f
You will keep the now uncommitted changes locally
Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
if (e1.getKey().equals(e2.getKey())) {
return res; // Code will now handle equality properly
} else {
return res != 0 ? res : 1; // While still adding all entries
}
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)
Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.
You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load
method of your Test.aspx.cs
file.
I experienced this today and I just do a:
12345@123456 MINGW64 ~/development/workspace/test (develop)
$ git status
Refresh index: 100% (1204/1204), done.
On branch develop
Your branch is up to date with 'origin/develop'.
nothing to commit, working tree clean
12345@123456 MINGW64 ~/development/workspace/test (develop)
$ git fetch
Then all worked again.
String key= "services_servicename"
ArrayList<String> data;
for(int i = 0; i lessthen data.size(); i++) {
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
servicesNameHashmap.put(key,data.get(i).getServiceName());
mServiceNameArray.add(i,servicesNameHashmap);
}
I have got the Best Results.
You just have to create new HashMap
like
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
in your for
loop. It will have same effect like same key and multiple values.
S3 doesn't have a folder structure, But there is something called as keys.
We can create /2013/11/xyz.xls
and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.
Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects
method and using the Prefix
parameter.
git push --tags production
Please note that if you have multiple application.properties
files throughout your codebase, then try adding your value to the parent project's property file.
You can check your project's pom.xml
file to identify what the parent project of your current project is.
Alternatively, try using environment.getProperty()
instead of @Value
.
button.setOnClickListener {
//write your code here
}
You either need to create an object of type Beta in the Alpha class or its method
Like you do here in the Main Beta cBeta = new Beta();
If you want to use the variable you create in your Main then you have to parse it to cAlpha as a parameter by making the Alpha constructor look like
public class Alpha
{
Beta localInstance;
public Alpha(Beta _beta)
{
localInstance = _beta;
}
public void DoSomethingAlpha()
{
localInstance.DoSomethingAlpha();
}
}
You can use the https://graph.facebook.com/v3.0/{Place_your_Page_ID here}/feed?fields=id,shares,share_count&access_token={Place_your_access_token_here} to get the shares count.
(this answer is not useful, but leaving it here since some of the comments may be)
docker images
will show the 'virtual size', i.e. how much in total including all the lower layers. So some double-counting if you have containers that share the same base image.
It happens mostly when JQuery
is not installed in your project.
Install JQuery in your project by following commands according to your package manager.
yarn add jquery
npm i jquery --save
After this just import $
in your project file.
import $ from 'jquery'
In your scenario, you can have a look at asp.net membership, it is good practice to store user's password as hashed string in the database. you can authenticate the user by comparing the hashed incoming password with the one stored in the database.
Everything has been built for this purposes, check out asp.net membership
@echo off
set array=
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set nl=^&echo(
set array=auto blue ^!nl!^
bycicle green ^!nl!^
buggy red
echo convert the String in indexed arrays
set /a index=0
for /F "tokens=1,2,3*" %%a in ( 'echo(!array!' ) do (
echo(vehicle[!index!]=%%a color[!index!]=%%b
set vehicle[!index!]=%%a
set color[!index!]=%%b
set /a index=!index!+1
)
echo use the arrays
echo(%vehicle[1]% %color[1]%
echo oder
set index=1
echo(!vehicle[%index%]! !color[%index%]!
With System.getProperty("user.dir")
you get the "Base of non-absolute paths" look at
I am just doing this without even trying it. Would this work?
myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");
Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).
For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:
HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Product>(data);
}
This way my content is parsed into a JSON string and then I convert it to my object.
If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.
stages {
stage('Nginx') {
when { changeset "nginx/*"}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
}
}
You can combine multiple conditions using anyOf
or allOf
keywords for OR or AND behaviour accordingly:
when {
anyOf {
changeset "nginx/**"
changeset "fluent-bit/**"
}
}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
Or, as @PhillipCloud suggested, just days.astype(int)
since the timedelta
is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D'
, 'ns'
, ...).
You can find more about it here.
Snagged from Oracle OTN forums
Use alter table to add column, for example:
alter table tableName add(columnName NUMBER);
Then create a sequence:
CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;
and, the use update
to insert values in column like this
UPDATE tableName SET columnName = seq_test_id.NEXTVAL
What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.
What you need is a dynamic include:
<jsp:include page="..." />
Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.
Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.
All you need is to POST
to the auth/login
URL a form-encoded blob with the various fields you see there (forget the labels for
, they're decoration for human visitors). handle=whatever&password-clear=pwd
and so on, as long as you know the values for the handle (AKA email) and password you should be fine.
Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie
header validating your session (be sure to save that cookie and send it back on further interaction along the session!).
from the website: Latest version supports:
and others, so try it now!
In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.
If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.
#include <stdio.h>
#include <stdlib.h>
void handle_line(char *line) {
printf("%s", line);
}
int main(int argc, char *argv[]) {
int size = 1024, pos;
int c;
char *buffer = (char *)malloc(size);
FILE *f = fopen("myfile.txt", "r");
if(f) {
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f);
if(c != EOF) buffer[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer = (char*)realloc(buffer, size);
}
}while(c != EOF && c != '\n');
buffer[pos] = 0;
// line is now in buffer
handle_line(buffer);
} while(c != EOF);
fclose(f);
}
free(buffer);
return 0;
}
To each his own but the right way to code this is to rename the columns inserting underscore so there are no gaps. This will ensure zero errors when coding. When printing the column names for public display you could search-and-replace to replace the underscore with a space.
For Visual Studio users:
Heroku links your projects based on the heroku
git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command:
git remote add heroku [email protected]:project.git
where project
is the name of your Heroku project (the same as the project.heroku.com
subdomain). Once you've done so, you can use the heroku xxxx
commands (assuming you have the Heroku Toolbelt installed), and can push to Heroku as usual via git push heroku master
. As a shortcut, if you're using the command line tool, you can type:
heroku git:remote -a project
where, again, project
is the name of your Heroku project (thanks, Colonel Panic). You can name the Git remote anything you want by passing -r remote_name
.
[Update]
As mentioned by Ben in the comments, the remote doesn't need to be named heroku
for the gem commands to work. I checked the source, and it appears it works like this:
--app
option (e.g. heroku info --app myapp
), it will use that app.--remote
option (e.g. heroku info --remote production
), it will use the app associated with that Git remote.heroku.remote
set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use git config heroku.remote production
in your repository, and Heroku will run git config heroku.remote
to read the value of this setting).git/config
file, and the gem only finds one remote in your Git remotes that has "heroku.com" in the URL, it will use that remote.--app
to your command.I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.
You can convert like this.
date = datetime.datetime.strptime('2019-3-16T5-49-52-595Z','%Y-%m-%dT%H-%M-%S-%f%z')
date_time = date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
SQL supports qualifying a column by prefixing the reference with either the full table name:
SELECT tbl_names.id, tbl_section.id, name, section
FROM tbl_names
JOIN tbl_section ON tbl_section.id = tbl_names.id
...or a table alias:
SELECT n.id, s.id, n.name, s.section
FROM tbl_names n
JOIN tbl_section s ON s.id = n.id
The table alias is the recommended approach -- why type more than you have to?
Secondly, my answers use ANSI-92 JOIN syntax (yours is ANSI-89). While they perform the same, ANSI-89 syntax does not support OUTER joins (RIGHT, LEFT, FULL). ANSI-89 syntax should be considered deprecated, there are many on SO who will not vote for ANSI-89 syntax to reinforce that. For more information, see this question.
Kotlin Solution:
For custom class save in onSaveInstanceState
you can be converted your class to JSON
string and restore it with Gson
convertion and for single String, Double, Int, Long
value save and restore as following. The following example is for Fragment
and Activity
:
For Activity:
For put data in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
//for custom class-----
val gson = Gson()
val json = gson.toJson(your_custom_class)
outState.putString("CUSTOM_CLASS", json)
//for single value------
outState.putString("MyString", stringValue)
outState.putBoolean("MyBoolean", true)
outState.putDouble("myDouble", doubleValue)
outState.putInt("MyInt", intValue)
}
Restore data:
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
//for custom class restore
val json = savedInstanceState?.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
testBundle = gson.fromJson(json, Session::class.java)
}
//for single value restore
val myBoolean: Boolean = savedInstanceState?.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState?.getDouble("myDouble")
val myInt: Int = savedInstanceState?.getInt("MyInt")
val myString: String = savedInstanceState?.getString("MyString")
}
You can restore it on Activity onCreate
also.
For fragment:
For put class in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val gson = Gson()
val json = gson.toJson(customClass)
outState.putString("CUSTOM_CLASS", json)
}
Restore data:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
//for custom class restore
if (savedInstanceState != null) {
val json = savedInstanceState.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
val customClass: CustomClass = gson.fromJson(json, CustomClass::class.java)
}
}
// for single value restore
val myBoolean: Boolean = savedInstanceState.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState.getDouble("myDouble")
val myInt: Int = savedInstanceState.getInt("MyInt")
val myString: String = savedInstanceState.getString("MyString")
}
I just received this obscure message when trying to deploy a report from BIDS.
After a little hunting I found a more descriptive error by going into the Preview window.
Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.
https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY
Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.
If you want user readable data but still detailed, you can use platform.platform()
>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'
platform
also has some other useful methods:
>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'
Here's a few different possible calls you can make to identify where you are
import platform
import sys
def linux_distribution():
try:
return platform.linux_distribution()
except:
return "N/A"
print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))
The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version
e.g. Solaris on sparc gave:
Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')
MAKE THIS YOUR config.js file code
CKEDITOR.editorConfig = function( config ) {
// config.enterMode = 2; //disabled <p> completely
config.enterMode = CKEDITOR.ENTER_BR // pressing the ENTER KEY input <br/>
config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
config.autoParagraph = false; // stops automatic insertion of <p> on focus
};
It isn't possible to do it the way you've defined ldap_get
. However, if you define ldap_get
like this:
def ldap_get ( base_dn, filter, attrs=nil, scope=LDAP::LDAP_SCOPE_SUBTREE )
Now you can:
ldap_get( base_dn, filter, X )
But now you have problem that you can't call it with the first two args and the last arg (the same problem as before but now the last arg is different).
The rationale for this is simple: Every argument in Ruby isn't required to have a default value, so you can't call it the way you've specified. In your case, for example, the first two arguments don't have default values.
I added below Path in environment variable
;%JAVA_HOME%/bin instead of %JAVA_HOME%\bin
in my case , it fix the problem
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
Throws:
Use multipart/mixed
with the first part as multipart/alternative
and subsequent parts for the attachments. In turn, use text/plain
and text/html
parts within the multipart/alternative
part.
A capable email client should then recognise the multipart/alternative
part and display the text part or html part as necessary. It should also show all of the subsequent parts as attachment parts.
The important thing to note here is that, in multipart MIME messages, it is perfectly valid to have parts within parts. In theory, that nesting can extend to any depth. Any reasonably capable email client should then be able to recursively process all of the message parts.
By now, cloud bitbucket (I'm not sure which version) allows to revert a commit from the file system as follows (I do not see how to revert from the Bitbucket interface in the Chrome browser).
-backup your entire directory to secure the changes you inadvertently committed
-select checked out directory
-right mouse button: tortoise git menu
-repo-browser (the menu option 'revert' only undoes the uncommited changes)
-press the HEAD button
-select the uppermost line (the last commit)
-right mouse button: revert change by this commit
-after it undid the changes on the file system, press commit
-this updates GIT with a message 'Revert (your previous message). This reverts commit so-and-so'
-select 'commit and push'.
See this resultant operator was opposite to the Timezone .So apply some math function then validate the num less or more.
var a = new Date().getTimezoneOffset();_x000D_
_x000D_
var res = -Math.round(a/60)+':'+-(a%60);_x000D_
res = res < 0 ?res : '+'+res;_x000D_
_x000D_
console.log(res)
_x000D_
Suppose you have this file:
something
name
comment
phone
email
something else
and more ...
You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.
:%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
The c
flag will prompt you for confirmation. You can drop that if you don't want the prompt.
Probable simplest and generally efficient:
#include <iostream>
int main()
{
std::cout << std::cin.rdbuf();
}
If needed, use stream of other types like std::ostringstream
as buffer instead of standard output stream here.
To select the ith
row, use iloc
:
In [31]: df_test.iloc[0]
Out[31]:
ATime 1.2
X 2.0
Y 15.0
Z 2.0
Btime 1.2
C 12.0
D 25.0
E 12.0
Name: 0, dtype: float64
To select the ith value in the Btime
column you could use:
In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2
df_test['Btime'].iloc[0]
(recommended) and df_test.iloc[0]['Btime']
:DataFrames store data in column-based blocks (where each block has a single
dtype). If you select by column first, a view can be returned (which is
quicker than returning a copy) and the original dtype is preserved. In contrast,
if you select by row first, and if the DataFrame has columns of different
dtypes, then Pandas copies the data into a new Series of object dtype. So
selecting columns is a bit faster than selecting rows. Thus, although
df_test.iloc[0]['Btime']
works, df_test['Btime'].iloc[0]
is a little bit
more efficient.
There is a big difference between the two when it comes to assignment.
df_test['Btime'].iloc[0] = x
affects df_test
, but df_test.iloc[0]['Btime']
may not. See below for an explanation of why. Because a subtle difference in
the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:
df.iloc[0, df.columns.get_loc('Btime')] = x
df.iloc[0, df.columns.get_loc('Btime')] = x
(recommended):The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,
df.loc[df.index[n], 'Btime'] = x
or
df.iloc[n, df.columns.get_loc('Btime')] = x
The latter method is a bit faster, because df.loc
has to convert the row and column labels to
positional indices, so there is a little less conversion necessary if you use
df.iloc
instead.
df['Btime'].iloc[0] = x
works, but is not recommended:Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime']
always returns a
view (not a copy) so df['Btime'].iloc[n] = x
can be used to assign a new value
at the nth location of the Btime
column of df
.
Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning
even though in this case the assignment succeeds in modifying df
:
In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
In [26]: df
Out[26]:
foo bar
0 A 99 <-- assignment succeeded
2 B 100
1 C 100
df.iloc[0]['Btime'] = x
does not work:In contrast, assignment with df.iloc[0]['bar'] = 123
does not work because df.iloc[0]
is returning a copy:
In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
In [67]: df
Out[67]:
foo bar
0 A 99 <-- assignment failed
2 B 100
1 C 100
Warning: I had previously suggested df_test.ix[i, 'Btime']
. But this is not guaranteed to give you the ith
value since ix
tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i]
will return the row labeled i
rather than the ith
row. For example,
In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [2]: df
Out[2]:
foo
0 A
2 B
1 C
In [4]: df.ix[1, 'foo']
Out[4]: 'C'
sha1sum is quite a bit faster on Power9 than md5sum
$ uname -mov
#1 SMP Mon May 13 12:16:08 EDT 2019 ppc64le GNU/Linux
$ cat /proc/cpuinfo
processor : 0
cpu : POWER9, altivec supported
clock : 2166.000000MHz
revision : 2.2 (pvr 004e 1202)
$ ls -l linux-master.tar
-rw-rw-r-- 1 x x 829685760 Jan 29 14:30 linux-master.tar
$ time sha1sum linux-master.tar
10fbf911e254c4fe8e5eb2e605c6c02d29a88563 linux-master.tar
real 0m1.685s
user 0m1.528s
sys 0m0.156s
$ time md5sum linux-master.tar
d476375abacda064ae437a683c537ec4 linux-master.tar
real 0m2.942s
user 0m2.806s
sys 0m0.136s
$ time sum linux-master.tar
36928 810240
real 0m2.186s
user 0m1.917s
sys 0m0.268s
If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:
Switch to branch "foo" and update it:
$ git checkout foo
$ git pull
You can see the branches you've got by issuing command:
$ git branch
The question is correctly answered here Center a column using Twitter Bootstrap 3
For odd rows: i.e., col-md-7 or col-large-9 use this
Add col-centered to the column you want centered.
<div class="col-lg-11 col-centered">
And add this to your stylesheet:
.col-centered{
float: none;
margin: 0 auto;
}
For even rows: i.e., col-md-6 or col-large-10 use this
Simply use bootstrap 3's offset col class. i.e.,
<div class="col-lg-10 col-lg-offset-1">
As Android is working on a single thread, you should not do any network operation on the main thread. There are various ways to avoid this.
Use the following way to perform a network operation
Never use StrictMode.setThreadPolicy(policy), as it will freeze your UI and is not at all a good idea.
string ImagePath = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
string a = "";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
if (receiveStream.CanRead)
{ a = "OK"; }
}
catch { }
http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
Here is a more modular and cleaner way to circle crop your bitmap in Glide:
BitmapTransformation
then override transform
method like this : For Glide 4.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {}
}
For Glide 3.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public String getId() {
// Return some id that uniquely identifies your transformation.
return "CircularTransformation";
}
}
Glide.with(yourActivity)
.load(yourUrl)
.asBitmap()
.transform(new CircularTransformation())
.into(yourView);
Hope this helps :)
$(window).on("scroll", function() {
//get height of the (browser) window aka viewport
var scrollHeight = $(document).height();
// get height of the document
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
// code to run when scroll to bottom of the page
}
});
This is the code on github.
String str_date = "11-June-07";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = formatter.parse(str_date);
You can check out this blog post. It had solved my problem.
http://dotnetguts.blogspot.com/2010/06/restore-failed-for-server-restore.html
Select @@Version
It had given me following output Microsoft SQL Server 2005 - 9.00.4053.00 (Intel X86) May 26 2009 14:24:20 Copyright (c) 1988-2005 Microsoft Corporation Express Edition on Windows NT 6.0 (Build 6002: Service Pack 2)
You will need to re-install to a new named instance to ensure that you are using the new SQL Server version.
There are no values that will cause the checkbox to be unchecked. If the checked
attribute exists, the checkbox will be checked regardless of what value you set it to.
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).
Made some optimizations to Travis' Linkify()
code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. [email protected]).
In addition, I changed the implementation to prototype the String
class so that items can be matched like so:
var text = '[email protected]';
text.linkify();
'http://stackoverflow.com/'.linkify();
Anyway, here's the script:
if(!String.linkify) {
String.prototype.linkify = function() {
// http://, https://, ftp://
var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
// www. sans http:// or https://
var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
// Email addresses
var emailAddressPattern = /[\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+/gim;
return this
.replace(urlPattern, '<a href="$&">$&</a>')
.replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
.replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
};
}
Why not just use simple javascript?
var array=[1,2,3,4];
var lastEl = array[array.length-1];
You can write it as a method too, if you like (assuming prototype has not been included on your page):
Array.prototype.last = function() {return this[this.length-1];}
If you want to get the strings separated by the ,
you can use
string b = a.Split(',')[0];
This is a PDO-only visualization, as the mysql_*
library is deprecated.
<?php
// Begin Vault (this is in a vault, not actually hard-coded)
$host="hostname";
$username="GuySmiley";
$password="thePassword";
$dbname="dbname";
$port="3306";
// End Vault
try {
$dbh = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "I am connected.<br/>";
// ... continue with your code
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>
Note that this OP Question appeared not to be about port numbers afterall. If you are using the default port of 3306
always, then consider removing it from the uri, that is, remove the port=$port;
part.
If you often change ports, consider the above port usage for more maintainability having changes made to the $port
variable.
Some likely errors returned from above:
PDO Exception: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
PDO Exception: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.
In the below error, we are at least getting closer, after changing our connect information:
PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)
After further changes, we are really close now, but not quite:
PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'
From the Manual on PDO Connections:
On Windows 10 Add this to your Path:
%APPDATA%\npm
This references the folder ~/AppData/Roaming/npm
[Assumes that you have already run npm install -g grunt-cli
]
According to 3.9 version of Docker compose, you can use image: myapp:tag
to specify name and tag.
version: "3.9"
services:
webapp:
build:
context: .
dockerfile: Dockerfile
image: webapp:tag
Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/
I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)
The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.
it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.
if you do this with the code below you will see that
var selectBox = document.getElementById("selectBox");
gets put in a box and stays there you don't do anything with it afterwards.
and
var selectBox = document.getElementById("selectBox");
is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag
your code works until you add to it or modify it then you can easily loose track and get all mixed up
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
a leaner way that works also is:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.
<script type="text/javascript">
function Mapit(){
var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;
alert(actualPostcode);
// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map
}
</script>
<select id="getPostcodes" onchange="Mapit();">
<option>London North Inner</option>
<option>N1</option>
<option>London North Outer</option>
<option>N2</option>
<option>N3</option>
<option>N4</option>
// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes
</select>
Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.
If you're on GNU Make, use the :=
assignment instead of =
. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.
FILES := $(shell ...) # expand now; FILES is now the result of $(shell ...)
FILES = $(shell ...) # expand later: FILES holds the syntax $(shell ...)
If you use the =
assignment, it means that every single occurrence of $(FILES)
will be expanding the $(shell ...)
syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.
void inPlaceStrTrim(char* str) {
int k = 0;
int i = 0;
for (i=0; str[i] != '\0';) {
if (isspace(str[i])) {
// we have got a space...
k = i;
for (int j=i; j<strlen(str)-1; j++) {
str[j] = str[j+1];
}
str[strlen(str)-1] = '\0';
i = k; // start the loop again where we ended..
} else {
i++;
}
}
}
http://www.unicode.org is the place to look for symbol names.
? BLACK CIRCLE 25CF
? MEDIUM BLACK CIRCLE 26AB
? BLACK LARGE CIRCLE 2B24
or even:
NEW MOON SYMBOL 1F311
Good luck finding a font that supports them all. Only one shows up in Windows 7 with Chrome.
This method is even easier if you're ok with fewer options:
FileCopy source, destination
This issue is still open here: https://github.com/docker/compose/issues/2925
You can set hostname but it is not reachable from other containers. So it is mostly useless.
I couldn't leave this question here with out a single statement using the modulo operator.
def rot13(s):
return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
or x.isupper() and ((ord(x) - 52) % 26) + 65
or ord(x))
for x in s])
This is not pythonic nor good practice, but it works!
>> rot13("Hello World!")
Uryyb Jbeyq!
Use svn merge:
svn merge -c -[rev num that deleted the file] http://<path to repository>
So an example:
svn merge -c -12345 https://svn.mysite.com/svn/repo/project/trunk
^ The negative is important
For TortoiseSVN (I think...)
That is completely untested, however.
Edited by OP: This works on my version of TortoiseSVN (the old kind without the next button)
The trick is to merge backwards. Kudos to sean.bright for pointing me in the right direction!
Edit: We are using different versions. The method I described worked perfectly with my version of TortoiseSVN.
Also of note is that if there were multiple changes in the commit you are reverse merging, you'll want to revert those other changes once the merge is done before you commit. If you don't, those extra changes will also be reversed.
VBA uses a garbage collector which is implemented by reference counting.
There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook
creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.
Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Besides using the INFORMATION_SCHEMA table, to use SHOW TABLES to insert into a table you would use the following
<?php
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
$arrayCount = 0
while ($row = mysql_fetch_row($result)) {
$tableNames[$arrayCount] = $row[0];
$arrayCount++; //only do this to make sure it starts at index 0
}
foreach ($tableNames as &$name {
$query = "INSERT INTO metadata (table_name) VALUES ('".$name."')";
mysql_query($query);
}
?>
ngStyle
accepts a map:
$scope.myStyle = {
"width" : "900px",
"background" : "red"
};
We can use the get_locale
function:
if (get_locale() == 'en_GB') {
// drink tea
}
For arrays you can use:
Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
And you can use LINQ as well:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
There are times that using OPTION(RECOMPILE)
makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:
EXEC sp_updatestats
And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.
Adding OPTION(RECOMPILE)
rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy
but maybe we are just using different terms for the same thing.
When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.
In summary - I don't see any reason that OPTION(RECOMPILE)
would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.
And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.
The Solution to your problem is :
echo " Some Text Goes Here " > filename.txt
But you can use cat command if you want to redirect the output of a file to some other file or if you want to append the output of a file to another file :
cat filename > newfile -- To redirect output of filename to newfile
cat filename >> newfile -- To append the output of filename to newfile
You might be interested in itertools.product
, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)
yields all values of the form (a, b)
, where the a
values come from A
and the b
values come from B
. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product
is the "inner" one. Generally, itertools.product(a0, a1, ... an)
is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]
If you are using Ubuntu 14.04 ffmpeg
is not available. You can install it by using the instructions directly from https://www.ffmpeg.org/download.html.
In short you will have to:
sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg
If this does not work maybe try using sudo apt-get dist-upgrade
but this may broke things in your system.
You don't need JavaScript for this.
Some CSS would do it. Here is an example:
<html>_x000D_
<style type="text/css">_x000D_
.section { background:#ccc; }_x000D_
.layer { background:#ddd; }_x000D_
.section:hover img { border:2px solid #333; }_x000D_
.section:hover .layer { border:2px solid #F90; }_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="section">_x000D_
<img src="myImage.jpg" />_x000D_
<div class="layer">Lorem Ipsum</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Short answer:
Remove (from list results
)
results.RemoveAll(r => r.ID == 2);
will remove the item with ID 2 in results
(in place).
Filter (without removing from original list results
):
var filtered = result.Where(f => f.ID != 2);
returns all items except the one with ID 2
Detailed answer:
I think .RemoveAll()
is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.
If you have:
class myClass {
public int ID; public string FirstName; public string LastName;
}
and assigned some values to results
as follows:
var results = new List<myClass> {
new myClass { ID=1, FirstName="Bill", LastName="Smith" }, // results[0]
new myClass { ID=2, FirstName="John", LastName="Wilson" }, // results[1]
new myClass { ID=3, FirstName="Doug", LastName="Berg" }, // results[2]
new myClass { ID=4, FirstName="Bill", LastName="Wilson" } // results[3]
};
Then you can define a list of IDs to remove:
var removeList = new List<int>() { 2, 3 };
And simply use this to remove them:
results.RemoveAll(r => removeList.Any(a => a==r.ID));
It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList
. Note that this happens in place, so there is no additional assigment required.
Of course, you can also use it on single items like:
results.RemoveAll(r => r.ID==4);
where it will remove Bill with ID 4 in our example.
A last thing to mention is that lists have an indexer, that is, they can also be accessed like a dynamic array, i.e. results[3]
will give you the 4th element in the results list (because the first element has the index 0, the 2nd has index 1 etc).
So if you want to remove all entries where the first name is the same as in the 4th element of the results list, you can simply do it this way:
results.RemoveAll(r => results[3].FirstName == r.FirstName);
Note that afterwards, only John and Doug will remain in the list, Bill is removed (the first and last element in the example). Important is that the list will shrink automatically, so it has only 2 elements left - and hence the largest allowed index after executing RemoveAll in this example is 1
(which is results.Count() - 1
).
Some Trivia: You can use this knowledge and create a local function
void myRemove() { var last = results.Count() - 1;
results.RemoveAll(r => results[last].FirstName == r.FirstName); }
What do you think will happen, if you call this function twice? Like
myRemove(); myRemove();
The first call will remove Bill at the first and last position, the second call will remove Doug and only John Wilson remains in the list.
DotNetFiddle: Run the demo
Note: Since C# Version 8, you can as well write results[^1]
instead of var last = results.Count() - 1;
and results[last]
:
void myRemove() { results.RemoveAll(r => results[^1].FirstName == r.FirstName); }
So you would not need the local variable last
anymore (see indices and ranges. For a list of all the new features in C#, look here).
Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
This work for me:
#If VBA7 And Win64 Then
Private Declare PtrSafe Function ShellExecuteA Lib "Shell32.dll" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#Else
Private Declare Function ShellExecuteA Lib "Shell32.dll" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
#End If
Thanks Jon49 for insight.
Angular's own website serves simplified content to search engines: http://docs.angularjs.org/?_escaped_fragment_=/tutorial/step_09
Say your Angular app is consuming a Node.js/Express-driven JSON api, like /api/path/to/resource
. Perhaps you could redirect any requests with ?_escaped_fragment_
to /api/path/to/resource.html
, and use content negotiation to render an HTML template of the content, rather than return the JSON data.
The only thing is, your Angular routes would need to match 1:1 with your REST API.
EDIT: I'm realizing that this has the potential to really muddy up your REST api and I don't recommend doing it outside of very simple use-cases where it might be a natural fit.
Instead, you can use an entirely different set of routes and controllers for your robot-friendly content. But then you're duplicating all of your AngularJS routes and controllers in Node/Express.
I've settled on generating snapshots with a headless browser, even though I feel that's a little less-than-ideal.
Reloading your whole activity may be a heavy task. Just put the part of code that has to be refreshed in (kotlin):
override fun onResume() {
super.onResume()
//here...
}
Java:
@Override
public void onResume(){
super.onResume();
//here...
}
And call "onResume()" whenever needed.
You should have access to the POST dictionary on the request object.
For Oracle Java applications, add this after the ObjectMapper
instantiation:
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
The slice() method returns a copy of a portion of an array into a new array object.
$scope.participantForms.slice(index, 1);
This does NOT change the participantForms
array but returns a new array containing the single element found at the index
position in the original array.
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
$scope.participantForms.splice(index, 1);
This will remove one element from the participantForms
array at the index
position.
These are the Javascript native functions, AngularJS has nothing to do with them.
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
<?php
include 'cdb.php';
$show=mysqli_query( $conn,"SELECT *FROM 'reg'");
while($row1= mysqli_fetch_array($show))
{
$id=$row1['id'];
$Name= $row1['name'];
$email = $row1['email'];
$username = $row1['username'];
$password= $row1['password'];
$birthm = $row1['bmonth'];
$birthd= $row1['bday'];
$birthy= $row1['byear'];
$gernder = $row1['gender'];
$phone= $row1['phone'];
$image=$row1['image'];
}
?>
<html>
<head><title>hey</head></title></head>
<body>
<form>
<table border="-2" bgcolor="pink" style="width: 12px; height: 100px;" >
<th>
id<input type="text" name="" style="width: 30px;" value= "<?php echo $row1['id']; ?>" >
</th>
<br>
<br>
<th>
name <input type="text" name="" style="width: 60px;" value= "<?php echo $row1['Name']; ?>" >
</th>
<th>
email<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['email']; ?>" >
</th>
<th>
username<input type="hidden" name="" style="width: 60px;" value= "<?php echo $username['email']; ?>" >
</th>
<th>
password<input type="hidden" name="" style="width: 60px;" value= "<?php echo $row1['password']; ?>">
</ths>
<th>
birthday month<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthm']; ?>">
</th>
<th>
birthday day<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthd']; ?>">
</th>
<th>
birthday year<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['birthy']; ?>" >
</th>
<th>
gender<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['gender']; ?>">
</th>
<th>
phone number<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['phone']; ?>">
</th>
<th>
<th>
image<input type="text" name="" style="width: 60px;" value= "<?php echo $row1['image']; ?>">
</th>
<th>
<font color="pink"> <a href="update.php">update</a></font>
</th>
</table>
</body>
</form>
</body>
</html>
According to Rails guide, this one liner should be used because it would load from the schema.rb
instead of reloading the migration files one by one:
rake db:reset
Personally, I would prefer
<IF>
<TIME from="5pm" to="9pm" />
<THEN>
<!-- action -->
</THEN>
<ELSE>
<!-- action -->
</ELSE>
</IF>
In this way you don't need an id
attribute to tie together the IF
, THEN
, ELSE
tags
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as global
, inside the function :
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make your function return the result :
function someFuntion(){
$myArr = array(); // At first, you have an empty array
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
return $myArr;
}
And call the function like this :
$result = someFunction();
Your function could also take parameters, and even work on a parameter passed by reference :
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
Then, call the function like this :
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
With this :
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
This will bring back totals per property and type
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
GROUP BY PropertyID,
TYPE
This will bring back only active values
SELECT PropertyID,
TYPE,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID,
TYPE
and this will bring back totals for properties
SELECT PropertyID,
SUM(Amount)
FROM yourTable
WHERE EndDate IS NULL
GROUP BY PropertyID
......
You have to put your code in the callback function you supply to setTimeout
:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
Any other code will execute immediately.
Though the installer answer is a good answer, it is not always practical when dealing with software you did not write. A simple answer is to create the log and the event source using the PowerShell command New-EventLog (http://technet.microsoft.com/en-us/library/hh849768.aspx)
Run PowerShell as an Administrator and run the following command changing out the log name and source that you need.
New-EventLog -LogName Application -Source TFSAggregator
I used it to solve the Event Log Exception when Aggregator runs issue from codeplex.
In case you want to apply common functions such as sum or mean, you should use rowSums
or rowMeans
since they're faster than apply(data, 1, sum)
approach. Otherwise, stick with apply(data, 1, fun)
. You can pass additional arguments after FUN argument (as Dirk already suggested):
set.seed(1)
m <- matrix(round(runif(20, 1, 5)), ncol=4)
diag(m) <- NA
m
[,1] [,2] [,3] [,4]
[1,] NA 5 2 3
[2,] 2 NA 2 4
[3,] 3 4 NA 5
[4,] 5 4 3 NA
[5,] 2 1 4 4
Then you can do something like this:
apply(m, 1, quantile, probs=c(.25,.5, .75), na.rm=TRUE)
[,1] [,2] [,3] [,4] [,5]
25% 2.5 2 3.5 3.5 1.75
50% 3.0 2 4.0 4.0 3.00
75% 4.0 3 4.5 4.5 4.00
You can use the parseInt() function to convert the string to a number, e.g:
parseInt($('#elem').css('top'));
Update: (as suggested by Ben): You should give the radix too:
parseInt($('#elem').css('top'), 10);
Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).
This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.
Either as recordset or output parameter. The latter has less overhead and I'd tend to use that rather than a single column/row recordset.
If I expected to >1 row I'd use the OUTPUT clause and a recordset
Return values would normally be used for error handling.
jQuery provides that:
if ($.browser.webkit){
...
}
Further reading at http://api.jquery.com/jQuery.browser/
Update
As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support
. Check the documentation to see the detailed list features to check for.
You can use Popen in subprocess
as they suggest.
with os
, which is not recomment, it's like below:
import os
a = os.popen('pwd').readlines()
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').html();
console.log($variable);
}
});
});
or
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').text();
console.log($variable);
}
});
});
or
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').val();
console.log($variable);
}
});
});
After some tries, these are the samples I am using in order to connect:
Specifying the username and the password:
sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword
Specifying the DB as well:
sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
jQuery is just a library which enhances the capabilities of the DOM within a web browser; the underlying language is JavaScript, which has, as you might hope to expect from a programming language, the ability to perform conditional logic, i.e.
if( condition ) {
// do something
}
Testing two conditions is straightforward, too:
if( A && B ) {
// do something
}
Dear God, I hope this isn't a troll...
Razor Syntax
In the case of ASP.NET MVC you can just store the title as a variable as use \r\n
and it'll work.
@{
var logTooltip = "Sunday\r\nMonday\r\netc.";
}
<h3 title="@logTooltip">Logs</h3>
The answer @Ro Hit gave helped me a lot, but I was missing the user credentials because I had to fake a user for authentication unit testing. Hence, let me describe how I solved it.
According to this, if you add the method
// using System.Security.Principal;
GenericPrincipal FakeUser(string userName)
{
var fakeIdentity = new GenericIdentity(userName);
var principal = new GenericPrincipal(fakeIdentity, null);
return principal;
}
and then append
HttpContext.Current.User = FakeUser("myDomain\\myUser");
to the last line of the TestSetup
method you're done, the user credentials are added and ready to be used for authentication testing.
I also noticed that there are other parts in HttpContext you might require, such as the .MapPath()
method. There is a FakeHttpContext available, which is described here and can be installed via NuGet.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
To remove all cookies you could write:
foreach ($_COOKIE as $key => $value) {
unset($value);
setcookie($key, '', time() - 3600);
}
very simple example of parallel processing is
from multiprocessing import Process
output1 = list()
output2 = list()
output3 = list()
def yourfunction():
for j in range(0, 10):
# calc individual parameter value
parameter = j * offset
# call the calculation
out1, out2, out3 = calc_stuff(parameter=parameter)
# put results into correct output list
output1.append(out1)
output2.append(out2)
output3.append(out3)
if __name__ == '__main__':
p = Process(target=pa.yourfunction, args=('bob',))
p.start()
p.join()
The following worked for me, nothing else -:
SET GLOBAL innodb_log_buffer_size = 80*1024*1024*1024;
and
SET GLOBAL innodb_strict_mode = 0;
Hope this helps someone because it wasted couple of days of my time as I was trying to do this in my.cnf with no joy.
The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.
Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:
void ListIpAddresses(IpAddresses& ipAddrs)
{
IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
IP_ADAPTER_ADDRESSES* adapter(NULL);
// Start with a 16 KB buffer and resize if needed -
// multiple attempts in case interfaces change while
// we are in the middle of querying them.
DWORD adapter_addresses_buffer_size = 16 * KB;
for (int attempts = 0; attempts != 3; ++attempts)
{
adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
assert(adapter_addresses);
DWORD error = ::GetAdaptersAddresses(
AF_UNSPEC,
GAA_FLAG_SKIP_ANYCAST |
GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_DNS_SERVER |
GAA_FLAG_SKIP_FRIENDLY_NAME,
NULL,
adapter_addresses,
&adapter_addresses_buffer_size);
if (ERROR_SUCCESS == error)
{
// We're done here, people!
break;
}
else if (ERROR_BUFFER_OVERFLOW == error)
{
// Try again with the new size
free(adapter_addresses);
adapter_addresses = NULL;
continue;
}
else
{
// Unexpected error code - log and throw
free(adapter_addresses);
adapter_addresses = NULL;
// @todo
LOG_AND_THROW_HERE();
}
}
// Iterate through all of the adapters
for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
{
// Skip loopback adapters
if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
{
continue;
}
// Parse all IPv4 and IPv6 addresses
for (
IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
NULL != address;
address = address->Next)
{
auto family = address->Address.lpSockaddr->sa_family;
if (AF_INET == family)
{
// IPv4
SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);
char str_buffer[INET_ADDRSTRLEN] = {0};
inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
ipAddrs.mIpv4.push_back(str_buffer);
}
else if (AF_INET6 == family)
{
// IPv6
SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);
char str_buffer[INET6_ADDRSTRLEN] = {0};
inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);
std::string ipv6_str(str_buffer);
// Detect and skip non-external addresses
bool is_link_local(false);
bool is_special_use(false);
if (0 == ipv6_str.find("fe"))
{
char c = ipv6_str[2];
if (c == '8' || c == '9' || c == 'a' || c == 'b')
{
is_link_local = true;
}
}
else if (0 == ipv6_str.find("2001:0:"))
{
is_special_use = true;
}
if (! (is_link_local || is_special_use))
{
ipAddrs.mIpv6.push_back(ipv6_str);
}
}
else
{
// Skip all other types of addresses
continue;
}
}
}
// Cleanup
free(adapter_addresses);
adapter_addresses = NULL;
// Cheers!
}
If you use the following to change the port or host:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
use the following code to start the server (my main entrance for flask is app.py):
python app.py
instead of using:
flask run
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
For Typescript users willing to set and get typed properties:
/**
* Silly wrapper to be able to type the storage keys
*/
export class TypedStorage<T> {
public removeItem(key: keyof T): void {
localStorage.removeItem(key);
}
public getItem<K extends keyof T>(key: K): T[K] | null {
const data: string | null = localStorage.getItem(key);
return JSON.parse(data);
}
public setItem<K extends keyof T>(key: K, value: T[K]): void {
const data: string = JSON.stringify(value);
localStorage.setItem(key, data);
}
}
// write an interface for the storage
interface MyStore {
age: number,
name: string,
address: {city:string}
}
const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();
storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok
const address: {city:string} = storage.getItem("address");
You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php
Then in your ajax call change the success function to this:
$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');
Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName
Will result in
System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
From Wikipedia:
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.
But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:
- the use of HTTP cookies.
- server side sessions,
- hidden variables (when the current page contains a form), and
- URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.
What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.
I thought it has been around a little longer, but according to this,
MySQL 5.7.4 introduces the ability to set server side execution time limits, specified in milliseconds, for top level read-only SELECT statements.
SELECT
/*+ MAX_EXECUTION_TIME(1000) */ --in milliseconds
*
FROM table;
Note that this only works for read-only SELECT statements.
Update: This variable was added in MySQL 5.7.4 and renamed to max_execution_time
in MySQL 5.7.8. (source)
It is normally provided by the browser and hard to change, so the only way around it will be a CSS/JavaScript hack,
See the following links for some approaches:
I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components
They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.
Something like this:
typedef struct vec
{
unsigned char* _mem;
unsigned long _elems;
unsigned long _elemsize;
unsigned long _capelems;
unsigned long _reserve;
};
vec* vec_new(unsigned long elemsize)
{
vec* pvec = (vec*)malloc(sizeof(vec));
pvec->_reserve = 10;
pvec->_capelems = pvec->_reserve;
pvec->_elemsize = elemsize;
pvec->_elems = 0;
pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
return pvec;
}
void vec_delete(vec* pvec)
{
free(pvec->_mem);
free(pvec);
}
void vec_grow(vec* pvec)
{
unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
free(pvec->_mem);
pvec->_mem = mem;
pvec->_capelems += pvec->_reserve;
}
void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
assert(elemsize == pvec->_elemsize);
if (pvec->_elems == pvec->_capelems) {
vec_grow(pvec);
}
memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
pvec->_elems++;
}
unsigned long vec_length(vec* pvec)
{
return pvec->_elems;
}
void* vec_get(vec* pvec, unsigned long index)
{
assert(index < pvec->_elems);
return (void*)(pvec->_mem + (index * pvec->_elemsize));
}
void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}
void playwithvec()
{
vec* pvec = vec_new(sizeof(int));
for (int val = 0; val < 1000; val += 10) {
vec_push_back(pvec, &val, sizeof(val));
}
for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
int val;
vec_copy_item(pvec, &val, index);
printf("vec(%d) = %d\n", index, val);
}
vec_delete(pvec);
}
Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
server {
server_name example.com;
root /path/to/root;
location / {
# bla bla
}
location /demo {
alias /path/to/root/production/folder/here;
}
}
If you need to use try_files
inside /demo
you'll need to replace alias
with a root
and do a rewrite because of the bug explained here
With does not work embedded, but it does work consecutive
;WITH A AS(
...
),
B AS(
...
)
SELECT *
FROM A
UNION ALL
SELECT *
FROM B
EDIT Fixed the syntax...
Also, have a look at the following example
This is a hacky method, but i tried it twice with different numbers and it seems to be consistent.
What you can do is to try and allocate a huge number of objects, like one or two million objects of the kind you want. Put the objects in an array to prevent the garbage collector from releasing them (note that this will add a slight memory overhead because of the array, but i hope this shouldn't matter and besides if you are going to worry about objects being in memory, you store them somewhere). Add an alert before and after the allocation and in each alert check how much memory the Firefox process is taking. Before you open the page with the test, make sure you have a fresh Firefox instance. Open the page, note the memory usage after the "before" alert is shown. Close the alert, wait for the memory to be allocated. Subtract the new memory from the older and divide it by the amount of allocations. Example:
function Marks()
{
this.maxMarks = 100;
}
function Student()
{
this.firstName = "firstName";
this.lastName = "lastName";
this.marks = new Marks();
}
var manyObjects = new Array();
alert('before');
for (var i=0; i<2000000; i++)
manyObjects[i] = new Student();
alert('after');
I tried this in my computer and the process had 48352K of memory when the "before" alert was shown. After the allocation, Firefox had 440236K of memory. For 2million allocations, this is about 200 bytes for each object.
I tried it again with 1million allocations and the result was similar: 196 bytes per object (i suppose the extra data in 2mill was used for Array).
So, here is a hacky method that might help you. JavaScript doesn't provide a "sizeof" method for a reason: each JavaScript implementaion is different. In Google Chrome for example the same page uses about 66 bytes for each object (judging from the task manager at least).
An important addition to Travis' answer; you need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth(). What i did ;
<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>
and call aWidth variable anywhere afterwards.
You can increase body size in nginx configuration file as
sudo nano /etc/nginx/nginx.conf
client_max_body_size 100M;
Restart nginx to apply the changes.
sudo service nginx restart
glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
Notice the cool thing in S.Lott's comment - you can also call functions with *mylist
and **mydict
to unpack positional and keyword arguments:
def foo(a, b, c, d):
print a, b, c, d
l = [0, 1]
d = {"d":3, "c":2}
foo(*l, **d)
Will print: 0 1 2 3