I think I found the answer:
convert(nvarchar(50), RequestID)
Here's the link where I found this info:
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
git branch copyOfMyBranch MyBranch
This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).
I find that if I try things that others say do not work, it's how I learn the most.
<p> </p>
<p>README.txt</p>
<p> </p>
<div id="list">
<p><iframe src="README.txt" frameborder="0" height="400"
width="95%"></iframe></p>
</div>
This worked for me. I used the yellow background-color that I set in the stylesheet.
#list p {
font: arial;
font-size: 14px;
background-color: yellow ;
}
The simplest possible solution I found was:
In your markup:
<a [href]="location.path()">Reload</a>
and in your component typescript file:
constructor(
private location: Location
) { }
You can also "fix" this by replacing the image with its inline Base64 representation:
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only. img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
If you're already using JavaScript to center stuff when the screen is too small (as per your comment for your header), why not just undo floats/margins with JavaScript while you're at it and use floats and margins normally.
You could even use CSS media queries to reduce the amount JavaScript you're using.
I wouldn't do it. Use virtual PCs instead. It might take a little setup, but you'll thank yourself in the long run. In my experience, you can't really get them cleanly installed side by side and unless they are standalone installs you can't really verify that it is 100% true-to-browser rendering.
Update: Looks like one of the better ways to accomplish this (if running Windows 7) is using Windows XP mode to set up multiple virtual machines: Testing Multiple Versions of IE on one PC at the IEBlog.
Update 2: (11/2014) There are new solutions since this was last updated. Microsoft now provides VMs for any environment to test multiple versions of IE: Modern.IE
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
Go to my.ini
file at the below path in windows
C:\ProgramData\MySQL\MySQL Server 8.0\my.ini
and comment the below line
#bind-address=127.0.0.1
Then restart the MySQL server and connect.
Then you would be able to connect to MySQL from other IP address/machine.
Even if old, this seems to be a popular questions, so I'll post another solution, which I think is very elegant:
http://fiveminutelessons.com/learn-microsoft-excel/using-multiple-if-statements-excel
It's elegant because it uses just the IF function. Basically, it boils down to this:
if(condition, choose/use a value from the table, if(condition, choose/use another value from the table...
And so on
Works beautifully, even better than HLOOKUP or VLOOOKUP
but... Be warned - there is a limit to the number of nested if statements excel can handle.
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
In JavaScript, there are no integers but only Number
s, which are implemented as double precision floating point numbers.
It means that if a Number a
is large enough, it can be considered equal to three consecutive integers:
a = 100000000000000000_x000D_
if (a == a+1 && a == a+2 && a == a+3){_x000D_
console.log("Precision loss!");_x000D_
}
_x000D_
True, it's not exactly what the interviewer asked (it doesn't work with a=0
), but it doesn't involve any trick with hidden functions or operator overloading.
For reference, there are a==1 && a==2 && a==3
solutions in Ruby and Python. With a slight modification, it's also possible in Java.
With a custom ==
:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Or an increasing a
:
def a
@a ||= 0
@a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
It's possible to modify Java Integer
cache:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
Integer a = 42;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Bad idea.");
}
}
}
This post is old, but I change your code to:
scope.$watch("assignments", function (value) {//I change here
var val = value || null;
if (val)
element.dataTable({"bDestroy": true});
});
}
see jsfiddle.
I hope it helps you
I can't find a single reference that state that it's possible without involving the serverside.
MSDN on:
From browserLanguage:
In Microsoft Internet Explorer 4.0 and earlier, the browserLanguage property reflects the language of the installed browser's user interface. For example, if you install a Japanese version of Windows Internet Explorer on an English operating system, browserLanguage would be ja.
In Internet Explorer 5 and later, however, the browserLanguage property reflects the language of the operating system regardless of the installed language version of Internet Explorer. However, if Microsoft Windows 2000 MultiLanguage version is installed, the browserLanguage property indicates the language set in the operating system's current menus and dialogs, as found in the Regional Options of the Control Panel. For example, if you install a Japanese version of Internet Explorer 5 on an English (United Kingdom) operating system, browserLanguage would be en-gb. If you install Windows 2000 MultiLanguage version and set the language of the menus and dialogs to French, browserLanguage would be fr, even though you have a Japanese version of Internet Explorer.
Note This property does not indicate the language or languages set by the user in Language Preferences, located in the Internet Options dialog box.
Furthermore, it looks like browserLanguage
is deprecated cause IE8 doesn't list it
Create a taxonomy field category (field name = post_category) and import it in your template as shown below:
<?php
$categ = get_field('post_category');
$args = array( 'posts_per_page' => 6,
'category_name' => $categ->slug );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
//your code here
<?php endforeach;
wp_reset_postdata();?>
As others have said, any compiler worth its salt will generate practically identical code. Any difference in performance is negligible - you are micro-optimizing.
The real question is, what is more readable? And that's the for
loop (at least IMHO).
This is because in this case the char
type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u
interprets the number as a large positive number:
212 = 0xD4
When it is sign-extended, FF
s are pre-pended to your number, so it becomes
0xFFFFFFD4 = 4294967252
which is the number that gets printed.
Note that this behavior is specific to your implementation. According to C99 specification, all char
types are promoted to (signed) int
, because an int
can represent all values of a char
, signed or unsigned:
6.1.1.2: If an
int
can represent all values of the original type, the value is converted to anint
; otherwise, it is converted to anunsigned int
.
This results in passing an int
to a format specifier %u
, which expects an unsigned int
.
To avoid undefined behavior in your program, add explicit type casts as follows:
unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);
char
up to the implementation. See this question for more details.
Use OnItemClickListener
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
When you click on a row a listener is fired. So you setOnClickListener
on the listview and use the annonymous inner class OnItemClickListener
.
You also override onItemClick
. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).
Using the position you get the item .
Edit : From your comments i assume you need to set the adapter o listview
So assuming your activity extends ListActivtiy
setListAdapter(adapter);
Or if your activity class extends Activity
ListView lv = (ListView) findViewById(R.id.listview1);
//initialize adapter
lv.setAdapter(adapter);
According to MSDN the method Guid.ToString(string format)
returns a string representation of the value of this Guid instance, according to the provided format specifier.
Examples:
guidVal.ToString()
or guidVal.ToString("D")
returns 32 hex digits
separated by hyphens: 00000000-0000-0000-0000-000000000000
guidVal.ToString("N")
returns 32 hex digits:00000000000000000000000000000000
guidVal.ToString("B")
returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
guidVal.ToString("P")
returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)
I have found this link
I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:
git fsck --full
git reflog expire --expire=now --all
git gc --prune=now
Found a way to grant Windows Service access to Network Drive.
Take Windows Server 2012 with NFS Disk for example:
Step 1: Write a Batch File to Mount.
Write a batch file, ex: C:\mount_nfs.bat
echo %time% >> c:\mount_nfs_log.txt
net use Z: \\{your ip}\{netdisk folder}\ >> C:\mount_nfs_log.txt 2>&1
Step 2: Mount Disk as NT AUTHORITY/SYSTEM.
Open "Task Scheduler", create a new task:
After these two simple steps, my Windows ActiveMQ Service run under "Local System" priviledge, perform perfectly without login.
From python3k, the startup need the encodings module, which can be found in PYTHONHOME\Lib directory. In fact, the API Py_Initialize () do the init and import the encodings module. Make sure PYTHONHOME\Lib is in sys.path and check the encodings module is there.
also check the PGHOST variable:
ECHO $PGHOST
to see if it matches the local machine name
Here are two ways to do the same thing, with or without jQuery:
// jquery way_x000D_
$(document).ready(function () {_x000D_
_x000D_
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];_x000D_
_x000D_
var tr;_x000D_
for (var i = 0; i < json.length; i++) {_x000D_
tr = $('<tr/>');_x000D_
tr.append("<td>" + json[i].User_Name + "</td>");_x000D_
tr.append("<td>" + json[i].score + "</td>");_x000D_
tr.append("<td>" + json[i].team + "</td>");_x000D_
$('table').first().append(tr);_x000D_
} _x000D_
});_x000D_
_x000D_
// without jquery_x000D_
function ready(){_x000D_
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];_x000D_
const table = document.getElementsByTagName('table')[1];_x000D_
json.forEach((obj) => {_x000D_
const row = table.insertRow(-1)_x000D_
row.innerHTML = `_x000D_
<td>${obj.User_Name}</td>_x000D_
<td>${obj.score}</td>_x000D_
<td>${obj.team}</td>_x000D_
`;_x000D_
});_x000D_
};_x000D_
_x000D_
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){_x000D_
ready();_x000D_
} else {_x000D_
document.addEventListener('DOMContentLoaded', ready);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<th>User_Name</th>_x000D_
<th>score</th>_x000D_
<th>team</th>_x000D_
</tr>_x000D_
</table>'_x000D_
<table>_x000D_
<tr>_x000D_
<th>User_Name</th>_x000D_
<th>score</th>_x000D_
<th>team</th>_x000D_
</tr>_x000D_
</table>
_x000D_
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
$('#userNav').change(function() {
window.location = $(':selected',this).attr('href')
});
<select id="userNav">
<option></option>
<option href="http://google.com">Goolge</option>
<option href="http://duckduckgo.com">Go Go duck</option>
</select>
This works for the href in an option that is selected
Python(the interpreter) is compiled.
Proof: It won't even compile your code if it contains syntax error.
Example 1:
print("This should print")
a = 9/0
Output:
This should print
Traceback (most recent call last):
File "p.py", line 2, in <module>
a = 9/0
ZeroDivisionError: integer division or modulo by zero
Code gets compiled successfully. First line gets executed (
ZeroDivisionError
(run time error) .
Example 2:
print("This should not print")
/0
Output:
File "p.py", line 2
/0
^
SyntaxError: invalid syntax
Conclusion: If your code file contains
SyntaxError
nothing will execute as compilation fails.
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
on ubuntu you can try gnome-open.
$ gnome-open http://www.google.com
var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
// There exists one with size 200 and is stored in item now
}
else {
// There is no PricePublicModel with size 200
}
If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.
Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task
that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await
operator.
Most of the time, you'll be using await
on an expression of type Task
. Task's implementation of the await
pattern is "smart" in that it defers to the SynchronizationContext
, which basically causes the following to happen:
await
is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.await
is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.
.... backing up! ....
I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await
on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:
WebRequest.GetResponse()
YourCode.HelperMethod()
YourCode.AnotherMethod()
YourCode.EventHandlerMethod()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopThen once the code has been transformed to use async, you'll typically end up with
WebRequest.GetResponseAsync()
YourCode.HelperMethodAsync()
YourCode.AnotherMethodAsync()
YourCode.EventHandlerMethodAsync()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopActually Answering
The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.
Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:
var customerList = TaskEx.RunEx(GetCustomers).Result;
The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).
The difference between from datetime import datetime and normal import datetime is that , you are dealing with a module at one time and a class at other.
The strptime function only exists in the datetime class so you have to import the class with the module otherwise you have to specify datetime twice when calling this function.
The thing here is that , the class name and the module name has been given the same name so it creates a bit of confusuion.
If you're willing to give up a hint of abstraction, then you could use a custom wrapper class which simply passes everything through to the PDO. Say, something like this: (Warning, code untested)
class SQLitePDOWrapper
{
private $pdo;
public function __construct( $dns, $uname = null, $pwd = null, $opts = null )
{
$this->pdo = new PDO( $dns, $unam, $pwd, $opts );
}
public function __call( $nm, $args )
{
$ret = call_user_func_array( array( $this->pdo, $nm ), $args );
if( $ret instanceof PDOStatement )
{
return new StatementWrapper( $this, $ret, $args[ 0 ] );
// I'm pretty sure args[ 0 ] will always be your query,
// even when binding
}
return $ret;
}
}
class StatementWrapper
{
private $pdo; private $stat; private $query;
public function __construct( PDO $pdo, PDOStatement $stat, $query )
{
$this->pdo = $pdo;
$this->stat = $stat;
this->query = $query;
}
public function rowCount()
{
if( strtolower( substr( $this->query, 0, 6 ) ) == 'select' )
{
// replace the select columns with a simple 'count(*)
$res = $this->pdo->query(
'SELECT COUNT(*)' .
substr( $this->query,
strpos( strtolower( $this->query ), 'from' ) )
)->fetch( PDO::FETCH_NUM );
return $res[ 0 ];
}
return $this->stat->rowCount();
}
public function __call( $nm, $args )
{
return call_user_func_array( array( $this->stat, $nm ), $args );
}
}
When trying to remove gems installed as root, xargs seems to halt when it encounters an error trying to uninstall a default gem:
sudo gem list | cut -d" " -f1 | xargs gem uninstall -aIx
# ERROR: While executing gem ... (Gem::InstallError)
# gem "test-unit" cannot be uninstalled because it is a default gem
This won't work for everyone, but here's what I used instead:
sudo for gem (`gem list | cut -d" " -f1`); do gem uninstall $gem -aIx; done
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
Please see this article:
Here is some code to determine what is the type of your machine
int num = 1; if(*(char *)&num == 1) { printf("\nLittle-Endian\n"); } else { printf("Big-Endian\n"); }
Install all thru terminal:
npm install lodash --save
tsd install lodash --save
Add paths in index.html
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
paths: {
lodash: './node_modules/lodash/lodash.js'
}
});
System.import('app/init').then(null, console.error.bind(console));
</script>
Import lodash at the top of the .ts file
import * as _ from 'lodash'
As commented by Chris, enums require much more memory on Android that adds up as they keep being used everywhere. You should try IntDef or StringDef instead, which use annotations so that the compiler validates passed values.
public abstract class ActionBar {
...
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention(RetentionPolicy.SOURCE)
public @interface NavigationMode {}
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
@NavigationMode
public abstract int getNavigationMode();
public abstract void setNavigationMode(@NavigationMode int mode);
It can also be used as flags, allowing for binary composition (OR / AND operations).
EDIT: It seems that transforming enums into ints is one of the default optimizations in Proguard.
os._exit()
:
exit(0)
:
exit(1)
:
sys.exit()
:
quit()
:
Basically they all do the same thing, however, it also depends on what you are doing it for.
I don't think you left anything out and I would recommend getting used to quit()
or exit()
.
You would use sys.exit()
and os._exit()
mainly if you are using big files or are using python to control terminal.
Otherwise mainly use exit()
or quit()
.
You can declare globals by augmenting the window interface:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
Sources:
This works for me in the current version 2.7.1
:
function colorizePercentageChart(myObjBar) {
var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {
var color = "green";
if(parseFloat(bars[i]) < 95){
color = "yellow";
}
if(parseFloat(bars[i]) < 50){
color = "red";
}
console.log(color);
myObjBar.data.datasets[0].backgroundColor[i] = color;
}
myObjBar.update();
}
Suppose we have three anchor tags like ,
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
now in script
$(".testClick").click(function () {
var anchorValue= $(this).attr("href");
alert(anchorValue);
});
use this keyword instead of className (testClick)
You could try to kill the PHP process:
exec('kill -9 ' . getmypid());
This worked for me:
jQuery('#tblPaging').dataTable({
"sort": true,
"pageLength": 20
});
In HTML, the <br/>
tag breaks the line. So, there's no sense to use an ASCII character for it.
In CSS we can use \A
for line break:
.selector::after{
content: '\A';
}
But if you want to display <br>
in the HTML as text then you can use:
<br> // < denotes to < sign and > denotes to > sign
You should reorganize your code so that you call session_start()
exactly once per page execution.
I have used redux-form and formik in the past, and recently React introduced Hook, and i have built a custom hook for it. Please check it out and see if it make your form validation much easier.
Github: https://github.com/bluebill1049/react-hook-form
Website: http://react-hook-form.now.sh
with this approach, you are no longer doing controlled input too.
example below:
import React from 'react'
import useForm from 'react-hook-form'
function App() {
const { register, handleSubmit, errors } = useForm() // initialise the hook
const onSubmit = (data) => { console.log(data) } // callback when validation pass
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstname" ref={register} /> {/* register an input */}
<input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
{errors.lastname && 'Last name is required.'} {/* error message */}
<input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
{errors.age && 'Please enter number for age.'} {/* error message */}
<input type="submit" />
</form>
)
}
Recompile without optimizations (-O0 on gcc).
You can use strcmp
:
break x:20 if strcmp(y, "hello") == 0
20
is line number, x
can be any filename and y
can be any variable.
If the texts has different sizes and they must be underlined this is the solution:
<table>
<tr>
<td class='left'>January</td>
<td class='right'>2014</td>
</tr>
</table>
css:
table{
width: 100%;
border-bottom: 2px solid black;
/*this is the size of the small text's baseline over part (˜25px*3/4)*/
line-height: 19.5px;
}
table td{
vertical-align: baseline;
}
.left{
font-family: Arial;
font-size: 40px;
text-align: left;
}
.right{
font-size: 25px;
text-align: right;
}
Following are few options available to change Heap Size.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
java -Xmx256m TestData.java
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
Not plumbing, but I have these in my .gitconfig:
lsum = log -n 1 --pretty=format:'%s'
lmsg = log -n 1 --pretty=format:'%s%n%n%b'
That's "last summary" and "last message". You can provide a commit to get the summary or message of that commit. (I'm using 1.7.0.5 so don't have %B.)
Though you cannot convert an OutputStream to an InputStream, java provides a way using PipedOutputStream and PipedInputStream that you can have data written to a PipedOutputStream to become available through an associated PipedInputStream.
Sometime back I faced a similar situation when dealing with third party libraries that required an InputStream instance to be passed to them instead of an OutputStream instance.
The way I fixed this issue is to use the PipedInputStream and PipedOutputStream.
By the way they are tricky to use and you must use multithreading to achieve what you want. I recently published an implementation on github which you can use.
Here is the link . You can go through the wiki to understand how to use it.
I think you're going to need separate lines for each segment:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random(size=(2,10))
for i in range(0, len(x), 2):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
plt.show()
(The numpy
import is just to set up some random 2x10 sample data)
Add build.gradle in-app level aaptOptions { cruncherEnabled = false }
A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.
UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.
Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.
You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.
You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.
use getBoundingClientRect
if $el
is the actual DOM object:
var top = $el.getBoundingClientRect().top;
Fiddle will show that this will get the same value that jquery's offset top will give you
Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses
https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)
offset: function( options ) {
//...
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
}
You cannot install app bundle [NAME].aab
directly to android device because it is publishing format, but there is way to extract the required apk
from bundle
and install it to you device, the process is as follow
java -jar bundletool.jar build-apks --bundle=bundleapp.aab --output=out_bundle_archive_set.apks
out_bundle_archive_set.apks
, just rename it to out_bundle_archive_set.zip
and extract the zip file, jump into the folder out_bundle_archive_set > standalones
, where you will seee a list of all the apks There goes the reference from android developers for bundle tools link
Calling scp
command via subprocess doesn't allow to receive the progress report inside the script. pexpect
could be used to extract that info:
import pipes
import re
import pexpect # $ pip install pexpect
def progress(locals):
# extract percents
print(int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination]))
pexpect.run(command, events={r'\d+%': progress})
Eclipse is the most widely used development environment for the Android platform. The reason is that even Google itself providing the plug-in to be added in eclipse and start developing the applications. I have tried installing it from the eclipse market place, it is very easy and simple to create the android application. set up also very simple.
You might need to collect the stats as you go, but @@ROWCOUNT
captures this:
declare @Fish table (
Name varchar(32)
)
insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT --gives 1
update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3
The Windows API has the functions UrlEscape/UrlUnescape, exported by shlwapi.dll, for this task.
A simpler way, if you are using .NET 3.5, is to use XDocument
and XmlSchemaSet
validation.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
See the MSDN documentation for more assistance.
Quoting from Books Online:
Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions.
Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped using DROP TABLE:
Issue maybe occured because of the file/script created/downloaded from a windows machine. Please try converting into linux file format.
dos2unix ./script_name.sh
or
dos2unix ~/.bashrc
Check the available projects by running: gcloud projects list
. This will give you a list of projects which you can access.
To switch between projects: gcloud config set project <project-id>
.
Also, I recommend checking the active config before making any change to gcloud config. You can do so by running: gcloud config list
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.
Using plural for all methods is more practical at least in one aspect: if you're developing and testing a resource API using Postman (or similar tool), you don't need to edit the URI when switching from GET to PUT to POST etc.
If you could use something other than 'awk' , then try this instead
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.
I had the same problem, none of the solutions listed here worked. The problem was my source files where not inside the right folder.
The directory structure MUST be :
[project]\[module]\src\main\java\[yourpackage]\[yourclass.java]
You'd use REGEXP_REPLACE
in order to remove all non-digit characters from a string:
select regexp_replace(column_name, '[^0-9]', '')
from mytable;
or
select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;
Of course you can write a function extract_number
. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.
create function extract_number(in_number varchar2) return varchar2 is
begin
return regexp_replace(in_number, '[^[:digit:]]', '');
end;
try this one. it worked for me $('input[type="radio"][name="name"]:checked').val();
To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");
To use the EF core SqlServer provider and compile the above code install the EF SqlServer package
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
After compilation before running the code do the following for the first time
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update
To run the code
dotnet run
In response to your clarification...
You could use ctypes to execute the c function "strcasecmp". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link for Win32 help):
from ctypes import *
libc = CDLL("libc.so.6") // see link above for Win32 help
libc.strcasecmp("THIS", "this") // returns 0
libc.strcasecmp("THIS", "THAT") // returns 8
may also want to reference strcasecmp documentation
Not really sure this is any faster or slower (have not tested), but it's a way to use a C function to do case insensitive string comparisons.
~~~~~~~~~~~~~~
ActiveState Code - Recipe 194371: Case Insensitive Strings is a recipe for creating a case insensitive string class. It might be a bit over kill for something quick, but could provide you with a common way of handling case insensitive strings if you plan on using them often.
I have just encountered a very similar problem.
Like you, my connection string appeared correct--and indeed, exactly the same connection string was working in other scenarios.
The problem turned out to be a lack of resources. 19 times out of 20, I would see the "Could not find installable ISAM," but once or twice (without any code changes at all), it would yield "Out of memory" instead.
Rebooting the machine "solved" the problem (for now...?). This happened using Jet version 4.0.9505.0 on Windows XP.
This is what finally worked for me.
Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080
Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)
I had the same issue. I found that I forgot to add selenium-2.53.0/selenium-java-2.53.0-srcs.jar file to my project's Reference library.
First off, I think mplot3D
worked a bit differently in matplotlib
version 0.99
than it does in the current version of matplotlib
.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99
, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib
.
If you're running version 0.99
, try doing this instead of using using the projection
keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib
1.0.x
, as well, not just 0.99
.
My actual version of pdfgrep (1.3.0) allows the following:
pdfgrep -HiR 'pattern' /path
When doing pdfgrep --help
:
It works well on my Ubuntu.
I made a simple class that makes ripple buttons, i never needed it in the end so its not the best, But here it is:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
public class RippleView extends Button
{
private float duration = 250;
private float speed = 1;
private float radius = 0;
private Paint paint = new Paint();
private float endRadius = 0;
private float rippleX = 0;
private float rippleY = 0;
private int width = 0;
private int height = 0;
private OnClickListener clickListener = null;
private Handler handler;
private int touchAction;
private RippleView thisRippleView = this;
public RippleView(Context context)
{
this(context, null, 0);
}
public RippleView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public RippleView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
if (isInEditMode())
return;
handler = new Handler();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
}
@Override
protected void onDraw(@NonNull Canvas canvas)
{
super.onDraw(canvas);
if(radius > 0 && radius < endRadius)
{
canvas.drawCircle(rippleX, rippleY, radius, paint);
if(touchAction == MotionEvent.ACTION_UP)
invalidate();
}
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event)
{
rippleX = event.getX();
rippleY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_UP;
radius = 1;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
speed = endRadius / duration * 10;
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
if(radius < endRadius)
{
radius += speed;
paint.setAlpha(90 - (int) (radius / endRadius * 90));
handler.postDelayed(this, 1);
}
else
{
clickListener.onClick(thisRippleView);
}
}
}, 10);
invalidate();
break;
}
case MotionEvent.ACTION_CANCEL:
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
radius = 0;
invalidate();
break;
}
case MotionEvent.ACTION_DOWN:
{
getParent().requestDisallowInterceptTouchEvent(true);
touchAction = MotionEvent.ACTION_UP;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
paint.setAlpha(90);
radius = endRadius/4;
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE:
{
if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
radius = 0;
invalidate();
break;
}
else
{
touchAction = MotionEvent.ACTION_MOVE;
invalidate();
return true;
}
}
}
return false;
}
@Override
public void setOnClickListener(OnClickListener l)
{
clickListener = l;
}
}
EDIT
Since many people are looking for something like this i made a class that can make other views have the ripple effect:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
public class RippleViewCreator extends FrameLayout
{
private float duration = 150;
private int frameRate = 15;
private float speed = 1;
private float radius = 0;
private Paint paint = new Paint();
private float endRadius = 0;
private float rippleX = 0;
private float rippleY = 0;
private int width = 0;
private int height = 0;
private Handler handler = new Handler();
private int touchAction;
public RippleViewCreator(Context context)
{
this(context, null, 0);
}
public RippleViewCreator(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public RippleViewCreator(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
if (isInEditMode())
return;
paint.setStyle(Paint.Style.FILL);
paint.setColor(getResources().getColor(R.color.control_highlight_color));
paint.setAntiAlias(true);
setWillNotDraw(true);
setDrawingCacheEnabled(true);
setClickable(true);
}
public static void addRippleToView(View v)
{
ViewGroup parent = (ViewGroup)v.getParent();
int index = -1;
if(parent != null)
{
index = parent.indexOfChild(v);
parent.removeView(v);
}
RippleViewCreator rippleViewCreator = new RippleViewCreator(v.getContext());
rippleViewCreator.setLayoutParams(v.getLayoutParams());
if(index == -1)
parent.addView(rippleViewCreator, index);
else
parent.addView(rippleViewCreator);
rippleViewCreator.addView(v);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas)
{
super.dispatchDraw(canvas);
if(radius > 0 && radius < endRadius)
{
canvas.drawCircle(rippleX, rippleY, radius, paint);
if(touchAction == MotionEvent.ACTION_UP)
invalidate();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event)
{
return true;
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event)
{
rippleX = event.getX();
rippleY = event.getY();
touchAction = event.getAction();
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
{
getParent().requestDisallowInterceptTouchEvent(false);
radius = 1;
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
speed = endRadius / duration * frameRate;
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
if(radius < endRadius)
{
radius += speed;
paint.setAlpha(90 - (int) (radius / endRadius * 90));
handler.postDelayed(this, frameRate);
}
else if(getChildAt(0) != null)
{
getChildAt(0).performClick();
}
}
}, frameRate);
break;
}
case MotionEvent.ACTION_CANCEL:
{
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
case MotionEvent.ACTION_DOWN:
{
getParent().requestDisallowInterceptTouchEvent(true);
endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
paint.setAlpha(90);
radius = endRadius/3;
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE:
{
if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
{
getParent().requestDisallowInterceptTouchEvent(false);
touchAction = MotionEvent.ACTION_CANCEL;
break;
}
else
{
invalidate();
return true;
}
}
}
invalidate();
return false;
}
@Override
public final void addView(@NonNull View child, int index, ViewGroup.LayoutParams params)
{
//limit one view
if (getChildCount() > 0)
{
throw new IllegalStateException(this.getClass().toString()+" can only have one child.");
}
super.addView(child, index, params);
}
}
What you want is %.2f
, not 2%f
.
Also, you might want to replace your %d
with a %f
;)
#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}
This will output:
When this number: 94.945600 is assigned to 2 dp, it will be: 94.95
See here for a full description of the printf formatting options: printf
If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php
. It then serves the same purpose of helpfulness and maintainability.
I normally have 2 php files for each page on my site:
welcome.php
in the root folder, containing all of the HTML markup. welcome.inc.php
in the inc
folder, containing all PHP functions specific to the welcome.php
page.EDIT: Another benefit of using the double extention .inc.php
would be that any IDE can still recognise the file as PHP code.
Yes. Problem is in wrong notation. Use:
$this->sendRequest($uri)
Instead. Or
self::staticMethod()
for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php
Yes, you can set the screen orientation programatically anytime you want using:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.
And this is how you can get the current screen orientation and set it adequatly depending on its current state:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation();
// OR: orientation = getRequestedOrientation(); // inside an Activity
// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
});
Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/
EDIT
Also, you can get the screen orientation using the Configuration
:
Activity.getResources().getConfiguration().orientation
You can not add links from CSS, you will have to do so from the HTML code explicitly. For example, something like this:
<a href="whatever.html"><li id="header"></li></a>
Try this code
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, it will clear the console.
Something like this works:
input + label::after {_x000D_
content: 'click my input';_x000D_
color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
content: 'not valid yet';_x000D_
color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
content: 'looks good';_x000D_
color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
Then add some floats or positioning to order stuff.
Another way (assuming you are using vue-router
), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;
{
path: '/mypage',
name: 'mypage',
component: MyPage,
props: (route) => ({ foo: route.query.foo })
}
Then in your component you can add the prop as normal;
props: {
foo: {
type: String,
default: null
}
},
Then it will be available as this.foo
and you can do anything you want with it (like set a watcher, etc.)
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
Use a format string to round up to two decimal places and convert the double
to a String
:
let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)
Example:
let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"
If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):
let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.
resurrection of thread at two years later. im working around this issue about days and found a simple trick for the prevent this ugly autocomplete feature:
just add a random string to form target like <form action="site.com/login.php?random=123213">
it works on recent chrome version 34.0.1847.137
update: if it does not work, give strange protocol to action like <form id="test" action="xxx://">
and fill this area later with javascript:
$('#test').attr('action', 'http://example.site/login.php');
update 2: still having issues with that, i decided to completely remove the <form>
tag and post variables via jquery. its more easy.
As of Python 3.2+, you can also accomplish this using the from_bytes
native int method:
file_size = int.from_bytes(fin.read(2), byteorder='big')
Note that this function requires you to specify whether the number is encoded in big- or little-endian format, so you will have to determine the endian-ness to make sure it works correctly.
You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>();
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
By changing the file permissions in apps/wordpress
folder mounted on MAC XAMPP-VM shown in the below screenshot.
sudo chown -R bitnami:daemon TARGET # [ Replace "TARGET" with your file/folder path ]
find TARGET -type d -print0 | xargs -0 chmod 775
find TARGET -type f -print0 | xargs -0 chmod 664
chmod 640 TARGET/wp-config.php
Source: bitnami
TARGET - Replace placeholder for your mounted filesystem wordpress path eg: '1.1.1.1/lampp/apps/wordpress'
Now you can edit your themes in VS-Code or any developer editor of your choice.
NOTE: This should be done only in your development environment. Production build permissions are different & above doesn't apply
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)
childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];
Whether you're using Team System Test or NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.
If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :
<configuration>
<appSettings>
<add key="TestValue" value="true" />
</appSettings>
</configuration>
And the test:
[TestFixture]
public class GeneralFixture
{
[Test]
public void VerifyAppDomainHasConfigurationSettings()
{
string value = ConfigurationManager.AppSettings["TestValue"];
Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
}
}
Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.
public class MyObject
{
public void Configure(MyConfigurationObject config)
{
_enabled = config.Enabled;
}
public string Foo()
{
if (_enabled)
{
return "foo!";
}
return String.Empty;
}
private bool _enabled;
}
[TestFixture]
public class MyObjectTestFixture
{
[Test]
public void CanInitializeWithProperConfig()
{
MyConfigurationObject config = new MyConfigurationObject();
config.Enabled = true;
MyObject myObj = new MyObject();
myObj.Configure(config);
Assert.AreEqual("foo!", myObj.Foo());
}
}
My "disappeared" folder was libraries/fof
.
If I deleted it, then ran an update, it wouldn't show up.
cd libaries
svn up
(nothing happens).
But updating with the actual name:
svn update fof
did the trick and it was updated. So I exploded my (manually tar-archived) working copy over it and recommitted. Easiest solution.
i feel above logics for hover is incorrect. it just inverse when mouse hovers. i have used below code. it seems to work perfectly alright.
<div @mouseover="upHere = true" @mouseleave="upHere = false" >
<h2> Something Something </h2>
<some-component v-show="upHere"></some-component>
</div>
on vue instance
data : {
upHere : false
}
Hope that helps
Page got refreshed when a trip to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
Enum.valueOf()
only checks the constant name, so you need to pass it "COLUMN_HEADINGS"
instead of "columnHeadings". Your name
property has nothing to do with Enum internals.
To address the questions/concerns in the comments:
The enum's "builtin" (implicitly declared) valueOf(String name)
method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:
enum PropName { contents, columnHeadings, ...}
. This is obviously the most convenient.valueOf
, if you're really fond of naming conventions.valueOf
to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.It inherits the meaning from DOS. @:
In DOS version 3.3 and later, hides the echo of a batch command. Any output generated by the command is echoed.
Without it, you could turn off command echoing using the echo off
command, but that command would be echoed first.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.contentView.backgroundColor = .black
} else {
self.contentView.backgroundColor = .white
}
}
you can do something like that:
where regexp_like(name, 'string$', 'i');
Sometimes the array element may be very long, at that time you can create an array in this way:
set list=a
set list=%list%;b
set list=%list%;c
set list=%list%;d
Then show it:
@echo off
for %%a in (%list%) do (
echo %%a
echo/
)
You're right in your assumption about Spring vs. Quartz instantiating the class. However, Spring provides some classes that let you do some primitive dependency injection in Quartz. Check out SchedulerFactoryBean.setJobFactory() along with the SpringBeanJobFactory. Essentially, by using the SpringBeanJobFactory, you enable dependency injection on all Job properties, but only for values that are in the Quartz scheduler context or the job data map. I don't know what all DI styles it supports (constructor, annotation, setter...) but I do know it supports setter injection.
I'd make both the input
and label
elements display: block
, and then split the name label & input, and the email label & input into div's
and float them next to each other.
input, label {_x000D_
display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
<section>_x000D_
_x000D_
<div style="float:left;margin-right:20px;">_x000D_
<label for="name">Name</label>_x000D_
<input id="name" type="text" value="" name="name">_x000D_
</div>_x000D_
_x000D_
<div style="float:left;">_x000D_
<label for="email">Email</label>_x000D_
<input id="email" type="text" value="" name="email">_x000D_
</div>_x000D_
_x000D_
<br style="clear:both;" />_x000D_
_x000D_
</section>_x000D_
_x000D_
<section>_x000D_
_x000D_
<label for="subject">Subject</label>_x000D_
<input id="subject" type="text" value="" name="subject">_x000D_
<label for="message">Message</label>_x000D_
<input id="message" type="text" value="" name="message">_x000D_
_x000D_
</section>_x000D_
</form>
_x000D_
The modern approach in 2019 is using ES6 module type scripts.
<script type="module" src="..."></script>
By default, modules are loaded asynchronously and defered. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.
The differences between a script and a module are described here:
https://stackoverflow.com/a/53821485/731548
The execution of a module compared to a script is described here:
https://developers.google.com/web/fundamentals/primers/modules#defer
Support is shown here:
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
m2eclipse has moved from sonatype to eclipse.
The correct update site is http://download.eclipse.org/technology/m2e/releases/
If this is not working, one possibility is you have an older version of Eclipse (< 3.6). The other - if you see timeout related errors - could be that you are behind a proxy server.
Short answer: use an unassigned user port
Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.
The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.
You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.
The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.
The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
This script will overwrite attempts to navigate back and forth with the state of the current page.
Update:
Some users have reported better success with using document.URL
instead of document.title
:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
jQuery code uses it's own data()
method as such id.
var id = $.data(object);
At the backstage method data
creates a very special field in object
called "jQuery" + now()
put there next id of a stream of unique ids like
id = elem[ expando ] = ++uuid;
I'd suggest you use the same method as John Resig obviously knows all there is about JavaScript and his method is based on all that knowledge.
When you use GROUP BY
, the resulting rows will be usually less then incoming rows.
But, when you use PARTITION BY
, the resulting row count should be the same as incoming.
You can use JitPack (free for public Git repositories) to expose your GitHub repository as a Maven artifact. Its very easy. Your users would need to add this to their pom.xml:
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
<dependency>
<groupId>com.github.User</groupId>
<artifactId>Repo name</artifactId>
<version>Release tag</version>
</dependency>
As answered elsewhere the idea is that JitPack will build your GitHub repo and will serve the jars. The requirement is that you have a build file and a GitHub release.
The nice thing is that you don't have to handle deployment and uploads. Since you didn't want to maintain your own artifact repository its a good match for your needs.
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
List keys = new ArrayList(yourMap.keySet());
Sort them
Collections.sort(keys)
print them.
In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time
].
Though you can push all these values to LinkedHashMap
, for later use as well.
While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.
I suggest instead setting the 'lineterminator' attribute when creating the writer:
import csv
import sys
doc = csv.writer(sys.stdout, lineterminator='\n')
doc.writerow('abc')
doc.writerow(range(3))
That example will work on Python 2 and Python 3 and won't produce the unwanted newline characters. Note, however, that it may produce undesirable newlines (omitting the LF character on Unix operating systems).
In most cases, however, I believe that behavior is preferable and more natural than treating all CSV as a binary format. I provide this answer as an alternative for your consideration.
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict = {}
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
Regarding your original question, the answer is still that there is no way in general to know the length of an iterator in Python.
Given that you question is motivated by an application of the pysam library, I can give a more specific answer: I'm a contributer to PySAM and the definitive answer is that SAM/BAM files do not provide an exact count of aligned reads. Nor is this information easily available from a BAM index file. The best one can do is to estimate the approximate number of alignments by using the location of the file pointer after reading a number of alignments and extrapolating based on the total size of the file. This is enough to implement a progress bar, but not a method of counting alignments in constant time.
SELECT * from
(
select m.*, rownum r
from maps006 m
)
where r > 49 and r < 101
I created it a long time ago, related question
String.Format = function (b) {
var a = arguments;
return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
if (b.substring(0, 2) == "{{") return b;
var c = parseInt(b.match(/\d/)[0]);
return a[c + 1]
})
};
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
Actually, Microsoft has now made the Debugging Tools downloadable separately from the SDK. Look for the section "Standalone Debugging Tools for Windows (WinDbg)" about mid-page:
This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.
To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.
X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)
The result of these rows are exactly the same, I show it without centering because of simplicity.
I would respond in a comment but did not have enough reputation.
There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
A simple way is to make your own log collector methods or even just an existing log collector app from the market.
For my apps I made a report functionality which sends the logs to my email (or even to another place - once you get the log you can do whether you want with it).
Here is a simple example about how to get the log file from a device:
Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.
You can simply save your data in a variable and use find(to get single object of records) or filter(to get single array of records) method of JavaScript.
For example :-
let data = {
"list": [
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]}
and now use below command onkeyup or enter
to get single object
data.list.find( record => record.name === "my Name")
to get single array object
data.list.filter( record => record.name === "my Name")
To get the first and last date of Last Month
;
$dateBegin = strtotime("first day of last month");
$dateEnd = strtotime("last day of last month");
echo date("D-F-Y", $dateBegin);
echo "<br>";
echo date("D-F-Y", $dateEnd);
All the above answers are great, but I'd like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).
The markup
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox"
ng-click="selectAll($event)"
ng-checked="isSelectedAll()">
</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
<td>
<input type="checkbox" name="selected"
ng-checked="isSelected(e.id)"
ng-click="updateSelection($event, e.id)">
</td>
<td>{{e.title}}</td>
</tr>
</tbody>
</table>
And in the controller
var updateSelected = function(action, id) {
if (action === 'add' && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass()
expects the entire entity but it was being called with the id of the entity only, which is now corrected
If you set the AllowsTransparency
property on the Window
(even without setting any transparency values) the border disappears and you can only resize via the grip.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="640" Height="480"
WindowStyle="None"
AllowsTransparency="True"
ResizeMode="CanResizeWithGrip">
<!-- Content -->
</Window>
Result looks like:
Something like this?
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;
you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)
Why do you need a cursor at all? Your entire segment of code can be replaced by this, which will run a lot faster on large numbers of rows.
UPDATE tarinvoice set confirmtocntctkey = PrimaryCntctKey
FROM tarinvoice INNER JOIN tarcustomer ON tarinvoice.custkey = tarcustomer.custkey
WHERE confirmtocntctkey is null and tranno like '%115876'
All these answers are explaining the scenario of your second activity needs to be finish after sending the data.
But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.
In Second Activity -
Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
In First Activity-
private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// do some action
}
};
Register the receiver in onCreate()-
LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));
Unregister it in onDestroy()
Nothing has worked. The solution for the issue is.
<style>
table td {
padding: 0;
}
</style>
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
}
To put it more simply, if you have:
if(condition == TRUE) x <- TRUE
else x <- FALSE
Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}
You can define the variable in General Declarations and then initialise it in the first event that fires in your environment.
Alternatively, you could create yourself a class with the relevant properties and initialise them in the Initialise method
Good news! At the time of writing, this feature has already been implemented in the 0.10.12-insiders release and carried out through 0.10.14-insiders. Hence we are going to have it in the upcoming version 1.0 Release of VS Code.
Implementation Ref: Implement -w/--wait command line arg
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
I was able to use some of the answers in this thread and others to get it working in IE and Chrome/Edge. history.pushState for me wasn't supported in IE11.
if (history.pushState) {
//Chrome and modern browsers
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event) {
history.pushState(null, document.title, location.href);
});
}
else {
//IE
history.forward();
}
Found a great plugin that works in Juno and Kepler. It puts shortcuts on the quick access bar for increasing or decreasing text size.
Install New Software -> http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/
Is something like this what you want to do?
$return_arr = array();
$fetch = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
It returns a json string in this format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
OR something like this:
$year = date('Y');
$month = date('m');
$json_array = array(
//Each array below must be pulled from database
//1st record
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
//2nd record
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
);
echo json_encode($json_array);
This usually happens when you edit the Homestead.yaml file.
If like me you tried homestead up --provision
and didn't worked!
then try this (it works for me):
homestead destroy
homestead up
would take time to route through TeamViewer's servers (TeamViewer bypasses corporate Symmetric NATs by simply proxying traffic through their servers)
You'll find that TeamViewer rarely needs to relay traffic through their own servers. TeamViewer penetrates NAT and networks complicated by NAT using NAT traversal (I think it is UDP hole-punching, like Google's libjingle).
They do use their own servers to middle-man in order to do the handshake and connection set-up, but most of the time the relationship between client and server will be P2P (best case, when the hand-shake is successful). If NAT traversal fails, then TeamViewer will indeed relay traffic through its own servers.
I've only ever seen it do this when a client has been behind double-NAT, though.
Edit: this answer is for those who use ckeditor module in drupal.
I found a solution which doesn't require modifying ckeditor js file.
this answer is copied from here. all credits should goes to original author.
Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).
Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add
config.allowedContent = true;
.Don't forget to flush the cache under "Performance tab."
looks good enough as a generic version. You can modify it to meet your needs, if they're specific enough.
also test for exceptions and error conditions, such as file doesn't exist or can't be read, etc.
you can also do the following to save some space:
byte[] bytes = System.IO.File.ReadAllBytes(filename);
FYI - if anyone experience issues with launching Apache, and getting errors about
/usr/sbin/apachectl: line 82: ulimit: open files: cannot modify limit: Invalid argument
it's because of a recent update to Apache in Snow Leopard. The fix is easy, just open /usr/sbin/apachectl
and set ULIMIT=""
Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.
Install:
$ npm install cors
const cors = require('cors');
app.use(cors());
You have to put this code in your node server.
A standard JavaScript solution:
var addition = [];
addition.push(2);
addition.push(3);
var total = 0;
for (var i = 0; i < addition.length; i++)
{
total += addition[i];
}
alert(total); // Just to output an example
/* console.log(total); // Just to output an example with Firebug */
This works for me (the result should be 5). I hope there is no hidden disadvantage in this kind of solution.
I encounter this issue when I first run LEMP on centos7 refer to this post.
I restart nginx to test the phpinfo page, but get this
http://xxx.xxx.xxx.xxx/info.php is not unreachable now.
Then I use tail -f /var/log/nginx/error.log
to see more info. I find is the
php-fpm.sock file not exist. Then I reboot the system, everything is OK.
Here may not need to reboot the system as Fath's post, just reload nginx and php-fpm.
One can both fix the warning and use the timezone specified in settings.py, which might be different from UTC.
For example in my settings.py I have:
USE_TZ = True
TIME_ZONE = 'Europe/Paris'
Here is a solution; the advantage is that str(mydate)
gives the correct time:
>>> from datetime import datetime
>>> from django.utils.timezone import get_current_timezone
>>> mydate = datetime.now(tz=get_current_timezone())
>>> mydate
datetime.datetime(2019, 3, 10, 11, 16, 9, 184106,
tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> str(mydate)
'2019-03-10 11:16:09.184106+01:00'
Another equivalent method is using make_aware
, see dmrz post.
You can find it here: RTL Bootstrap v3.2.0.
to compare UTC timestamps from a log file with local timestamps.
It is hard to find out Olson TZ name for a local timezone in a portable manner. Fortunately, you don't need it to perform the comparison.
tzlocal
module returns a pytz timezone corresponding to the local timezone:
from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone()
local_dt = tz.localize(datetime(2010, 4, 27, 12, 0, 0, 0), is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc) #NOTE: utc.normalize() is unnecessary here
Unlike other solutions presented so far the above code avoids the following issues:
dateutil
) fail to take that into accountNote: to get timezone-aware datetime object from a naive datetime object, you should use*:
local_dt = tz.localize(datetime(2010, 4, 27, 12, 0, 0, 0), is_dst=None)
instead of:
#XXX fails for some timezones
local_dt = datetime(2010, 4, 27, 12, 0, 0, 0, tzinfo=tz)
*is_dst=None
forces an exception if given local time is ambiguous or non-existent.
If you are certain that all local timestamps use the same (current) utc offset for the local timezone then you could perform the comparison using only stdlib:
# convert a naive datetime object that represents time in local timezone to epoch time
timestamp1 = (datetime(2010, 4, 27, 12, 0, 0, 0) - datetime.fromtimestamp(0)).total_seconds()
# convert a naive datetime object that represents time in UTC to epoch time
timestamp2 = (datetime(2010, 4, 27, 9, 0) - datetime.utcfromtimestamp(0)).total_seconds()
timestamp1
and timestamp2
can be compared directly.
Note:
timestamp1
formula works only if the UTC offset at epoch (datetime.fromtimestamp(0)
) is the same as nowfromtimestamp()
creates a naive datetime object in the current local timezoneutcfromtimestamp()
creates a naive datetime object in UTC.I was wondering if two times WORKDIR
will work or not, but it worked :)
FROM ubuntu:18.04
RUN apt-get update && \
apt-get install -y python3.6
WORKDIR /usr/src
COPY ./ ./
WORKDIR /usr/src/src
CMD ["python3", "app.py"]
The answer is Yes if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.
Yes. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction.
Be careful to only use WITH (NOLOCK)
in SELECT statements on tables that have a clustered index.
WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.
The result set can contain rows that have not yet been committed, that are often later rolled back.
If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times.
READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.
Open your.gitconfig file to add the longpaths property. So it will look like the following:
[core]
symlinks = false
autocrlf = true
longpaths = true
The answer was already given but if you already have an Instance of T then you can do this:
T t; //Assuming you already have this object instantiated or given by parameter.
int length;
T[] ts = (T[]) Array.newInstance(t.getClass(), length);
Hope, I could Help, Ferdi265
Simply write to file string.Empty
, when append is set to false in StreamWriter. I think this one is easiest to understand for beginner.
private void ClearFile()
{
if (!File.Exists("TextFile.txt"))
File.Create("TextFile.txt");
TextWriter tw = new StreamWriter("TextFile.txt", false);
tw.Write(string.Empty);
tw.Close();
}
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:
LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");
list.sort( new Comparator<String>(){
@Override
public int compare(String o1,String o2){
return Collator.getInstance().compare(o1,o2);
}
});
References:
http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
http://tools.ietf.org/html/rfc2616#section-10.4.1
422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.
This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.
http://tools.ietf.org/html/rfc4918#page-78
See also Mark Nottingham's post on status codes:
it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.
Try the following:
UPDATE TableName SET ValueName=@parameterName WHERE
IdName=@ParameterIdName
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
You can use geolocator.js for easily getting timezone and more...
It uses Google APIs that require a key. So, first you configure geolocator:
geolocator.config({
language: "en",
google: {
version: "3",
key: "YOUR-GOOGLE-API-KEY"
}
});
Get TimeZone if you have the coordinates:
geolocator.getTimeZone(options, function (err, timezone) {
console.log(err || timezone);
});
Example output:
{
id: "Europe/Paris",
name: "Central European Standard Time",
abbr: "CEST",
dstOffset: 0,
rawOffset: 3600,
timestamp: 1455733120
}
Locate then get TimeZone and more
If you don't have the coordinates, you can locate the user position first.
Example below will first try HTML5 Geolocation API to get the coordinates. If it fails or rejected, it will get the coordinates via Geo-IP look-up. Finally, it will get the timezone and more...
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30,
fallbackToIP: true, // if HTML5 fails or rejected
addressLookup: true, // this will get full address information
timezone: true,
map: "my-map" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
Example output:
{
coords: {
latitude: 37.4224764,
longitude: -122.0842499,
accuracy: 30,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
},
address: {
commonName: "",
street: "Amphitheatre Pkwy",
route: "Amphitheatre Pkwy",
streetNumber: "1600",
neighborhood: "",
town: "",
city: "Mountain View",
region: "Santa Clara County",
state: "California",
stateCode: "CA",
postalCode: "94043",
country: "United States",
countryCode: "US"
},
formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
type: "ROOFTOP",
placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
timezone: {
id: "America/Los_Angeles",
name: "Pacific Standard Time",
abbr: "PST",
dstOffset: 0,
rawOffset: -28800
},
flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
map: {
element: HTMLElement,
instance: Object, // google.maps.Map
marker: Object, // google.maps.Marker
infoWindow: Object, // google.maps.InfoWindow
options: Object // map options
},
timestamp: 1456795956380
}
FYI you dont have string datatype in C. Use array of characters to store the value and manipulate it. Change your variable c into an array of characters and use it inside a loop to get values.
char c[10];
int i=0;
while(i!=10)
{
c[i]=fgetc(fp);
i++;
}
The other way to do is to use pointers and allocate memory dynamically and assign values.
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
The .join()
function is using the index
of the passed as argument dataset, so you should use set_index
or use .merge
function instead.
Please find the two examples that should work in your case:
join_df = LS_sgo.join(MSU_pi.set_index('mukey'), on='mukey', how='left')
or
join_df = df_a.merge(df_b, on='mukey', how='left')
SELECT id FROM table1 WHERE foreign_key_id_column NOT IN (SELECT id FROM table2)
Table 1 has a column that you want to add the foreign key constraint to, but the values in the foreign_key_id_column
don't all match up with an id
in table 2.
id
s from table1. These will be the rows we want to delete. NOT IN
clause in the where statement limits the query to only rows where the value in the foreign_key_id_column
is not in the list of table 2 id
s. SELECT
statement in parenthesis will get a list of all the id
s that are in table 2.Give your inputs ref like this
<input type="text" name="email" placeholder="Email" ref="email" />
<input type="password" name="password" placeholder="Password" ref="password" />
then you can access it in your handleLogin like soo
handleLogin: function(e) {
e.preventDefault();
console.log(this.refs.email.value)
console.log(this.refs.password.value)
}
I follow this simple setup with meld. Meld is free and opensource diff tool. You will see nice side by side comparison of files and directory for any code changes.
[diff] tool = meld
git difftool --dir-diff ./
git difftool --cached --dir-diff ./
The simplest and most fun way (imo) is glob
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
But the standard way is to use the directory functions.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
There are also the SPL DirectoryIterator methods. If you are interested
To update database type following codes in PowerShell...
Update-Database -context EnrollmentAppContext
*if more than one databases exist only use this codes,otherwise not necessary..
In python re, you can span from numberic to upper case alpha. So..
import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
That makes the simplest Python UUID regex:
re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)
I'll leave it as an exercise to the reader to use timeit to compare the performance of these.
Enjoy. Keep it Pythonic™!
NOTE: Those spans will also match :;<=>?@'
so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)
Simple GET request
using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
Simple POST request
using System.Net;
using System.Collections.Specialized;
...
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
}
This works and it's deadly simple. As many points as you want:
private function moveTweets():void {
var newScale:Number=Scale(meshes.length,50,500,6,2);
trace("new scale:"+newScale);
var l:Number=this.meshes.length;
var tweetMeshInstance:TweetMesh;
var destx:Number;
var desty:Number;
var destz:Number;
for (var i:Number=0;i<this.meshes.length;i++){
tweetMeshInstance=meshes[i];
var phi:Number = Math.acos( -1 + ( 2 * i ) / l );
var theta:Number = Math.sqrt( l * Math.PI ) * phi;
tweetMeshInstance.origX = (sphereRadius+5) * Math.cos( theta ) * Math.sin( phi );
tweetMeshInstance.origY= (sphereRadius+5) * Math.sin( theta ) * Math.sin( phi );
tweetMeshInstance.origZ = (sphereRadius+5) * Math.cos( phi );
destx=sphereRadius * Math.cos( theta ) * Math.sin( phi );
desty=sphereRadius * Math.sin( theta ) * Math.sin( phi );
destz=sphereRadius * Math.cos( phi );
tweetMeshInstance.lookAt(new Vector3D());
TweenMax.to(tweetMeshInstance, 1, {scaleX:newScale,scaleY:newScale,x:destx,y:desty,z:destz,onUpdate:onLookAtTween, onUpdateParams:[tweetMeshInstance]});
}
}
private function onLookAtTween(theMesh:TweetMesh):void {
theMesh.lookAt(new Vector3D());
}
There are two separate things here:
For example:
{
vector<MyObject> v;
// do some stuff, push some objects onto v
v.clear(); // 1
// maybe do some more stuff
} // 2
At 1
, you clear v
: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject
is now released.
However, vector v
has the right to keep the raw storage around in case you want it later.
If you decide to push some more things into it between 1
and 2
, this saves time as it can reuse the old memory.
At 2
, the vector v
goes out of scope: any objects you pushed into it since 1
will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v
won't be around to reuse it any more).
If I change the example so v
becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2
doesn't do that for you. It's better to use something like std::unique_ptr
in that case, but if you don't and v
is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v
is deleted, and calling clear
isn't sufficient.
It is better to rely on regexps like ^[^0-9]+$
rather than on regexps like [a-zA-Z]+
as your app may one day accept user inputs from users speaking language like Polish, where many more characters should be accepted rather than only [a-zA-Z]+
. Using ^[^0-9]+$
easily rules out any such undesired side effects.
Joze's way also need LINQ, ToList()
is in System.Linq
namespace.
You can convert Array to List without Linq by passing the array to List constructor:
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
After replacing the character, you need to be asign to the variable.
var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)
In the alert box it will shows 88.9827
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
Swift 5
Two ways to switch dark to light mode:
1- info.plist
<key>UIUserInterfaceStyle</key>
<string>Light</string>
2- Programmatically or Runtime
@IBAction private func switchToDark(_ sender: UIButton){
UIApplication.shared.windows.forEach { window in
//here you can switch between the dark and light
window.overrideUserInterfaceStyle = .dark
}
}
Here is my Timer widget, not related to the Question but may help someone.
import 'dart:async';
import 'package:flutter/material.dart';
class OtpTimer extends StatefulWidget {
@override
_OtpTimerState createState() => _OtpTimerState();
}
class _OtpTimerState extends State<OtpTimer> {
final interval = const Duration(seconds: 1);
final int timerMaxSeconds = 60;
int currentSeconds = 0;
String get timerText =>
'${((timerMaxSeconds - currentSeconds) ~/ 60).toString().padLeft(2, '0')}: ${((timerMaxSeconds - currentSeconds) % 60).toString().padLeft(2, '0')}';
startTimeout([int milliseconds]) {
var duration = interval;
Timer.periodic(duration, (timer) {
setState(() {
print(timer.tick);
currentSeconds = timer.tick;
if (timer.tick >= timerMaxSeconds) timer.cancel();
});
});
}
@override
void initState() {
startTimeout();
super.initState();
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(Icons.timer),
SizedBox(
width: 5,
),
Text(timerText)
],
);
}
}
You will get something like this