This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.
g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)
I definitely prefer the format
method more, as it is very flexible and can be easily extended to your custom classes by defining __format__
or the str
or repr
representations. For the sake of keeping it simple, i am using print
in the following examples, which can be replaced by sys.stdout.write
.
Simple Examples: alignment / filling
#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido")) # 'Guido '
print("{0:>10}".format("Guido")) # ' Guido'
print("{0:^10}".format("Guido")) # ' Guido '
We can add next to the align
specifies which are ^
, <
and >
a fill character to replace the space by any other character
print("{0:.^10}".format("Guido")) #..Guido...
Multiinput examples: align and fill many inputs
print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'
Advanced Examples
If you have your custom classes, you can define it's str
or repr
representations as follows:
class foo(object):
def __str__(self):
return "...::4::.."
def __repr__(self):
return "...::12::.."
Now you can use the !s
(str) or !r
(repr) to tell python to call those defined methods. If nothing is defined, Python defaults to __format__
which can be overwritten as well.
x = foo()
print "{0!r:<10}".format(x) #'...::12::..'
print "{0!s:<10}".format(x) #'...::4::..'
Source: Python Essential Reference, David M. Beazley, 4th Edition
You can easily convert to xml format using online converters:
I have converted the list:
<?xml version="1.0" encoding="UTF-8" ?>
<countries>
<code>+7 840</code>
<name>Abkhazia</name>
</countries>
<countries>
<code>+93</code>
<name>Afghanistan</name>
</countries>
<countries>
<code>+355</code>
<name>Albania</name>
</countries>
<countries>
<code>+213</code>
<name>Algeria</name>
</countries>
<countries>
<code>+1 684</code>
<name>American Samoa</name>
</countries>
<countries>
<code>+376</code>
<name>Andorra</name>
</countries>
<countries>
<code>+244</code>
<name>Angola</name>
</countries>
<countries>
<code>+1 264</code>
<name>Anguilla</name>
</countries>
<countries>
<code>+1 268</code>
<name>Antigua and Barbuda</name>
</countries>
<countries>
<code>+54</code>
<name>Argentina</name>
</countries>
<countries>
<code>+374</code>
<name>Armenia</name>
</countries>
<countries>
<code>+297</code>
<name>Aruba</name>
</countries>
<countries>
<code>+247</code>
<name>Ascension</name>
</countries>
<countries>
<code>+61</code>
<name>Australia</name>
</countries>
<countries>
<code>+672</code>
<name>Australian External Territories</name>
</countries>
<countries>
<code>+43</code>
<name>Austria</name>
</countries>
<countries>
<code>+994</code>
<name>Azerbaijan</name>
</countries>
<countries>
<code>+1 242</code>
<name>Bahamas</name>
</countries>
<countries>
<code>+973</code>
<name>Bahrain</name>
</countries>
<countries>
<code>+880</code>
<name>Bangladesh</name>
</countries>
<countries>
<code>+1 246</code>
<name>Barbados</name>
</countries>
<countries>
<code>+1 268</code>
<name>Barbuda</name>
</countries>
<countries>
<code>+375</code>
<name>Belarus</name>
</countries>
<countries>
<code>+32</code>
<name>Belgium</name>
</countries>
<countries>
<code>+501</code>
<name>Belize</name>
</countries>
<countries>
<code>+229</code>
<name>Benin</name>
</countries>
<countries>
<code>+1 441</code>
<name>Bermuda</name>
</countries>
<countries>
<code>+975</code>
<name>Bhutan</name>
</countries>
<countries>
<code>+591</code>
<name>Bolivia</name>
</countries>
<countries>
<code>+387</code>
<name>Bosnia and Herzegovina</name>
</countries>
<countries>
<code>+267</code>
<name>Botswana</name>
</countries>
<countries>
<code>+55</code>
<name>Brazil</name>
</countries>
<countries>
<code>+246</code>
<name>British Indian Ocean Territory</name>
</countries>
<countries>
<code>+1 284</code>
<name>British Virgin Islands</name>
</countries>
<countries>
<code>+673</code>
<name>Brunei</name>
</countries>
<countries>
<code>+359</code>
<name>Bulgaria</name>
</countries>
<countries>
<code>+226</code>
<name>Burkina Faso</name>
</countries>
<countries>
<code>+257</code>
<name>Burundi</name>
</countries>
<countries>
<code>+855</code>
<name>Cambodia</name>
</countries>
<countries>
<code>+237</code>
<name>Cameroon</name>
</countries>
<countries>
<code>+1</code>
<name>Canada</name>
</countries>
<countries>
<code>+238</code>
<name>Cape Verde</name>
</countries>
<countries>
<code>+ 345</code>
<name>Cayman Islands</name>
</countries>
<countries>
<code>+236</code>
<name>Central African Republic</name>
</countries>
<countries>
<code>+235</code>
<name>Chad</name>
</countries>
<countries>
<code>+56</code>
<name>Chile</name>
</countries>
<countries>
<code>+86</code>
<name>China</name>
</countries>
<countries>
<code>+61</code>
<name>Christmas Island</name>
</countries>
<countries>
<code>+61</code>
<name>Cocos-Keeling Islands</name>
</countries>
<countries>
<code>+57</code>
<name>Colombia</name>
</countries>
<countries>
<code>+269</code>
<name>Comoros</name>
</countries>
<countries>
<code>+242</code>
<name>Congo</name>
</countries>
<countries>
<code>+243</code>
<name>Congo, Dem. Rep. of (Zaire)</name>
</countries>
<countries>
<code>+682</code>
<name>Cook Islands</name>
</countries>
<countries>
<code>+506</code>
<name>Costa Rica</name>
</countries>
<countries>
<code>+385</code>
<name>Croatia</name>
</countries>
<countries>
<code>+53</code>
<name>Cuba</name>
</countries>
<countries>
<code>+599</code>
<name>Curacao</name>
</countries>
<countries>
<code>+537</code>
<name>Cyprus</name>
</countries>
<countries>
<code>+420</code>
<name>Czech Republic</name>
</countries>
<countries>
<code>+45</code>
<name>Denmark</name>
</countries>
<countries>
<code>+246</code>
<name>Diego Garcia</name>
</countries>
<countries>
<code>+253</code>
<name>Djibouti</name>
</countries>
<countries>
<code>+1 767</code>
<name>Dominica</name>
</countries>
<countries>
<code>+1 809</code>
<name>Dominican Republic</name>
</countries>
<countries>
<code>+670</code>
<name>East Timor</name>
</countries>
<countries>
<code>+56</code>
<name>Easter Island</name>
</countries>
<countries>
<code>+593</code>
<name>Ecuador</name>
</countries>
<countries>
<code>+20</code>
<name>Egypt</name>
</countries>
<countries>
<code>+503</code>
<name>El Salvador</name>
</countries>
<countries>
<code>+240</code>
<name>Equatorial Guinea</name>
</countries>
<countries>
<code>+291</code>
<name>Eritrea</name>
</countries>
<countries>
<code>+372</code>
<name>Estonia</name>
</countries>
<countries>
<code>+251</code>
<name>Ethiopia</name>
</countries>
<countries>
<code>+500</code>
<name>Falkland Islands</name>
</countries>
<countries>
<code>+298</code>
<name>Faroe Islands</name>
</countries>
<countries>
<code>+679</code>
<name>Fiji</name>
</countries>
<countries>
<code>+358</code>
<name>Finland</name>
</countries>
<countries>
<code>+33</code>
<name>France</name>
</countries>
<countries>
<code>+596</code>
<name>French Antilles</name>
</countries>
<countries>
<code>+594</code>
<name>French Guiana</name>
</countries>
<countries>
<code>+689</code>
<name>French Polynesia</name>
</countries>
<countries>
<code>+241</code>
<name>Gabon</name>
</countries>
<countries>
<code>+220</code>
<name>Gambia</name>
</countries>
<countries>
<code>+995</code>
<name>Georgia</name>
</countries>
<countries>
<code>+49</code>
<name>Germany</name>
</countries>
<countries>
<code>+233</code>
<name>Ghana</name>
</countries>
<countries>
<code>+350</code>
<name>Gibraltar</name>
</countries>
<countries>
<code>+30</code>
<name>Greece</name>
</countries>
<countries>
<code>+299</code>
<name>Greenland</name>
</countries>
<countries>
<code>+1 473</code>
<name>Grenada</name>
</countries>
<countries>
<code>+590</code>
<name>Guadeloupe</name>
</countries>
<countries>
<code>+1 671</code>
<name>Guam</name>
</countries>
<countries>
<code>+502</code>
<name>Guatemala</name>
</countries>
<countries>
<code>+224</code>
<name>Guinea</name>
</countries>
<countries>
<code>+245</code>
<name>Guinea-Bissau</name>
</countries>
<countries>
<code>+595</code>
<name>Guyana</name>
</countries>
<countries>
<code>+509</code>
<name>Haiti</name>
</countries>
<countries>
<code>+504</code>
<name>Honduras</name>
</countries>
<countries>
<code>+852</code>
<name>Hong Kong SAR China</name>
</countries>
<countries>
<code>+36</code>
<name>Hungary</name>
</countries>
<countries>
<code>+354</code>
<name>Iceland</name>
</countries>
<countries>
<code>+91</code>
<name>India</name>
</countries>
<countries>
<code>+62</code>
<name>Indonesia</name>
</countries>
<countries>
<code>+98</code>
<name>Iran</name>
</countries>
<countries>
<code>+964</code>
<name>Iraq</name>
</countries>
<countries>
<code>+353</code>
<name>Ireland</name>
</countries>
<countries>
<code>+972</code>
<name>Israel</name>
</countries>
<countries>
<code>+39</code>
<name>Italy</name>
</countries>
<countries>
<code>+225</code>
<name>Ivory Coast</name>
</countries>
<countries>
<code>+1 876</code>
<name>Jamaica</name>
</countries>
<countries>
<code>+81</code>
<name>Japan</name>
</countries>
<countries>
<code>+962</code>
<name>Jordan</name>
</countries>
<countries>
<code>+7 7</code>
<name>Kazakhstan</name>
</countries>
<countries>
<code>+254</code>
<name>Kenya</name>
</countries>
<countries>
<code>+686</code>
<name>Kiribati</name>
</countries>
<countries>
<code>+965</code>
<name>Kuwait</name>
</countries>
<countries>
<code>+996</code>
<name>Kyrgyzstan</name>
</countries>
<countries>
<code>+856</code>
<name>Laos</name>
</countries>
<countries>
<code>+371</code>
<name>Latvia</name>
</countries>
<countries>
<code>+961</code>
<name>Lebanon</name>
</countries>
<countries>
<code>+266</code>
<name>Lesotho</name>
</countries>
<countries>
<code>+231</code>
<name>Liberia</name>
</countries>
<countries>
<code>+218</code>
<name>Libya</name>
</countries>
<countries>
<code>+423</code>
<name>Liechtenstein</name>
</countries>
<countries>
<code>+370</code>
<name>Lithuania</name>
</countries>
<countries>
<code>+352</code>
<name>Luxembourg</name>
</countries>
<countries>
<code>+853</code>
<name>Macau SAR China</name>
</countries>
<countries>
<code>+389</code>
<name>Macedonia</name>
</countries>
<countries>
<code>+261</code>
<name>Madagascar</name>
</countries>
<countries>
<code>+265</code>
<name>Malawi</name>
</countries>
<countries>
<code>+60</code>
<name>Malaysia</name>
</countries>
<countries>
<code>+960</code>
<name>Maldives</name>
</countries>
<countries>
<code>+223</code>
<name>Mali</name>
</countries>
<countries>
<code>+356</code>
<name>Malta</name>
</countries>
<countries>
<code>+692</code>
<name>Marshall Islands</name>
</countries>
<countries>
<code>+596</code>
<name>Martinique</name>
</countries>
<countries>
<code>+222</code>
<name>Mauritania</name>
</countries>
<countries>
<code>+230</code>
<name>Mauritius</name>
</countries>
<countries>
<code>+262</code>
<name>Mayotte</name>
</countries>
<countries>
<code>+52</code>
<name>Mexico</name>
</countries>
<countries>
<code>+691</code>
<name>Micronesia</name>
</countries>
<countries>
<code>+1 808</code>
<name>Midway Island</name>
</countries>
<countries>
<code>+373</code>
<name>Moldova</name>
</countries>
<countries>
<code>+377</code>
<name>Monaco</name>
</countries>
<countries>
<code>+976</code>
<name>Mongolia</name>
</countries>
<countries>
<code>+382</code>
<name>Montenegro</name>
</countries>
<countries>
<code>+1664</code>
<name>Montserrat</name>
</countries>
<countries>
<code>+212</code>
<name>Morocco</name>
</countries>
<countries>
<code>+95</code>
<name>Myanmar</name>
</countries>
<countries>
<code>+264</code>
<name>Namibia</name>
</countries>
<countries>
<code>+674</code>
<name>Nauru</name>
</countries>
<countries>
<code>+977</code>
<name>Nepal</name>
</countries>
<countries>
<code>+31</code>
<name>Netherlands</name>
</countries>
<countries>
<code>+599</code>
<name>Netherlands Antilles</name>
</countries>
<countries>
<code>+1 869</code>
<name>Nevis</name>
</countries>
<countries>
<code>+687</code>
<name>New Caledonia</name>
</countries>
<countries>
<code>+64</code>
<name>New Zealand</name>
</countries>
<countries>
<code>+505</code>
<name>Nicaragua</name>
</countries>
<countries>
<code>+227</code>
<name>Niger</name>
</countries>
<countries>
<code>+234</code>
<name>Nigeria</name>
</countries>
<countries>
<code>+683</code>
<name>Niue</name>
</countries>
<countries>
<code>+672</code>
<name>Norfolk Island</name>
</countries>
<countries>
<code>+850</code>
<name>North Korea</name>
</countries>
<countries>
<code>+1 670</code>
<name>Northern Mariana Islands</name>
</countries>
<countries>
<code>+47</code>
<name>Norway</name>
</countries>
<countries>
<code>+968</code>
<name>Oman</name>
</countries>
<countries>
<code>+92</code>
<name>Pakistan</name>
</countries>
<countries>
<code>+680</code>
<name>Palau</name>
</countries>
<countries>
<code>+970</code>
<name>Palestinian Territory</name>
</countries>
<countries>
<code>+507</code>
<name>Panama</name>
</countries>
<countries>
<code>+675</code>
<name>Papua New Guinea</name>
</countries>
<countries>
<code>+595</code>
<name>Paraguay</name>
</countries>
<countries>
<code>+51</code>
<name>Peru</name>
</countries>
<countries>
<code>+63</code>
<name>Philippines</name>
</countries>
<countries>
<code>+48</code>
<name>Poland</name>
</countries>
<countries>
<code>+351</code>
<name>Portugal</name>
</countries>
<countries>
<code>+1 787</code>
<name>Puerto Rico</name>
</countries>
<countries>
<code>+974</code>
<name>Qatar</name>
</countries>
<countries>
<code>+262</code>
<name>Reunion</name>
</countries>
<countries>
<code>+40</code>
<name>Romania</name>
</countries>
<countries>
<code>+7</code>
<name>Russia</name>
</countries>
<countries>
<code>+250</code>
<name>Rwanda</name>
</countries>
<countries>
<code>+685</code>
<name>Samoa</name>
</countries>
<countries>
<code>+378</code>
<name>San Marino</name>
</countries>
<countries>
<code>+966</code>
<name>Saudi Arabia</name>
</countries>
<countries>
<code>+221</code>
<name>Senegal</name>
</countries>
<countries>
<code>+381</code>
<name>Serbia</name>
</countries>
<countries>
<code>+248</code>
<name>Seychelles</name>
</countries>
<countries>
<code>+232</code>
<name>Sierra Leone</name>
</countries>
<countries>
<code>+65</code>
<name>Singapore</name>
</countries>
<countries>
<code>+421</code>
<name>Slovakia</name>
</countries>
<countries>
<code>+386</code>
<name>Slovenia</name>
</countries>
<countries>
<code>+677</code>
<name>Solomon Islands</name>
</countries>
<countries>
<code>+27</code>
<name>South Africa</name>
</countries>
<countries>
<code>+500</code>
<name>South Georgia and the South Sandwich Islands</name>
</countries>
<countries>
<code>+82</code>
<name>South Korea</name>
</countries>
<countries>
<code>+34</code>
<name>Spain</name>
</countries>
<countries>
<code>+94</code>
<name>Sri Lanka</name>
</countries>
<countries>
<code>+249</code>
<name>Sudan</name>
</countries>
<countries>
<code>+597</code>
<name>Suriname</name>
</countries>
<countries>
<code>+268</code>
<name>Swaziland</name>
</countries>
<countries>
<code>+46</code>
<name>Sweden</name>
</countries>
<countries>
<code>+41</code>
<name>Switzerland</name>
</countries>
<countries>
<code>+963</code>
<name>Syria</name>
</countries>
<countries>
<code>+886</code>
<name>Taiwan</name>
</countries>
<countries>
<code>+992</code>
<name>Tajikistan</name>
</countries>
<countries>
<code>+255</code>
<name>Tanzania</name>
</countries>
<countries>
<code>+66</code>
<name>Thailand</name>
</countries>
<countries>
<code>+670</code>
<name>Timor Leste</name>
</countries>
<countries>
<code>+228</code>
<name>Togo</name>
</countries>
<countries>
<code>+690</code>
<name>Tokelau</name>
</countries>
<countries>
<code>+676</code>
<name>Tonga</name>
</countries>
<countries>
<code>+1 868</code>
<name>Trinidad and Tobago</name>
</countries>
<countries>
<code>+216</code>
<name>Tunisia</name>
</countries>
<countries>
<code>+90</code>
<name>Turkey</name>
</countries>
<countries>
<code>+993</code>
<name>Turkmenistan</name>
</countries>
<countries>
<code>+1 649</code>
<name>Turks and Caicos Islands</name>
</countries>
<countries>
<code>+688</code>
<name>Tuvalu</name>
</countries>
<countries>
<code>+1 340</code>
<name>U.S. Virgin Islands</name>
</countries>
<countries>
<code>+256</code>
<name>Uganda</name>
</countries>
<countries>
<code>+380</code>
<name>Ukraine</name>
</countries>
<countries>
<code>+971</code>
<name>United Arab Emirates</name>
</countries>
<countries>
<code>+44</code>
<name>United Kingdom</name>
</countries>
<countries>
<code>+1</code>
<name>United States</name>
</countries>
<countries>
<code>+598</code>
<name>Uruguay</name>
</countries>
<countries>
<code>+998</code>
<name>Uzbekistan</name>
</countries>
<countries>
<code>+678</code>
<name>Vanuatu</name>
</countries>
<countries>
<code>+58</code>
<name>Venezuela</name>
</countries>
<countries>
<code>+84</code>
<name>Vietnam</name>
</countries>
<countries>
<code>+1 808</code>
<name>Wake Island</name>
</countries>
<countries>
<code>+681</code>
<name>Wallis and Futuna</name>
</countries>
<countries>
<code>+967</code>
<name>Yemen</name>
</countries>
<countries>
<code>+260</code>
<name>Zambia</name>
</countries>
<countries>
<code>+255</code>
<name>Zanzibar</name>
</countries>
<countries>
<code>+263</code>
<name>Zimbabwe</name>
</countries>
You need to add the original repository (the one that you forked) as a remote.
git remote add github (clone url for the orignal repository)
Then you need to bring in the changes to your local repository
git fetch github
Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master
. With these branches you can do what you will. Merge them into your branches etc
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:
I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.
Recently D3js is able to handle local json file.
This is the issue https://github.com/mbostock/d3/issues/673
This is the patch inorder for D3 to work with local json files. https://github.com/mbostock/d3/pull/632
Just pass it in like any other parameter:
def a(x):
return "a(%s)" % (x,)
def b(f,x):
return f(x)
print b(a,10)
If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
See Spring 4.2.x CORS for more information.
Without Spring Security this will work:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
Four years later I came across this again. My current approach is this as it allows for code completion in the IDE as well as type safety:
Base class:
abstract class TypedEnum
{
private static $_instancedValues;
private $_value;
private $_name;
private function __construct($value, $name)
{
$this->_value = $value;
$this->_name = $name;
}
private static function _fromGetter($getter, $value)
{
$reflectionClass = new ReflectionClass(get_called_class());
$methods = $reflectionClass->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC);
$className = get_called_class();
foreach($methods as $method)
{
if ($method->class === $className)
{
$enumItem = $method->invoke(null);
if ($enumItem instanceof $className && $enumItem->$getter() === $value)
{
return $enumItem;
}
}
}
throw new OutOfRangeException();
}
protected static function _create($value)
{
if (self::$_instancedValues === null)
{
self::$_instancedValues = array();
}
$className = get_called_class();
if (!isset(self::$_instancedValues[$className]))
{
self::$_instancedValues[$className] = array();
}
if (!isset(self::$_instancedValues[$className][$value]))
{
$debugTrace = debug_backtrace();
$lastCaller = array_shift($debugTrace);
while ($lastCaller['class'] !== $className && count($debugTrace) > 0)
{
$lastCaller = array_shift($debugTrace);
}
self::$_instancedValues[$className][$value] = new static($value, $lastCaller['function']);
}
return self::$_instancedValues[$className][$value];
}
public static function fromValue($value)
{
return self::_fromGetter('getValue', $value);
}
public static function fromName($value)
{
return self::_fromGetter('getName', $value);
}
public function getValue()
{
return $this->_value;
}
public function getName()
{
return $this->_name;
}
}
Example Enum:
final class DaysOfWeek extends TypedEnum
{
public static function Sunday() { return self::_create(0); }
public static function Monday() { return self::_create(1); }
public static function Tuesday() { return self::_create(2); }
public static function Wednesday() { return self::_create(3); }
public static function Thursday() { return self::_create(4); }
public static function Friday() { return self::_create(5); }
public static function Saturday() { return self::_create(6); }
}
Example usage:
function saveEvent(DaysOfWeek $weekDay, $comment)
{
// store week day numeric value and comment:
$myDatabase->save('myeventtable',
array('weekday_id' => $weekDay->getValue()),
array('comment' => $comment));
}
// call the function, note: DaysOfWeek::Monday() returns an object of type DaysOfWeek
saveEvent(DaysOfWeek::Monday(), 'some comment');
Note that all instances of the same enum entry are the same:
$monday1 = DaysOfWeek::Monday();
$monday2 = DaysOfWeek::Monday();
$monday1 === $monday2; // true
You can also use it inside of a switch statement:
function getGermanWeekDayName(DaysOfWeek $weekDay)
{
switch ($weekDay)
{
case DaysOfWeek::Monday(): return 'Montag';
case DaysOfWeek::Tuesday(): return 'Dienstag';
// ...
}
You can also create an enum entry by name or value:
$monday = DaysOfWeek::fromValue(2);
$tuesday = DaysOfWeek::fromName('Tuesday');
Or you can just get the name (i.e. the function name) from an existing enum entry:
$wednesday = DaysOfWeek::Wednesday()
echo $wednesDay->getName(); // Wednesday
You could use loc
to get series which satisfying your condition and then iloc
to get first element:
In [2]: df
Out[2]:
A B
0 p1 1
1 p1 2
2 p3 3
3 p2 4
In [3]: df.loc[df['B'] == 3, 'A']
Out[3]:
2 p3
Name: A, dtype: object
In [4]: df.loc[df['B'] == 3, 'A'].iloc[0]
Out[4]: 'p3'
This exact same error happened to me only when I tried to build my debug build type. The way I solved it was to change my google-services.json
for my debug build type.
My original field had a field called client_id
and the value was android:com.example.exampleapp
, and I just deleted the android:
prefix and leave as com.example.exampleapp
and after that my gradle build was successful.
Hope it helps!
EDIT
I've just added back the android:
prefix in my google-services.json
and it continued to work correctly. Not sure what happened exactly but I was able to solve my problem with the solution mentioned above.
I mean it's quite simple. Set it as a double. So lets say
double answer = 3.0/2.0;
System.out.print(answer);
Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.
This is the only way I can ever see myself developing from a Windows box again.
I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.
Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.
Here is an example of showing the line number of where exception takes place.
import sys
try:
print(5/0)
except Exception as e:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
print('And the rest of program continues')
what about that simple way)
$(document).ready ->
$('#datepicker').datepicker( dateFormat: 'yy-mm-dd', onSelect: (dateStr) ->
alert dateStr # yy-mm-dd
#OR
alert $("#datepicker").val(); # yy-mm-dd
The add_business_days has a small bug. Try the following with the existing function and the output will be a Saturday.
Startdate = Friday Business days to add = 1 Holidays array = Add date for the following Monday.
I have fixed that in my function below.
function add_business_days($startdate, $buisnessdays, $holidays = array(), $dateformat = 'Y-m-d'){
$i= 1;
$dayx= strtotime($startdate);
$buisnessdays= ceil($buisnessdays);
while($i < $buisnessdays)
{
$day= date('N',$dayx);
$date= date('Y-m-d',$dayx);
if($day < 6 && !in_array($date,$holidays))
$i++;
$dayx= strtotime($date.' +1 day');
}
## If the calculated day falls on a weekend or is a holiday, then add days to the next business day
$day= date('N',$dayx);
$date= date('Y-m-d',$dayx);
while($day >= 6 || in_array($date,$holidays))
{
$dayx= strtotime($date.' +1 day');
$day= date('N',$dayx);
$date= date('Y-m-d',$dayx);
}
return date($dateformat, $dayx);}
You can compare both approaches for the same data:
def myGeneratorList(n):
for i in range(n):
yield i
def myIterableList(n):
ll = n*[None]
for i in range(n):
ll[i] = i
return ll
# Same values
ll1 = myGeneratorList(10)
ll2 = myIterableList(10)
for i1, i2 in zip(ll1, ll2):
print("{} {}".format(i1, i2))
# Generator can only be read once
ll1 = myGeneratorList(10)
ll2 = myIterableList(10)
print("{} {}".format(len(list(ll1)), len(ll2)))
print("{} {}".format(len(list(ll1)), len(ll2)))
# Generator can be read several times if converted into iterable
ll1 = list(myGeneratorList(10))
ll2 = myIterableList(10)
print("{} {}".format(len(list(ll1)), len(ll2)))
print("{} {}".format(len(list(ll1)), len(ll2)))
Besides, if you check the memory footprint, the generator takes much less memory as it doesn't need to store all the values in memory at the same time.
I got an error when I used
<git config --global http.proxy http://user:password@proxy_addr:port>
The error is that the config file cannot be identified as there is no such file. I changed the command to
<git config --system http.proxy http://user:password@proxy_addr:port>
I am running git on the Windows 7 command prompt.
The above command references the config file in GIT_HOME/etc/gitconfig
.
The --global
option does not.
I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:
Activity:
override fun onCreate(savedInstanceState: Bundle?) {
val intent = Intent(this, BackgroundService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
BackgroundService:
override fun onCreate() {
super.onCreate()
startForeground()
}
private fun startForeground() {
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
val channelId = "my_service"
val channelName = "My Background Service"
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_HIGH)
chan.lightColor = Color.BLUE
chan.importance = NotificationManager.IMPORTANCE_NONE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
JAVA EQUIVALENT
public class YourService extends Service {
// Constants
private static final int ID_SERVICE = 101;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
// do stuff like register for BroadcastReceiver, etc.
// Create the Foreground Service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build();
startForeground(ID_SERVICE, notification);
}
@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
String channelId = "my_service_channelid";
String channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
}
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
You need to reverse the nesting inside the generate block:
genvar c;
generate
for (c = 0; c < ROWBITS; c = c + 1) begin: test
always @(posedge sysclk) begin
temp[c] <= 1'b0;
end
end
endgenerate
Technically, this generates four always blocks:
always @(posedge sysclk) temp[0] <= 1'b0;
always @(posedge sysclk) temp[1] <= 1'b0;
always @(posedge sysclk) temp[2] <= 1'b0;
always @(posedge sysclk) temp[3] <= 1'b0;
In this simple example, there's no difference in behavior between the four always blocks and a single always block containing four assignments, but in other cases there could be.
The genvar-dependent operation needs to be resolved when constructing the in-memory representation of the design (in the case of a simulator) or when mapping to logic gates (in the case of a synthesis tool). The always @posedge
doesn't have meaning until the design is operating.
Subject to certain restrictions, you can put a for loop inside the always block, even for synthesizable code. For synthesis, the loop will be unrolled. However, in that case, the for loop needs to work with a reg
, integer
, or similar. It can't use a genvar
, because having the for loop inside the always block describes an operation that occurs at each edge of the clock, not an operation that can be expanded statically during elaboration of the design.
As stated by @Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof()
macro useful - it does the equivalent of what you've done ;)
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":
instantclient-basic-windows.x64-12.1.0.2.0.zip
instantclient-sqlplus-windows.x64-12.1.0.2.0.zip
instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".
Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.
Then Restart your server.
To invoke the procedure from the SQLPlus command line, try one of these:
CALL test_sp_1();
EXEC test_sp_1
Please use the below code for your REST API request:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Json;
namespace ConsoleApplication2
{
class Program
{
private const string URL = "https://XXXX/rest/api/2/component";
private const string DATA = @"{
""name"": ""Component 2"",
""description"": ""This is a JIRA component"",
""leadUserName"": ""xx"",
""assigneeType"": ""PROJECT_LEAD"",
""isAssigneeTypeValid"": false,
""project"": ""TP""}";
static void Main(string[] args)
{
AddComponent();
}
private static void AddComponent()
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(URL);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(URL, content).Result;
string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
description = result;
}
}
}
}
for iOS 8 and above
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
This is what I do to get the actual count (no using the schema)
It's slower but more accurate.
It's a two step process at
Get list of tables for your db. You can get it using
mysql -uroot -p mydb -e "show tables"
Create and assign the list of tables to the array variable in this bash script (separated by a single space just like in the code below)
array=( table1 table2 table3 )
for i in "${array[@]}"
do
echo $i
mysql -uroot mydb -e "select count(*) from $i"
done
Run it:
chmod +x script.sh; ./script.sh
Instead of using a dot, like: 1.2, try to input like this: 1,2.
I had the same problem.
Here is a workaround
android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"
return RedirectToAction("ProductImageManager","Index", new { id=id });
Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct
For those who don't know where to find the file they're talking about. On my machine (OSX) it is in:
/Applications/PyCharm CE.app/Contents/bin/idea.properties
/Applications/WebStorm.app/Contents/bin/idea.properties
You may come across code that reads from an InputStream
and uses the snippet
while(in.available()>0)
to check for the end of the stream, rather than checking for an
EOFException (end of the file).
The problem with this technique, and the Javadoc
does echo this, is that it only tells you the number of blocks that can be read without blocking the next caller. In other words, it can return 0
even if there are more bytes to be read. Therefore, the InputStream available()
method should never be used to check for the end of the stream.
You must use while (true)
and
catch(EOFException e) {
//This isn't problem
} catch (Other e) {
//This is problem
}
Sometimes, the same error occurs when you forget to include the corresponding header
.
The problem comes from instinctively believing that DISTINCT
is a local pre-modifier for a column.
Hence, you "should" be able to type
XXbadXX SELECT col1, DISTINCT col2 FROM mytable XXbadXX
and have it return unique values for col
2. Sadly, no. DISTINCT
is actually a global post-modifier for SELECT
, that is, as opposed to SELECT ALL
(returning all answers) it is SELECT DISTINCT
(returning all unique answers). So a single DISTINCT
acts on ALL the columns that you give it.
This makes it real hard to use DISTINCT
on a single column, while getting the other columns, without doing major extremely ugly backflips.
The correct answer is to use a GROUP BY
on the columns that you want to have unique answers: SELECT col1, col2 FROM mytable GROUP BY col2
will give you arbitrary unique col2
rows, with their col1
data as well.
The localhost refers to the device on which the code is running, in this case the emulator.
If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead.
You can read more from here.
If you're looking to capture everything up to "abc":
/^(.*?)abc/
Explanation:
( )
capture the expression inside the parentheses for access using $1
, $2
, etc.
^
match start of line
.*
match anything, ?
non-greedily (match the minimum number of characters required) - [1]
[1] The reason why this is needed is that otherwise, in the following string:
whatever whatever something abc something abc
by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/
would match "whatever whatever something abc something ". Adding the non-greedy quantifier ?
makes the regex only match "whatever whatever something ".
Using echo to print values of variables is a common Bash pitfall. Reference link:
Extending User1648825's nice simple answer (I can't comment and my edit was rejected):
@Value("${spring.profiles.active}")
private String activeProfile;
This may throw an IllegalArgumentException if no profiles are set (I get a null value). This may be a Good Thing if you need it to be set; if not use the 'default' syntax for @Value, ie:
@Value("${spring.profiles.active:Unknown}")
private String activeProfile;
...activeProfile now contains 'Unknown' if spring.profiles.active could not be resolved
You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.
Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:
SELECT * FROM foo LIMIT 10, 50
For a solution to return all results, see Thomas' answer.
The solution I am proposing detects if its not touch device and that the navbar-toggle
(hamburger menu) is not visible and makes the parent menu item revealing submenu on hover and and follow its link on click.
Also makes tne margin-top 0 because the gap between the navbar and the menu in some browser will not let you hover to the subitems
$(function(){_x000D_
function is_touch_device() {_x000D_
return 'ontouchstart' in window // works on most browsers _x000D_
|| navigator.maxTouchPoints; // works on IE10/11 and Surface_x000D_
};_x000D_
_x000D_
if(!is_touch_device() && $('.navbar-toggle:hidden')){_x000D_
$('.dropdown-menu', this).css('margin-top',0);_x000D_
$('.dropdown').hover(function(){ _x000D_
$('.dropdown-toggle', this).trigger('click').toggleClass("disabled"); _x000D_
}); _x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
$(function(){_x000D_
$("#nav .dropdown").hover(_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeIn("fast");_x000D_
$(this).toggleClass('open');_x000D_
},_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeOut("fast");_x000D_
$(this).toggleClass('open');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
In read.table
(and its relatives) it is the na.strings
argument which specifies which strings are to be interpreted as missing values NA
. The default value is na.strings = "NA"
If missing values in an otherwise numeric variable column are coded as something else than "NA
", e.g. ".
" or "N/A
", these rows will be interpreted as character
, and then the whole column is converted to character
.
Thus, if your missing values are some else than "NA
", you need to specify them in na.strings
.
You can't. If you have a method called isBiggerThanMaxLong(long)
it should always return false
.
If you were to increment the bits of Long.MAX_VALUE
, the next value should be Long.MIN_VALUE
. Read up on twos-complement and that should tell you why.
protected $primaryKey = 'SongID';
After adding to my model to tell the primary key because it was taking id(SongID) by default
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
I got the same after installing java8 from a non-permissioned account. To fix I simply reinstalled from admin user account. This created the quoted directory with file links to java exes.
The timestamp casted correctly between formats else there is a chance the fields would be misinterpreted.
Here is a working sample that is correct when two different dates (Date2, Date1) are considered from table TableXYZ.
SELECT ROUND (totalSeconds / (24 * 60 * 60), 1) TotalTimeSpendIn_DAYS,
ROUND (totalSeconds / (60 * 60), 0) TotalTimeSpendIn_HOURS,
ROUND (totalSeconds / 60) TotalTimeSpendIn_MINUTES,
ROUND (totalSeconds) TotalTimeSpendIn_SECONDS
FROM (SELECT ROUND (
EXTRACT (DAY FROM timeDiff) * 24 * 60 * 60
+ EXTRACT (HOUR FROM timeDiff) * 60 * 60
+ EXTRACT (MINUTE FROM timeDiff) * 60
+ EXTRACT (SECOND FROM timeDiff))
totalSeconds,
FROM (SELECT TO_TIMESTAMP (
TO_CHAR (Date2,
'yyyy-mm-dd HH24:mi:ss')
- 'yyyy-mm-dd HH24:mi:ss'),
TO_TIMESTAMP (
TO_CHAR (Date1,
'yyyy-mm-dd HH24:mi:ss'),
'yyyy-mm-dd HH24:mi:ss')
timeDiff
FROM TableXYZ))
Download the SDK from here: http://developer.android.com/sdk/ to C:\android-sdk\.
Then when you launch Android Studio again, it will prompt you for the SDK path just point it to: C:\android-sdk\.
Update: new download location, https://developer.android.com/studio/#command-tools
Base on accepted answer, I made an extension method to check column exist in table as
I shared for whom concern.
public static class DatatableHelper
{
public static bool ContainColumn(this DataTable table, string columnName)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
return true;
}
return false;
}
}
And use as dtTagData.ContainColumn("SystemName")
Use DATEADD in your WHERE clause:
...
WHERE date < DATEADD(day, -30, GETDATE())
You can also use abbreviation d
or dd
instead of day
.
I am using remove and replace both for refreshing content of Fragment like
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(resetFragment).commit();
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit();
This is the solution I came up with if anyone is interested.
https://kellyschronicles.wordpress.com/2017/12/16/dynamic-predicate-for-a-linq-query/
First we identify the single element type we need to use ( Of TRow As DataRow) and then identify the “source” we are using and tie the identifier to that source ((source As TypedTableBase(Of TRow)). Then we must specify the predicate, or the WHERE clause that is going to be passed (predicate As Func(Of TRow, Boolean)) which will either be returned as true or false. Then we identify how we want the returned information ordered (OrderByField As String). Our function will then return a EnumerableRowCollection(Of TRow), our collection of datarows that have met the conditions of our predicate(EnumerableRowCollection(Of TRow)). This is a basic example. Of course you must make sure your order field doesn’t contain nulls, or have handled that situation properly and make sure your column names (if you are using a strongly typed datasource never mind this, it will rename the columns for you) are standard.
options: {
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: false
}
}],
yAxes: [{
gridLines: {
drawOnChartArea: false
}
}]
}
}
The std::string.append
function isn't a good option because it doesn't accept many forms of data. A more useful alternative is to use std::stringstream
; like so:
#include <sstream>
// ...
std::stringstream ss;
//put arbitrary formatted data into the stream
ss << 4.5 << ", " << 4 << " whatever";
//convert the stream buffer into a string
std::string str = ss.str();
Alternatively, you can use Guava's Resources object:
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);
In case you encounter an error like this
mysqldump: 1044 Access denied when using LOCK TABLES
A quick workaround is to pass the –-single-transaction
option to mysqldump
.
So your command will be like this.
mysqldump --single-transaction -u user -p DBNAME > backup.sql
subprocess.Popen does exactly what you want.
from subprocess import Popen
p = Popen(['watch', 'ls']) # something long running
# ... do other stuff while subprocess is running
p.terminate()
(Edit to complete the answer from comments)
The Popen instance can do various other things like you can poll()
it to see if it is still running, and you can communicate()
with it to send it data on stdin, and wait for it to terminate.
For those who come here by search (because this thread is over 3 years old):
string entry // replace with search value
if (comboBox.Items.Contains(entry))
comboBox.SelectedIndex = comboBox.Items.IndexOf(entry);
else
comboBox.SelectedIndex = 0;
Simple solution(even though question is old)
Test1.bat
echo off
echo "Batch started"
set arg1=%1
echo "arg1 is %arg1%"
echo on
pause
CallTest1.bat
call "C:\Temp\Test1.bat" pass123
output
YourLocalPath>call "C:\Temp\test.bat" pass123
YourLocalPath>echo off
"Batch started"
"arg1 is pass123"
YourLocalPath>pause
Press any key to continue . . .
Where YourLocalPath is current directory path.
To keep things simple store the command param in variable and use variable for comparison.
Its not just simple to write but its simple to maintain as well so if later some other person or you read your script after long period of time, it will be easy to understand and maintain.
To write code inline : see other answers.
Make sure there's no hidden whitespace at the start of your XML file. Also maybe include encoding="UTF-8" (or 16? No clue) in the node.
"Conflicts" mean "parallel evolutions of a same content". So if it goes "all to hell" during a merge, it means you have massive evolutions on the same set of files.
The reason why a rebase is then better than a merge is that:
I confirm that the correct workflow in that case (evolutions on common set of files) is rebase first, then merge.
However, that means that, if you push your local branch (for backup reason), that branch should not be pulled (or at least used) by anyone else (since the commit history will be rewritten by the successive rebase).
On that topic (rebase then merge workflow), barraponto mentions in the comments two interesting posts, both from randyfay.com:
Using this technique, your work always goes on top of the public branch like a patch that is up-to-date with current
HEAD
.
(a similar technique exists for bazaar)
git push --force
(instead of a git pull --rebase
for instance)To convert a string
having the form a="[[1, 3], [2, -6]]"
I wrote yet not optimized code:
matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
matrixAr.append(row)
print matrixAr
I've always found you need both
android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
Here we go, guys! It helped me
$('.slick-slider').not('.slick-initialized').slick({
infinite: false,
slidesToShow: 1,
slidesToScroll: 1,
dots: true,
arrows: false,
touchThreshold: 9
});
>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))
I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:
public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp)
{
var parameter = Expression.Parameter(sourceType);
var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
var left = leftVisitor.Visit(exp.Body);
var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
var right = rightVisitor.Visit(newExp.Body);
var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
}
You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.
This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.
Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.
Your fiddle is updated, see here: jsfiddle
The code:
$('form').on('submit', function (e) {
var focusSet = false;
if (!$('#email').val()) {
if ($("#email").parent().next(".validation").length == 0) // only add if not added
{
$("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#email').focus();
focusSet = true;
} else {
$("#email").parent().next(".validation").remove(); // remove it
}
if (!$('#password').val()) {
if ($("#password").parent().next(".validation").length == 0) // only add if not added
{
$("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
}
e.preventDefault(); // prevent form from POST to server
if (!focusSet) {
$("#password").focus();
}
} else {
$("#password").parent().next(".validation").remove(); // remove it
}
});
The CSS:
.validation
{
color: red;
margin-bottom: 20px;
}
I double load my external css source file and change the media="screen" to media="print" and all the borders for my table were shown
Try this :
<link rel="stylesheet" media="print" href="bootstrap.css" />
<link rel="stylesheet" media="screen" href="bootstrap.css" />
I want to clear here that preg_split();
is far away from it but explode();
can be used in similar way as split();
following is the comparison between split();
and explode();
usage
<?php
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.split.php
<?php
$data = "04/30/1973";
list($month, $day, $year) = explode("/", $data);
echo $month; // foo
echo $day; // *
echo $year;
?>
URL: http://php.net/manual/en/function.explode.php
Here is how we can use it :)
You can use AT & T commands for sending sms using GSM modem.
If you don't want to grant admin permission to dashboard service account, you can create cluster admin service account.
$ kubectl create serviceaccount cluster-admin-dashboard-sa
$ kubectl create clusterrolebinding cluster-admin-dashboard-sa \
--clusterrole=cluster-admin \
--serviceaccount=default:cluster-admin-dashboard-sa
And then, you can use the token of just created cluster admin service account.
$ kubectl get secret | grep cluster-admin-dashboard-sa
cluster-admin-dashboard-sa-token-6xm8l kubernetes.io/service-account-token 3 18m
$ kubectl describe secret cluster-admin-dashboard-sa-token-6xm8l
I quoted it from giantswarm guide - https://docs.giantswarm.io/guides/install-kubernetes-dashboard/
You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.
As Paul has already mentioned add "-lm
" to link with the math library in the step where you are attempting to generate your executable.
Why for
sin()
in<math.h>
, do we need-lm
option explicitly; but, not forprintf()
in<stdio.h>
?
Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).
This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:
Standard C Library
The Standard C library is automatically searched by
cc
to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.Standard C Mathematical Library
This library supports the Base System math routines, as defined in Volume 1. The
cc
option-lm
is used to search this library.
The reasoning behind this separation was influenced by a number of factors:
The pressures that fed into the decision to put -lm
in a different library probably included, but are not limited to:
sin()
and putting it in a custom built library.In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm
.
To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected):
https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7
For general guidance on setting up a script in Google Sheets, see this quickstart guide.
To use this script:
You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist.
The above mentioned steps are taken from this link
Check out androPHP I use it for testing on android ANdroPHP.
Another option is
devtools::unload("your-package")
This apparently also deals with the issue of registered S3 methods that are not removed with unloadNamespace()
The way to do this is to set the EnableHeadersVisualStyles
flag for the data grid view to False
, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor
property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
If you do not set the EnableHeadersVisualStyles
flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
Now that Firefox Quantum 57 is out with substantial — and potentially breaking — improvements to Gecko collectively known as Stylo or Quantum CSS, you may find yourself in a situation where you have to distinguish between legacy versions of Firefox and Firefox Quantum.
From my answer here:
You can use
@supports
with acalc(0s)
expression in conjunction with@-moz-document
to test for Stylo — Gecko does not support time values incalc()
expressions but Stylo does:@-moz-document url-prefix() { @supports (animation: calc(0s)) { /* Stylo */ } }
Here's a proof-of-concept:
_x000D__x000D__x000D__x000D__x000D_body::before {_x000D_ content: 'Not Fx';_x000D_ }_x000D_ _x000D_ @-moz-document url-prefix() {_x000D_ body::before {_x000D_ content: 'Fx legacy';_x000D_ }_x000D_ _x000D_ @supports (animation: calc(0s)) {_x000D_ body::before {_x000D_ content: 'Fx Quantum';_x000D_ }_x000D_ }_x000D_ }
Targeting legacy versions of Firefox is a little tricky — if you're only interested in versions that support
@supports
, which is Fx 22 and up,@supports not (animation: calc(0s))
is all you need:@-moz-document url-prefix() { @supports not (animation: calc(0s)) { /* Gecko */ } }
... but if you need to support even older versions, you'll need to make use of the cascade, as demonstrated in the proof-of-concept above.
I had the same problem while using Jupyter Notebook, no matter what I updated in Python 3, conda, I could not get in Jupyter:
import sklearn
print (sklearn.__version__)
0.17.1
to SHOW scikit-learn-0.18.1
Finally, I removed Anaconda3 and Jupyter Notebook and reinstalled fresh. I got it to work.
http://ukitech.blogspot.com/2017/02/sklearnmodelselection.html
cmd
Tunnel all your internet traffic through a socks proxy:
netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"
View the current proxy settings:
netsh winhttp show proxy
Clear all proxy settings:
netsh winhttp reset proxy
If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.
EXAMPLE:
txt="potatoes"
print("I love ",txt,"",sep="")
This will print: I love potatoes.
Instead of: I love potatoes .
In your case, since you would be trying to get ride of the \t, do sep="\t"
None of these answers worked for me, at least not for scrolling down a facebook search result page, but I found after a lot of testing this solution:
while driver.find_element_by_tag_name('div'):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Divs=driver.find_element_by_tag_name('div').text
if 'End of Results' in Divs:
print 'end'
break
else:
continue
You can try this:
-ms-transform: scale(width,height); /* IE 9 */
-webkit-transform: scale(width,height); /* Safari */
transform: scale(width, height);
Example: image "grows" 1.3 times
-ms-transform: scale(1.3,1.3); /* IE 9 */
-webkit-transform: scale(1.3,1.3); /* Safari */
transform: scale(1.3,1.3);
One possible could be like this,
HTML
<div class="box-left-mini">
<div class="front">this div is infront</div>
<div class="behind">
this div is behind
</div>
</div>
CSS
.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
background-color:lightgreen;
}
.behind{
background-color:grey;
position:absolute;
width:100%;
height:100%;
top:0;
z-index:-1;
}
But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
This is what worked for me.
// In the console
// First install jQuery
npm install --save jquery
// and jQuery Definition
npm install -D @types/jquery
// Now, within any of the app files (ES2015 style)
import * as $ from 'jquery';
//
$('#elemId').width();
// OR
// CommonJS style - working with "require"
import $ = require('jquery')
//
$('#elemId').width();
Feb - 2017
Lately, I'm writing code with ES6
instead of typescript
and am able to import
without * as $
in the import statement
. This is what it looks like now:
import $ from 'jquery';
//
$('#elemId').width();
Good Luck.
There are a number of advantages to using Ray:
In your case, you could start Ray and define a remote function
import ray
ray.init()
@ray.remote(num_return_vals=3)
def calc_stuff(parameter=None):
# Do something.
return 1, 2, 3
and then invoke it in parallel
output1, output2, output3 = [], [], []
# Launch the tasks.
for j in range(10):
id1, id2, id3 = calc_stuff.remote(parameter=j)
output1.append(id1)
output2.append(id2)
output3.append(id3)
# Block until the results have finished and get the results.
output1 = ray.get(output1)
output2 = ray.get(output2)
output3 = ray.get(output3)
To run the same example on a cluster, the only line that would change would be the call to ray.init(). The relevant documentation can be found here.
Note that I'm helping to develop Ray.
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
I've used the following script with great success on numerous servers:
pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid
while [ -e /proc/$pid ]; do sleep 0.1; done
notes:
$INSTALLATION
contains enough of the process path that's it's totally unambiguousThis script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.
This is how I solved it:
Integer.toHexString(System.identityHashCode(object));
Looks like javax.faces.SEPARATOR_CHAR must not be equal to _
MiniDLNA uses inotify
, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.
The notify_interval
(notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval
(ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify
functionality.
This is how it looks in my /etc/minidlna.conf
:
# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes
Make sure that inotify is enabled in your kernel.
If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.
Try using something like
Creates or overwrites a file in the specified path.
An alternative answer that uses today()
method to calculate current date and then subtracts one using timedelta()
. Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
For Http Request Default Port number is 80
For Https Default Port Number is 443
For Sql Server Default Port Number is 1433
Wouldn't it just be:
SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';
That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.
If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.
Both perform the same function but driver.get(); seems more popular.
driver.navigate().to();
is best used when you are already in the middle of a script and you want to redirect from current URL to a new one. For the sake of differentiating your codes, you can use driver.get();
to launch the first URL after opening a browser instance, albeit both will work either way.
OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...
I also created the image below to show the differences at a glance:
Extracts myArchive.tar to /destinationDirectory
Commands:
cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'
Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.
Just using animate().translationY()
function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.
first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab3"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_btn_speak_now" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab2"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_menu_camera" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab1"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_dialog_map" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
Now in your java class just define all your FAB and perform the click like shown below:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
fab3 = (FloatingActionButton) findViewById(R.id.fab3);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!isFABOpen){
showFABMenu();
}else{
closeFABMenu();
}
}
});
Use the animation().translationY()
to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:
private void showFABMenu(){
isFABOpen=true;
fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}
private void closeFABMenu(){
isFABOpen=false;
fab1.animate().translationY(0);
fab2.animate().translationY(0);
fab3.animate().translationY(0);
}
Now define the above mentioned dimension inside res->values->dimens.xml as shown below:
<dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>
That's all hope this solution will help the people in future, who are searching for simple solution.
EDITED
If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github
to close the FAB on Backpress, override onBackPress() as showen below:
@Override
public void onBackPressed() {
if(!isFABOpen){
this.super.onBackPressed();
}else{
closeFABMenu();
}
}
The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub
Your code works, but the fadeIn
doesn't, because it's already visible. I think the effect you want to achieve is: fadeOut
→ load
→ fadeIn
:
var auto_refresh = setInterval(function () {
$('.View').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 15000); // refresh every 15000 milliseconds
Try it here: http://jsfiddle.net/kelunik/3qfNn/1/
Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax
and $.ajaxSetup ({ cache: false });
or the random-hack, he mentioned.
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.
The PHP documentation for time() shows an example of how you can get a date one week out. You can modify this to instead go into a loop that iterates a maximum of 7 times, get the timestamp each time, get the corresponding date, and from that get the day of the week.
Use immutableJS
import { fromJS } from 'immutable';
// An object we want to clone
let objA = {
a: { deep: 'value1', moreDeep: {key: 'value2'} }
};
let immB = fromJS(objA); // Create immutable Map
let objB = immB.toJS(); // Convert to plain JS object
console.log(objA); // Object { a: { deep: 'value1', moreDeep: {key: 'value2'} } }
console.log(objB); // Object { a: { deep: 'value1', moreDeep: {key: 'value2'} } }
// objA and objB are equalent, but now they and their inner objects are undependent
console.log(objA === objB); // false
console.log(objA.a === objB.a); // false
console.log(objA.moreDeep === objB.moreDeep); // false
Or lodash/merge
import merge from 'lodash/merge'
var objA = {
a: [{ 'b': 2 }, { 'd': 4 }]
};
// New deeply cloned object:
merge({}, objA );
// We can also create new object from several objects by deep merge:
var objB = {
a: [{ 'c': 3 }, { 'e': 5 }]
};
merge({}, objA , objB ); // Object { a: [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking
In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))
In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]:
A B C D
12 0.491683 0.137766 0.859753 -1.041487
13 0.376200 0.575667 1.534179 1.247358
14 0.428739 1.539973 1.057848 -1.254489
In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]:
A 3
B 3
C 3
D 3
dtype: int64
In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3
As in this answer Custom HTTP Header for a specific file you can use <File>
to enable CORS for a single file with this code:
<Files "index.php">
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>
If you are trying to find a View
from your Fragment
then try doing it like this:
int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;
Your code compiles just fine. However, your array initialization line is wrong:
int array[]={};
What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.
Instead, you can either initialize the array right in your original line:
int array[] = { 5, 5, 5, 5 };
Or you can declare the size and then populate it:
int array[] = new int[4];
// ...while loop
If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList
instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).
Using alias for referencing the tables to get the columns from different tables after joining them.
Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction
delegate in C#, use an ISomeBehaviour
reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
@Override
public void SomeFunction() {
// your implementation
}
});
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
// Java 8
SomeMethod(() -> { /* your implementation */ });
If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards
example :
make unittest=*
I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run
Another tool that you may want to use is APK Studio It relies howewer on third party tools: Apktool, jadx, ADB and Uber APK signer that you need to download separately.
Simple php script worked for me.
Export:
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($jobs as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$path = "http://server1:8080/jenkins/job/".$value."/config.xml";
$myfile = fopen($value.".xml", "w");
fwrite($myfile, file_get_contents($path));
fclose($myfile);
}
Import:
<?php
// add all job codes in the array
$jobs = array("job1", "job2", "job3");
foreach ($arr as $value)
{
fwrite(STDOUT, $value. " \n") or die("Unable to open file!");
$cmd = "java -jar jenkins-cli.jar -s http://server2:8080/jenkins/ create-job ".$value." < ".$value.".xml";
echo exec($cmd);
}
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
you have many HTML and java script mistakes includes:
tag, using non UTF-8 encoding for form submission, no need,...
You must use document.forms.FORMNAME
or document.forms[0]
for first appear form in page
Corrected:
function validate_frm_new_user_request()_x000D_
{_x000D_
alert('test');_x000D_
var valid = true;_x000D_
_x000D_
if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
{_x000D_
alert ( "Please enter your valid ISID Information." );_x000D_
document.forms.frm_new_user_request.u_userid.focus();_x000D_
valid = false;_x000D_
console.log("FALSE::Empty Value ");_x000D_
}_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
<tr align="left">_x000D_
<td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td align="center" colspan="4">_x000D_
<input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Below is an example where we can convert float value without any scientific notation.
DECLARE @Floater AS FLOAT = 100000003.141592653
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 10
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 100
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SELECT LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
,FORMAT(@Floater, '')
In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.
Media Queries in style-Attributes are not possible right now. But if you have to set this dynamically via Javascript. You could insert that rule via JS aswell.
document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");
This is as if the style was there in the stylesheet. So be aware of specificity.
Cross apply works well with an XML field as well. If you wish to select node values in combination with other fields.
For example, if you have a table containing some xml
<root> <subnode1> <some_node value="1" /> <some_node value="2" /> <some_node value="3" /> <some_node value="4" /> </subnode1> </root>
Using the query
SELECT
id as [xt_id]
,xmlfield.value('(/root/@attribute)[1]', 'varchar(50)') root_attribute_value
,node_attribute_value = [some_node].value('@value', 'int')
,lt.lt_name
FROM dbo.table_with_xml xt
CROSS APPLY xmlfield.nodes('/root/subnode1/some_node') as g ([some_node])
LEFT OUTER JOIN dbo.lookup_table lt
ON [some_node].value('@value', 'int') = lt.lt_id
Will return a result
xt_id root_attribute_value node_attribute_value lt_name
----------------------------------------------------------------------
1 test1 1 Benefits
1 test1 4 FINRPTCOMPANY
import UIKit
extension UIView {
func removeConstraints() { removeConstraints(constraints) }
func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }
func getAllConstraints() -> [NSLayoutConstraint] {
var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
if let superview = self.superview {
subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
if let view = constraint.firstItem as? UIView, view == self { return constraint }
return nil
}
}
return subviewsConstraints + constraints
}
class func getAllSubviews(view: UIView) -> [UIView] {
return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
}
}
print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()
It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.
It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT: Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
The \n
is just fine for all cases I've encountered. I you are working with web, use \n
and don't worry about it (unless you have had any newline-related issues).
I wouldn't recommend the HAVING
keyword for newbies, it is essentially for legacy purposes.
I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:
I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.
So I've taken a literal interpretation.
The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES
but it could be a VIEW
:
WITH PAYMENT_TALLIES (user_id, zip, tally)
AS
(
SELECT user_id, zip, COUNT(*) AS tally
FROM PAYMENT
GROUP
BY user_id, zip
)
SELECT DISTINCT *
FROM PAYMENT AS P
WHERE EXISTS (
SELECT *
FROM PAYMENT_TALLIES AS PT
WHERE P.user_id = PT.user_id
AND PT.tally > 1
);
I believe the link below will always give you the latest version of the 64-bit JRE http://javadl.sun.com/webapps/download/AutoDL?BundleId=43883
Because your button is in control
it could be that there is a validation from another control that don't allow the button to submit.
The result in my case was to add CausesValidation
property to the button:
<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" CausesValidation="False"/>
Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton
function per data structure*):
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
}
}
* except for ResizeArray
itself of course, hence this question :)
In practice I actually name it Create
to align with other helpers I define such as Tuple.Create
, Lazy.Create
[2], LazyTask.Create
etc:
namespace System.Collections.Generic
{
public static class List
{
public static List<T> Create<T>(T value) => new List<T>(1) { value };
}
}
[2]
namespace System
{
public static class Lazy
{
public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
}
}
In this case the problem arises from lost Key Pair. About this:
You can follow these steps:
In general, remember you have to allow your EC2 instance to accept inbound SSH traffic.
To do this, you have to create a specific rule for the Security Group of your EC2 instance. You can follow these steps.
Hope this can help someone as helped me.
Following on from answer's by bstoney and Snark I did some tests on the various methods:
// Test 1 (array_merge)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
$array1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);
// Test2 (foreach)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
foreach ($array2 as $v) {
$array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);
// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
array_push($array1, ...$array2);
echo sprintf("Test 3: %.06f\n", microtime(true) - $start);
Which produces:
Test 1: 0.002717
Test 2: 0.006922
Test 3: 0.004744
ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.
Whilst method 3 isn't strictly an answer to the criteria of 'not array_push' in the question, it is one line and the most high performance in all respects, I think the question was asked before the ... syntax was an option.
UPDATE 25/03/2020: I've updated the test which was flawed as the variables weren't reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn't have been affected by the testing flaw.
So, the saga continues, I will start using array_merge from now on!
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json);
you can use. The blob will most likely be of type JsonObject
which is derived from JsonValue
, but could be JsonArray
. Check the blob.JsonType
if you need to know.
And to answer you question, YES, you may replace json
with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
In my case I called the method GetFilter()
on an adapter from the TextWatcher()
method on main Activity, and I added the data with a For loop on GetFilter()
.
The solution was change the For loop to AfterTextChanged()
sub method on main Activity and delete the call to GetFilter()
I think you face three problems:
ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)
ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.
ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.
HTML:
<div id="something">... content ...</div>
CSS:
#something {
position: absolute;
height: 200px;
width: 400px;
margin: -100px 0 0 -200px;
top: 50%;
left: 50%;
}
It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like
# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"
inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules
). This answer is based on the debian wiki
To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:
for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done
This's Because!
the Solution's declaring a single scope for each iteration by using a self-function executed(anonymous one or better IIFE) and having a copy of i in it, like this:
for (var i = 1; i <= 2; i++) {
(function(){
var j = i;
setTimeout(function() { console.log(j) }, 100);
})();
}
the cleaner one would be
for (var i = 1; i <= 2; i++) {
(function(i){
setTimeout(function() { console.log(i) }, 100);
})(i);
}
The use of an IIFE(self-executed function) inside each iteration created a new scope for each iteration, which gave our timeout function callbacks the opportunity to close over a new scope for each iteration, one which had a variable with the right per-iteration value in it for us to access.
A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.
if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
--> int noop = 0; //don't do anything
}
(the breakpoint is represented by the arrow)
This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.
I haven't tested this - but it should give you a general idea of the direction you need to take.
For this to work, I'm going to assume a few things about the text of the TextView
:
TextView
consists of lines delimited with "\n"
.TextView
which will all include one operator and one number.Char
of a line.First we get the text:
String input = tv1.getText().toString();
Then we split it up for each line:
String[] lines = input.split( "\n" );
Now we need to calculate the total value:
int total = Integer.parseInt( lines[0].trim() ); //We know this is a number.
for( int i = 1; i < lines.length(); i++ ) {
total = calculate( lines[i].trim(), total );
}
The method calculate should look like this, assuming that we know the first Char
of a line is the operator:
private int calculate( String input, int total ) {
switch( input.charAt( 0 ) )
case '+':
return total + Integer.parseInt( input.substring( 1, input.length() );
case '-':
return total - Integer.parseInt( input.substring( 1, input.length() );
case '*':
return total * Integer.parseInt( input.substring( 1, input.length() );
case '/':
return total / Integer.parseInt( input.substring( 1, input.length() );
}
EDIT
So the above as stated in the comment below does "left-to-right" calculation, ignoring the normal order ( + and / before + and -).
The following does the calculation the right way:
String input = tv1.getText().toString();
input = input.replace( "\n", "" );
input = input.replace( " ", "" );
int total = getValue( input );
The method getValue
is a recursive method and it should look like this:
private int getValue( String line ) {
int value = 0;
if( line.contains( "+" ) ) {
String[] lines = line.split( "\\+" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value += getValue( lines[i] );
return value;
}
if( line.contains( "-" ) ) {
String[] lines = line.split( "\\-" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value -= getValue( lines[i] );
return value;
}
if( line.contains( "*" ) ) {
String[] lines = line.split( "\\*" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value *= getValue( lines[i] );
return value;
}
if( line.contains( "/" ) ) {
String[] lines = line.split( "\\/" );
value += getValue( lines[0] );
for( int i = 1; i < lines.length; i++ )
value /= getValue( lines[i] );
return value;
}
return Integer.parseInt( line );
}
Special cases that the recursive method does not handle:
Also the fact the we're using Integers
might give some "odd" results in some cases as e.g. 5/3 = 1.
$(document).ready(function() {
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
// var target = $(e.target).attr("href"); // activated tab
// alert (target);
$($.fn.dataTable.tables( true ) ).css('width', '100%');
$($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
} );
});
It works for me, with "autoWidth": false,
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
Alternatively to
image = image[..., np.newaxis]
in @dbliss' answer, you can also use numpy.expand_dims
like
image = np.expand_dims(image, <your desired dimension>)
For example (taken from the link above):
x = np.array([1, 2])
print(x.shape) # prints (2,)
Then
y = np.expand_dims(x, axis=0)
yields
array([[1, 2]])
and
y.shape
gives
(1, 2)
If you want to convert all elements of a
to a single numeric vector and length(a)
is greater than 1 (OK, even if it is of length 1), you could unlist
the object first and then convert.
as.numeric(unlist(a))
# [1] 10 38 66 101 129 185 283 374
Bear in mind that there aren't any quality controls here. Also, X$Days
a mighty odd name.
Here's how to disable minification on a per-bundle basis:
bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));
Sidenote: The paths used for your bundles must not coincide with any actual path in your published builds otherwise nothing will work. Also make sure to avoid using .js, .css and/or '.' and '_' anywhere in the name of the bundle. Keep the name as simple and as straightforward as possible, like in the example above.
The helper classes are shown below. Notice that in order to make these classes future-proof we surgically remove the js/css minifying instances instead of using .clear() and we also insert a mime-type-setter transformation without which production builds are bound to run into trouble especially when it comes to properly handing over css-bundles (firefox and chrome reject css bundles with mime-type set to "text/html" which is the default):
internal sealed class StyleBundleRaw : StyleBundle
{
private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");
public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(CssContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify upon unwiring the minifier we
// need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}
internal sealed class ScriptBundleRaw : ScriptBundle
{
private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");
public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(JsContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify upon unwiring the minifier we need
// to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}
internal sealed class BundleMimeType : IBundleTransform
{
private readonly string _mimeType;
public BundleMimeType(string mimeType) { _mimeType = mimeType; }
public void Process(BundleContext context, BundleResponse response)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (response == null)
throw new ArgumentNullException(nameof(response));
response.ContentType = _mimeType;
}
}
To make this whole thing work you need to install (via nuget):
WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimization 1.1.3+
And your web.config should be enriched like so:
<runtime>
[...]
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
[...]
</runtime>
<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files -->
<system.webServer>
[...]
<staticContent>
<!-- in case iis already has these mime types -->
<remove fileExtension=".otf" />
<remove fileExtension=".eot" />
<remove fileExtension=".ttf" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".otf" mimeType="font/otf" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
<!-- also vital otherwise published builds wont work https://stackoverflow.com/a/13597128/863651 -->
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
[...]
</system.webServer>
Note that you might have to take extra steps to make your css-bundles work in terms of fonts etc. But that's a different story.
Where is your gcc
?
My gcc
is in "C:\Program Files\CodeBlocks\MinGW\bin\".
"C:\Program Files\CodeBlocks\MinGW\bin\gcc" -c "foo.c"
"C:\Program Files\CodeBlocks\MinGW\bin\gcc" "foo.o" -o "foo 01.exe"
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
You can use the following to only include valid characters:
SQL
SELECT * FROM @Table
WHERE Col NOT LIKE '%[^0-9.]%'
Results
Col
---------
234.62
6435.23
2
Get the .column
parent of the this
element, get its previous sibling, then find any input there:
$(this).closest(".column").prev().find("input:first").val();
I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.
Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.
Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.
package to use: org.apache.tomcat.jdbc.pool.*
PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
p.setDriverClassName(driverClass);
p.setUsername(user);
p.setPassword(pwd);
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setValidationQueryTimeout(100);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(5);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(5);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setPoolProperties(p);
return ds;
I deleted my project (root folder) and created it again. It was the fastest and simplest way in my case.
Do not forget to save all you changes, before you delete you project!
In Word, it is possible to paste code that uses color to differentiate comments from code using "Paste Keep Source Formatting." However, if you use the pasted code to create a new style, Word automatically strips the color coded text and changes them to be black (or whatever the auto default color is). Since applying a style is the best way to ensure compliance with document format requirements, Word is not very useful for documenting software programs. Unfortunately, I don't recall Open Office being any better. The best work-around is to use the default simple text box.
In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.
flex-basis: 25%;
This will be a lot smoother when testing.
// VARIABLES
$screen-xs: 480px;
$screen-sm: 768px;
$screen-md: 992px;
$screen-lg: 1200px;
$screen-xl: 1400px;
$screen-xxl: 1600px;
// QUERIES
@media screen (max-width: $screen-lg) {
flex-basis: 25%;
}
@media screen (max-width: $screen-md) {
flex-basis: 33.33%;
}
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase
, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:
void swapCase(char *name);
or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.
Your query will work in MYSQL
if you set to disable ONLY_FULL_GROUP_BY
server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY
clause, eg
SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2
Non-Aggregated columns means the column is not pass into aggregated functions like SUM
, MAX
, COUNT
, etc..
In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.
Once this is done you can check the content of the temporary table by opening a new query window. Just use "select * from ##temptable"
Steps that worked for me on Ubuntu 8.04.2
to remove postgres 8.3
List All Postgres related packages
dpkg -l | grep postgres
ii postgresql 8.3.17-0ubuntu0.8.04.1 object-relational SQL database (latest versi
ii postgresql-8.3 8.3.9-0ubuntu8.04 object-relational SQL database, version 8.3
ii postgresql-client 8.3.9-0ubuntu8.04 front-end programs for PostgreSQL (latest ve
ii postgresql-client-8.3 8.3.9-0ubuntu8.04 front-end programs for PostgreSQL 8.3
ii postgresql-client-common 87ubuntu2 manager for multiple PostgreSQL client versi
ii postgresql-common 87ubuntu2 PostgreSQL database-cluster manager
ii postgresql-contrib 8.3.9-0ubuntu8.04 additional facilities for PostgreSQL (latest
ii postgresql-contrib-8.3 8.3.9-0ubuntu8.04 additional facilities for PostgreSQL
Remove all above listed
sudo apt-get --purge remove postgresql postgresql-8.3 postgresql-client postgresql-client-8.3 postgresql-client-common postgresql-common postgresql-contrib postgresql-contrib-8.3
Remove the following folders
sudo rm -rf /var/lib/postgresql/
sudo rm -rf /var/log/postgresql/
sudo rm -rf /etc/postgresql/
I use GenMyModel, first released in 2013. It's a real UML modeler, not a drawing tool. Your diagrams are UML-compliant, generate code and can be exported as UML/XMI files. It's web-based and free so it matches your criteria.
A very simple example:
SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%
The result should be:
Hello World!
Another way to do this:
"C1=A1&B1"
A simple array assignment works... Note that the first element of a bash
array can be addressed by just the name
without the [0]
index, ie, $md5
contains only the 32 chars of the md5sum.
md5=($(md5sum file))
echo $md5
# 53c8fdfcbb60cf8e1a1ee90601cc8fe2
The official MS line is "because it's not a functional operation" (ie it's a stateful operation).
Couldn't you do something like:
list.Select( x => x+1 )
or if you really need it in a List:
var someValues = new List<int>( list.Select( x => x+1 ) );
Try the following code :
$username='ABC';
$password='XYZ';
$URL='<URL>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]]
throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if
in if [[ -n $argument_label ]] ; then
cleans it up.
Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.
Include File "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Include File "flags-arguments.sh"
# $@ here represents all arguments passed in
for i in "$@"
do
arguments[$index]=$i;
prev_index="$(expr $index - 1)";
# this if block does something akin to "where $i contains ="
# "%=*" here strips out everything from the = to the end of the argument leaving only the label
if [[ $i == *"="* ]]
then argument_label=${i%=*}
else argument_label=${arguments[$prev_index]}
fi
if [[ -n $argument_label ]] ; then
# this if block only evaluates to true if the argument label exists in the variables array
if [[ -n ${variables[$argument_label]} ]] ; then
# dynamically creating variables names using declare
# "#$argument_label=" here strips out the label leaving only the value
if [[ $i == *"="* ]]
then declare ${variables[$argument_label]}=${i#$argument_label=}
else declare ${variables[$argument_label]}=${arguments[$index]}
fi
fi
fi
index=index+1;
done;
Your "script.sh"
. bin/includes/flags-declares.sh
# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value)
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";
. bin/includes/flags-arguments.sh
# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";
File -> Spreadsheet Settings -> (Tab) Calculation -> Recalculation (3 Options)
- On change
- On change and every minute
- On change and every hour
This affects how often NOW, TODAY, RAND, and RANDBETWEEN are updated.
but..
.. it updates only, if the functions arguments (their ranges, cells) are affected by that.
from my example
I use google spreadsheet to find out the age of a person. I have his birthday date in the format (dd.mm.yyyy) -> it's the used format here in Switzerland.
=ARRAYFORMULA(IF(ISTEXT(K4:K), IF(TODAY() - DATE(YEAR(TODAY()), MONTH(REGEXREPLACE(K4:K, "[.]", "/")), DAY(REGEXREPLACE(K4:K, "[.]", "/"))) > 0, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/")) + 1, YEAR(TODAY()) - YEAR(REGEXREPLACE(K4:K, "[.]", "/"))), IF(LEN(K4:K) > 0, IF(TODAY() - DATE(YEAR(TODAY()), MONTH(K4:K), DAY(K4:K)) > 0, YEAR(TODAY()) - YEAR(K4:K) + 1, YEAR(TODAY()) - YEAR(K4:K)), "")))
I'm using TODAY()
and I did the recalculation settings described above. -> but no automatically refresh. :-(
It updates only, if I change some value inside the ranges where the function is looking for.
So I wrote a Google Script (Tools -> Script Editor..) for that purpose.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetMaster = ss.getSheetByName("Master");
var sortRange = sheetMaster.getRange(firstRow, firstColumn, lastRow, lastColumn);
sortRange.getCell(1, 2).setValue(sortRange.getCell(1, 2).getValue());
}
You need to set numbers for firstRow
, firstColumn
, lastRow
, lastColumn
The Script get active when the spreadsheets open, writes the content of one cell into the same cell again. That's enough to trigger the TODAY()
function.
Look for more information on that link from Edward Moffett. Force google sheet formula to recalculate
Best regards,
Christoph
There should be an easier way to do this, but, depending on what you're trying to do, the best route might be to convert to a regular Python datetime object:
datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4
Based on comments below, this seems to only work in Python 2.7.x and Python 3.6+
No you cannot do that in Java. you can however write a method as follows:
boolean isContains(int i, int ... numbers) {
// code to check if i is one of the numbers
for (int n : numbers) {
if (i == n) return true;
}
return false;
}
Use git config --global core.editor mate -w
or git config --global core.editor open
as @dmckee suggests in the comments.
Reference: http://git-scm.com/docs/git-config
select * from table
where tester NOT LIKE '%username%';
The TextInput
has a TextFormatter
which can be used to format, convert and limit the types of text that can be input.
The TextFormatter
has a filter which can be used to reject input. We need to set this to reject anything that's not a valid integer. It also has a converter which we need to set to convert the string value to an integer value which we can bind later on.
Lets create a reusable filter:
public class IntegerFilter implements UnaryOperator<TextFormatter.Change> {
private final static Pattern DIGIT_PATTERN = Pattern.compile("\\d*");
@Override
public Change apply(TextFormatter.Change aT) {
return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
}
}
The filter can do one of three things, it can return the change unmodified to accept it as it is, it can alter the change in some way it deems fit or it can return null
to reject the change all together.
We will use the standard IntegerStringConverter
as a converter.
Putting it all together we have:
TextField textField = ...;
TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(), // Standard converter form JavaFX
defaultValue,
new IntegerFilter());
formatter.valueProperty().bindBidirectional(myIntegerProperty);
textField.setTextFormatter(formatter);
If you want don't need a reusable filter you can do this fancy one-liner instead:
TextFormatter<Integer> formatter = new TextFormatter<>(
new IntegerStringConverter(),
defaultValue,
c -> Pattern.matches("\\d*", c.getText()) ? c : null );
I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):
# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)
Enjoy!
You can readily do this this with the input format U.u
.
$now = DateTime::createFromFormat('U.u', microtime(true));
echo $now->format("m-d-Y H:i:s.u");
This produces the following output:
04-13-2015 05:56:22.082300
From the PHP manual page for date formats:
http://php.net/manual/en/function.date.php
Thanks goes to giggsey for pointing out a flaw in my original answer, adding number_format()
to the line should fix the case of the exact second. Too bad it doesn't feel quite as elegant any more...
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
http://php.net/manual/en/function.number-format.php
A note on time zones in response to DaVe.
Normally the createFromFormat()
method will use the local time zone if one is not specified.
http://php.net/manual/en/datetime.createfromformat.php
However, the technique described here is initialising the DateTime object using microtime()
which returns the number of seconds elapsed since the Unix Epoch (01 Jan 1970 00:00:00 GMT).
http://php.net/manual/en/function.microtime.php
This means that the DateTime object is implicitly initialised to UTC, which is fine for server internal tasks that just want to track elapsed time.
If you need to display the time for a particular time zone then you need to set it accordingly. However, this should be done as a separate step after the initialisation (not using the third parameter of createFromFormat()
) because of the reasons discussed above.
The setTimeZone()
method can be used to accomplish this requirement.
http://php.net/manual/en/datetime.settimezone.php
As an example:
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
echo $now->format("m-d-Y H:i:s.u") . '<br>';
$local = $now->setTimeZone(new DateTimeZone('Australia/Canberra'));
echo $local->format("m-d-Y H:i:s.u") . '<br>';
Produces the following output:
10-29-2015 00:40:09.433818
10-29-2015 11:40:09.433818
Note that if you want to input into mysql, the time format needs to be:
format("Y-m-d H:i:s.u")
BASEPAIRS = { "T": "A", "A": "T", "G": "C", "C": "G" } What would you use?
Maybe:
static const char basepairs[] = "ATAGCG";
// lookup:
if (const char* p = strchr(basepairs, c))
// use p[1]
;-)
Open studio.vmoptions and change JVM options
studio.vmoptions locates at /Applications/Android\ Studio.app/bin/studio.vmoptions (Mac OS). In my machine, it looks like
-Xms128m
-Xmx800m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops
Change to
-Xms256m
-Xmx1024m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops
And restart Android Studio
See more Android Studio website
I'm not gonna claim that this is more elegant than the highest-voted solution...but this is cool (well, at least in my mind LOL) in its own way:
$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"
"open $server
user $user $password
binary
cd $dir
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in
As you can see, it uses that dinky built-in windows FTP client. Much shorter and straightforward, too. Yes, I've actually used this and it works!
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
You can save the loop, initialization is already made to 0. Even for a local variable.
But please correct the place where you place the brackets, for readability (recognized best-practice):
int[] arr = new int[10];
You can do this with GNU grep's perl mode:
echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o
-P
means Perl-style, and -o
means match only.
This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.
try {
$content = file_get_contents($site);
} catch(\Exception $e) {
return 'The file was not found';
}
to also check blank string, I suggest following
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty fn:trim(var1)}">
</c:if>
It also handles nulls
Since unpaidMembers
is a dictionary it always returns two values when called with .items()
- (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..]
.
You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:
Worksheets("Sheet1").Range("B2:C3").Locked = False
Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:
Worksheets("Sheet1").Protect UserInterfaceOnly:=True
or
Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)
I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
Here is a practical example of Anchor tag with different
So it was a problem of encoding. Iconv solves the problem
curl 'http://www.multitran.ru/c/m.exe?CL=1&s=hello&l1=1' | iconv -f windows-1251 | tr -dc '[:print:]' | ...
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
You have to run 'bibtex':
latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
If you want to use CSS3:
position:absolute;
left:calc(50% - PutTheSizeOfTheHalfOfYourElementpx);
You might want to do further searches to figure out how to get the percentage to fit your element's width.
I got this error when I was playing around while reading progit. I made a local repository, then fetched it in another repo on the same file system, made an edit and tried to push. After reading NowhereMan's answer, a quick fix was to go to the "remote" directory and temporarily checkout another commit, push from the directory I made changes in, then go back and put the head back on master.
Anything having to do with formatting (especially place of '{' and other block character) is always a pain to enforce.
Even with an automatic format at each source file checking, you can not be sure every developer will ever always use the same formatter, with the same formatting set of rules...
And then you have to merge those files back to trunk. And you commit suicide ;)
You can apply your style to all the div and re-initialize the last one with :last-child:
for example in CSS:
.yourclass{
border: 1px solid blue;
}
.yourclass:last-child{
border: 0;
}
or in SCSS:
.yourclass{
border: 1px solid rgba(255, 255, 255, 1);
&:last-child{
border: 0;
}
}
When you want to have wide characters stored in your string. wide
depends on the implementation. Visual C++ defaults to 16 bit if i remember correctly, while GCC defaults depending on the target. It's 32 bits long here. Please note wchar_t (wide character type) has nothing to do with unicode. It's merely guaranteed that it can store all the members of the largest character set that the implementation supports by its locales, and at least as long as char. You can store unicode strings fine into std::string
using the utf-8
encoding too. But it won't understand the meaning of unicode code points. So str.size()
won't give you the amount of logical characters in your string, but merely the amount of char or wchar_t elements stored in that string/wstring. For that reason, the gtk/glib C++ wrapper folks have developed a Glib::ustring
class that can handle utf-8.
If your wchar_t is 32 bits long, then you can use utf-32
as an unicode encoding, and you can store and handle unicode strings using a fixed (utf-32 is fixed length) encoding. This means your wstring's s.size()
function will then return the right amount of wchar_t elements and logical characters.
Use Html.Raw()
. Phil Haack posted a nice syntax guide at http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx.
<div class='content'>
@Html.Raw( Model.Content )
</div>
NSAttributedString *attributedText =[[[NSAttributedString alloc]
initWithString:joyMeComment.content
attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:TextFont]}] autorelease];
CGRect paragraphRect =
[attributedText boundingRectWithSize:CGSizeMake(kWith, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
contentSize = paragraphRect.size;
contentSize.size.height+=10;
label.frame=contentSize;
if label's frame not add 10 this method will never work! hope this can help you! goog luck.
I just went through this and configured it with the following:
Ubuntu 16.04
Tomcat 8.5.9
Apache2.4.25
APR 1.5.2
Tomcat-native 1.2.10
Java 8
These are the steps i used based on the older posts here:
sudo apt-get update
sudo apt-get install libtcnative-1
sudo apt-get install make
sudo apt-get install gcc
sudo apt-get install openssl
sudo apt-get install libssl-dev
cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install
cd /usr/local/apr/lib/
ls
libapr-1.la
cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native
sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install
sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'
sudo service tomcat restart
List of Integer
.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
Within Spring Boot 2.4 it is
sec:authorize="hasAnyRole('ROLE_ADMIN')
Ensure that you have
thymeleaf-extras-springsecurity5
in your dependencies. Also make sure that you include the namespace
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
in your html...
Use the form Initialize event, e.g.:
Private Sub UserForm_Initialize()
TextBox1.Value = Format(Date, "mm/dd/yyyy")
End Sub