If you use PHP's default session handling, the only way to reliably change the session duration in all platforms is to change php.ini. That's because in some platforms, garbage collection is implemented through a script that runs every certain time (a cron script) that reads directly from php.ini, and therefore any attempts at changing it at run time, e.g. via ini_set()
, are unreliable and most likely won't work.
For example, in Debian Linux systems, PHP's internal garbage collection is disabled by setting session.gc_probability=0
by default in the configuration, and is instead done via /etc/cron.d/php, which runs at XX:09 and XX:39 (that is, every half hour). This cron job looks for sessions older than the session.gc_maxlifetime specified in the configuration, and if any are found, they are deleted. As a consequence, in these systems ini_set('session.gc_maxlifetime', ...)
is ignored. That also explains why in this question: PHP sessions timing out too quickly, the OP had problems in one host but the problems ceased when switching to a different host.
So, given that you don't have access to php.ini, if you want to do it portably, using the default session handling is not an option. Apparently, extending the cookie lifetime was enough for your host, but if you want a solution that works reliably even if you switch hosts, you have to use a different alternative.
Available alternative methods include:
Set a different session (save) handler in PHP to save your sessions in a different directory or in a database, as specified in PHP: Custom Session Handlers (PHP manual), so that the cron job doesn't reach it, and only PHP's internal garbage collection takes place. This option probably can make use of ini_set()
to set session.gc_maxlifetime but I prefer to just ignore the maxlifetime parameter in my gc()
callback and determine maximum lifetime on my own.
Completely forget about PHP internal session handling and implement your own session management. This method has two main disadvantages: you will need your own global session variables, so you lose the advantage of the $_SESSION
superglobal, and it needs more code thus there are more opportunities for bugs and security flaws. Most importantly, the session identifier should be generated out of cryptographically secure random or pseudorandom numbers to avoid session ID predictability (leading to possible session hijacking), and that is not so easy to do with PHP portably. The main advantage is that it will work consistently in all platforms and you have full control over the code. That's the approach taken e.g. by the phpBB forum software (at least version 1; I'm not sure about more recent versions).
There is an example of (1) in the documentation for session_set_save_handler()
. The example is long but I'll reproduce it here, with the relevant modifications necessary to extend the session duration. Note the inclusion of session_set_cookie_params()
to increase the cookie lifetime as well.
<?php
class FileSessionHandler
{
private $savePath;
private $lifetime;
function open($savePath, $sessionName)
{
$this->savePath = 'my_savepath'; // Ignore savepath and use our own to keep it safe from automatic GC
$this->lifetime = 3600; // 1 hour minimum session duration
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
function close()
{
return true;
}
function read($id)
{
return (string)@file_get_contents("$this->savePath/sess_$id");
}
function write($id, $data)
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
function destroy($id)
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $this->lifetime < time() && file_exists($file)) { // Use our own lifetime
unlink($file);
}
}
return true;
}
}
$handler = new FileSessionHandler();
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);
// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');
session_set_cookie_params(3600); // Set session cookie duration to 1 hour
session_start();
// proceed to set and retrieve values by key from $_SESSION
Approach (2) is more complicated; basically, you have to re-implement all session functions on your own. I won't go into details here.
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
First, check that whatever you are returning via unicode is a String.
If it is not a string you can change it to a string like this (where self.id is an integer)
def __unicode__(self):
return '%s' % self.id
following which, if it still doesn't work, restart your ./manage.py shell for the changes to take effect and try again. It should work.
Best Regards
<script>
window.open('http://www.example.com?ReportID=1', '_blank');
</script>
The second parameter is optional and is the name of the target window.
I am loading html pages from Documents and if they have the same name of css file UIWebView
it seem it does not throw the previous css rules. Maybe because they have the same URL or something.
I tried this:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
I tried this :
[[NSURLCache sharedURLCache] removeAllCachedResponses];
I am loading the initial page with:
NSURLRequest *appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
It refuses to throw its cached data! Frustrating!
I am doing this inside a PhoneGap (Cordova) application. I have not tried it in isolated UIWebView.
Update1: I have found this.
Changing the html files, though seems very messy.
You can just use Add-Computer, there is a parameter for "-NewName"
Example: Add-Computer -DomainName MYLAB.Local -ComputerName TARGETCOMPUTER -newname NewTARGETCOMPUTER
You might want to check also the parameter "-OPTIONS"
def colision(rect, circle):
dx = rect.x - circle.x
dy = rect.y - circle.y
distance = (dy**2 + dx**2)**0.5
angle_to = (rect.angle + math.atan2(dx, dy)/3.1415*180.0) % 360
if((angle_to>135 and angle_to<225) or (angle_to>0 and angle_to<45) or (angle_to>315 and angle_to<360)):
if distance <= circle.rad/2.+((rect.height/2.0)*(1.+0.5*abs(math.sin(angle_to*math.pi/180.)))):
return True
else:
if distance <= circle.rad/2.+((rect.width/2.0)*(1.+0.5*abs(math.cos(angle_to*math.pi/180.)))):
return True
return False
$oblast = Oblast::all();
$category = Category::where('slug', $catName)->first();
$availableProjects = $category->availableProjects;
return view('pages.business-area')->with(array('category'=>$category, 'availableProjects'=>$availableProjects, 'oblast'=>$oblast));
The difference between RMI and RPC is that:
Why not use the escape sequence ... !
System.out.println(str + '\b');
Life is much easier now . XD ! ~ A readable one-liner
nohup node server.js > /dev/null 2>&1 &
nohup
means: Do not terminate this process even when the stty is cut
off.> /dev/null
means: stdout goes to /dev/null (which is a dummy
device that does not record any output). 2>&1
means: stderr also goes to the stdout (which is already redirected to /dev/null
). You may replace &1 with a file path to keep a log of errors, e.g.: 2>/tmp/myLog
&
at the end means: run this command as a background task.If anyone like me is still unable to register ASP.NET with IIS.
You just need to run these three commands one by one in command prompt
cd c:\windows\Microsoft.Net\Framework\v2.0.50727
after that, Run
aspnet_regiis.exe -i -enable
and Finally Reset IIS
iisreset
Hope it helps the person in need... cheers!
Visual studio community edition is bundled with xamarin and which is free as well.
Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
It says:
Other parameters included in the response include
expires_in
andtoken_type
. These parameters describe the lifetime of the token in seconds...
Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:
$this->session->set_userdata('language', ENGLISH);
Then you can grab it anytime like this:
$language = $this->session->userdata('language');
You need to convert the coordinates to radians to do the spherical geometry. Once converted, then you can calculate a distance between the two points. The distance then can be converted to any measure you want.
I could not redirect the Perl based solution to a file for some reason so I kept searching and found a bash
only way to do this:
ping www.google.fr | while read pong; do echo "$(date): $pong"; done
Wed Jun 26 13:09:23 CEST 2013: PING www.google.fr (173.194.40.56) 56(84) bytes of data.
Wed Jun 26 13:09:23 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=1 ttl=57 time=7.26 ms
Wed Jun 26 13:09:24 CEST 2013: 64 bytes from zrh04s05-in-f24.1e100.net (173.194.40.56): icmp_req=2 ttl=57 time=8.14 ms
The credit goes to https://askubuntu.com/a/137246
here is how you can do it through list comprehension, but this will waste a little bit of your computer's memory as line.strip() has been called twice.
with open('textfile.txt') as file:
lines =[
line.strip()
for line in file
if line.strip() != '']
print("number of lines = {}".format(len(lines)))
In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.
In intnumber, parseInt is used and in floatnumber valueOf is used why so?
There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.
Java is case sensitive, and there isn't any Readline()
method. Perhaps you mean readLine().
DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();
However, for your case, I would use the Scanner class.
Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();
If you want to know what a class does I suggest you have a quick look at the Javadoc.
StringBuilder
(introduced in Java 5) is identical to StringBuffer
, except its methods are not synchronized. This means it has better performance than the latter, but the drawback is that it is not thread-safe.
Read tutorial for more details.
Dump a table using a where query:
mysqldump mydatabase mytable --where="mycolumn = myvalue" --no-create-info > data.sql
Dump an entire table:
mysqldump mydatabase mytable > data.sql
Notes:
mydatabase
, mytable
, and the where statement with your desired values.mysqldump
will include DROP TABLE
and CREATE TABLE
statements in its output. Therefore, if you wish to not delete all the data in your table when restoring from the saved data file, make sure you use the --no-create-info
option.-h
, -u
, and -p
options to the example commands above in order to specify your desired database host, user, and password, respectively.Use boost::hash
#include <boost\functional\hash.hpp>
...
std::string a = "ABCDE";
size_t b = boost::hash_value(a);
Here is another base R solution. We can use read.table
but since it accepts only one-byte sep
argument and here we have multi-byte separator we can use gsub
to replace the multibyte separator to any one-byte separator and use that as sep
argument in read.table
cbind(before[1], read.table(text = gsub('_and_', '\t', before$type),
sep = "\t", col.names = paste0("type_", 1:2)))
# attr type_1 type_2
#1 1 foo bar
#2 30 foo bar_2
#3 4 foo bar
#4 6 foo bar_2
In this case, we can also make it shorter by replacing it with default sep
argument so we don't have to mention it explicitly
cbind(before[1], read.table(text = gsub('_and_', ' ', before$type),
col.names = paste0("type_", 1:2)))
The problem is that you are passing a nullable type to a non-nullable type.
You can do any of the following solution:
A. Declare your dt
as nullable
DateTime? dt = dateTime;
B. Use Value
property of the the DateTime? datetime
DateTime dt = datetime.Value;
C. Cast it
DateTime dt = (DateTime) datetime;
The logcat shows the error, you should call super.onCreate(savedInstanceState)
:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//... your code
}
The way I have done it is to have the actionLink and the image seperately. Set the actionlink image as hidden and then added a jQuery trigger call. This is more of a workaround.
'<%= Html.ActionLink("Button Name", "Index", null, new { @class="yourclassname" }) %>'
<img id="yourImage" src="myImage.jpg" />
Trigger example:
$("#yourImage").click(function () {
$('.yourclassname').trigger('click');
});
php --ini
This will tell you exactly which php.ini file is being loaded, so you know which one to modify. I wasted a lot of time changing the wrong php.ini file because I had WAMP and XAMPP installed.
Also, don't forget to restart the WAMP server (or whatever you use) after changing php.ini.
1/ Convert the file encoding
File -> Settings -> Editor -> File encodings -> set UTF-8 for
Press OK
2/ Rebuild Project
Build -> Rebuild project
It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:
String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";
Something like this would
String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"
for k, m in self.materials.items():
example:
miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
print("%s: %s" % (k, v))
If you do not wan't to blindly trust everybody and make a trust exception only for certain hosts the following solution is more appropriate.
public static class Ssl
{
private static readonly string[] TrustedHosts = new[] {
"host1.domain.com",
"host2.domain.com"
};
public static void EnableTrustedHosts()
{
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
var request = sender as HttpWebRequest;
if (request != null)
{
return TrustedHosts.Contains(request.RequestUri.Host);
}
return false;
};
}
}
Then just call Ssl.EnableTrustedHosts when your app starts.
You don't need to use complicated coding really!
Greyscale Hover:
-webkit-filter: grayscale(100%);
Greyscale "Hover-out":
-webkit-filter: grayscale(0%);
I simply made my css class have a separate hover class and added in the second greyscale. It's really simple if you really don't like complexity.
The easiest way is to get the year from Calendar.
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
Solmead has the correct answer. For more info you can look at XML Comments.
I had same issue with my WPF RSS reader, I originally went with Awesomium (I think version 1.6) Awesomium is great. You get a lot of control for caching (images and HTML content), JavaScript execution, intercepting downloads and so forth. It's also super fast. The process isolation means when browser crashes it does not crash the app.
But it's also heavy, even release build adds about 10-15mb (can't remember exact number) and hence a slight start-up penalty. I then realized, only problem I had with IE browser control was that it would throw the JavaScript errors every now and again. But that was fixed with the following snippet.
I hardly used my app on XP or Vista but on Win 7 and above it never crashed (at least not because I used IE browser control)
IOleServiceProvider sp = browser.Document as IOleServiceProvider;
if (sp != null)
{
IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
webBrowser;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
if (webBrowser != null)
{
webBrowser.GetType().InvokeMember("Silent",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
}
}
Looking into the actual implementation of UrlBasedViewResolver and RedirectView the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.
So to achieve what you are trying you could do something like:
@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, ModelMap model)
{
String redirectUrl = request.getScheme() + "://www.yahoo.com";
return "redirect:" + redirectUrl;
}
You can use varargs
public function yourFunction(Parameter... parameters)
See also
It seems you want to save your class instances across sessions, and using pickle
is a decent way to do this. However, there's a package called klepto
that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto
is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.
Note that It works for dynamically added class attributes, which pickle cannot do...
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>>
>>> db['banana'] = banana
>>> db.dump()
>>>
Then we restart…
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>>
>>> db['banana'].color
'yellow'
>>>
Klepto
works on python2 and python3.
Get the code here: https://github.com/uqfoundation
// a wrapper closure around executing a string
// can take either a string or a list of strings (for arguments with spaces)
// prints all output, complains and halts on error
def runCommand = { strList ->
assert ( strList instanceof String ||
( strList instanceof List && strList.each{ it instanceof String } ) \
)
def proc = strList.execute()
proc.in.eachLine { line -> println line }
proc.out.close()
proc.waitFor()
print "[INFO] ( "
if(strList instanceof List) {
strList.each { print "${it} " }
} else {
print strList
}
println " )"
if (proc.exitValue()) {
println "gave the following error: "
println "[ERROR] ${proc.getErrorStream()}"
}
assert !proc.exitValue()
}
This simple extension in Swift works well.
extension String {
func size(OfFont font: UIFont) -> CGSize {
return (self as NSString).size(attributes: [NSFontAttributeName: font])
}
}
Usage:
let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}
You can only do so during a transaction.
BEGIN;
INSERT INTO xxx ...;
DELETE FROM ...;
Then you can either:
COMMIT; -- will confirm your changes
Or
ROLLBACK -- will undo your previous changes
My first contribution to the community , example as rotating a simple text and the header of a table, only using html and css.
HTML
<div class="rotate">text</div>
CSS
.rotate {
display:inline-block;
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
Here's a possible way to do it:
$string=exec('getmac');
$mac=substr($string, 0, 17);
echo $mac;
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
If you need the key for some reason, you can do;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
I think the problem is that you are using type="text" instead of textarea. What you want is:
<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>
To clarify, a type="text" will always be one row, where-as a textarea can be multiple.
On click it can be done using below code
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').slideToggle(500);
});
For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:
In your class you need to define an equality operator overload ==
. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/
Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/
namespace std {
template<>
struct hash<my_type> {
size_t operator()(const my_type& k) {
// Do your hash function here
...
}
};
}
std::map
or std::unordered_map
just like you would normally do and use my_type
as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.#include <unordered_map>
int main() {
std::unordered_map<my_type, other_type> my_map;
}
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
In C99 you can do it using a compound literal in combination with memcpy
memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray);
(assuming that the size of the source and the size of the target is the same).
In C89/90 you can emulate that by declaring an additional "source" array
const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */
int myArray[SIZE];
...
memcpy(myarray, SOURCE, sizeof myarray);
I run into the same issues with nexus7.
Following worked for fixing this.
Open Developer
option in the Settings
menu on your device.
Switch off
the button on the upper right of the screen.
Delete
all debug permission
from the list of the menu.
Switch on
the button on the upper right of the screen.
now reconnect your device to your PC and everything should be fine.
Sorry for my poor english and some name of the menus(buttons) can be incorrect in your language because mine is Japanese.
In Python 2.7 the multiline comment is:
"""
This is a
multilline comment
"""
In case you are inside a class you should tab it properly.
For example:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is @myItem.i and a value is @myItem.value.Name</li>
}
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
$("html, body").animate({ scrollTop: 0 }, "slow");
This CSS conflict with scroll to top so take care of this
html, body {
overflow-x: hidden;
}
Save the current product id before entering your loop:
$current_product = $product->id;
Then in your loop for your sidebar, use $product->id again to compare:
<li><a <? if ($product->id == $current_product) { echo "class='on'"; }?> href="<?=get_permalink();?>"><?=the_title();?></a></li>
for decimal values greater than zero, HTML5 works as follows:
<input id="txtMyDecimal" min="0" step="any" type="number">
Check the static Nullable.GetUnderlyingType
.
- If the underlying type is null, then the template parameter is not Nullable
, and we can use that type directly
- If the underlying type is not null, then use the underlying type in the conversion.
Seems to work for me:
public object Get( string _toparse, Type _t )
{
// Test for Nullable<T> and return the base type instead:
Type undertype = Nullable.GetUnderlyingType(_t);
Type basetype = undertype == null ? _t : undertype;
return Convert.ChangeType(_toparse, basetype);
}
public T Get<T>(string _key)
{
return (T)Get(_key, typeof(T));
}
public void test()
{
int x = Get<int>("14");
int? nx = Get<Nullable<int>>("14");
}
This is what I used. Link button is
<div class="link-button"><a href="/">Example</a></div>
CSS
/* body is sans-serif */
.link-button {
margin-top:15px;
max-width:90px;
background-color:#eee;
border-color:#888888;
color:#333;
display:inline-block;
vertical-align:middle;
text-align:center;
text-decoration:none;
align-items:flex-start;
cursor:default;
-webkit-appearence: push-button;
border-style: solid;
border-width: 1px;
border-radius: 5px;
font-size: 1em;
font-family: inherit;
border-color: #000;
padding-left: 5px;
padding-right: 5px;
width: 100%;
min-height: 30px;
}
.link-button a {
margin-top:4px;
display:inline-block;
text-decoration:none;
color:#333;
}
.link-button:hover {
background-color:#888;
}
.link-button:active {
background-color:#333;
}
.link-button:hover a, .link-button:active a {
color:#fff;
}
Try "`n"
with double quotes. (not single quotes '`n'
)
For a complete list of escaping characters see:
Help about_Escape_character
The code should be
$str += "`n"
while (<>) {
print;
}
will read either from a file specified on the command line or from stdin if no file is given
If you are required this loop construction in command line, then you may use -n
option:
$ perl -ne 'print;'
Here you just put code between {}
from first example into ''
in second
You can't increase the heap size dynamically but you can request to use more by using.
android:largeHeap="true"
in the manifest.xml
,you can add in your manifest these lines it is working for some situations.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="@style/AppTheme">
Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.
To query the available memory size at runtime, use the methods getMemoryClass()
or getLargeMemoryClass()
.
If still facing problem then this should also work
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
mBitmapInsurance = BitmapFactory.decodeFile(mCurrentPhotoPath,options);
This is the optimal use of BitmapFactory.Options.inSampleSize with regards to speed of displaying the image. The documentation mentions using values that are a power of 2, so I am working with 2, 4, 8, 16 etc.
For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x128 pixel thumbnail in an ImageView
.
To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize
to true
in your BitmapFactory.Options
object. For example, an image with resolution 2100 x 1500 pixels that is decoded with an inSampleSize
of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888
). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the
inSampleSize
documentation.
To use this method, first decode with inJustDecodeBounds
set to true
, pass the options through and then decode again using the new inSampleSize
value and inJustDecodeBounds
set to false
:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
This method makes it easy to load a bitmap of arbitrarily large size into an ImageView
that displays a 100x100 pixel thumbnail, as shown in the following example code:
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
You can follow a similar process to decode bitmaps from other sources, by substituting the appropriate BitmapFactory.decode*
method as needed.
I found this code also interesting:
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ",
orig-height: " + o.outHeight);
Bitmap bitmap = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
bitmap = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = bitmap.getHeight();
int width = bitmap.getWidth();
Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x,
(int) y, true);
bitmap.recycle();
bitmap = scaledBitmap;
System.gc();
} else {
bitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +bitmap.getWidth() + ", height: " +
bitmap.getHeight());
return bitmap;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}
It's not a good idea to use android:largeHeap="true"
here's the extract from google that explains it,
However, the ability to request a large heap is intended only for a small set of apps that can justify the need to consume more RAM (such as a large photo editing app). Never request a large heap simply because you've run out of memory and you need a quick fix—you should use it only when you know exactly where all your memory is being allocated and why it must be retained. Yet, even when you're confident your app can justify the large heap, you should avoid requesting it to whatever extent possible. Using the extra memory will increasingly be to the detriment of the overall user experience because garbage collection will take longer and system performance may be slower when task switching or performing other common operations.
After working excrutiatingly with out of memory errors
i would say adding this to the manifest to avoid the oom issue is not a sin
The Android runtime (ART) is the default runtime for devices running Android 5.0 (API level 21) and higher. This runtime offers a number of features that improve performance and smoothness of the Android platform and apps. You can find more information about ART's new features in Introducing ART.
However, some techniques that work on Dalvik do not work on ART. This document lets you know about things to watch for when migrating an existing app to be compatible with ART. Most apps should just work when running with ART.
Under Dalvik, apps frequently find it useful to explicitly call System.gc() to prompt garbage collection (GC). This should be far less necessary with ART, particularly if you're invoking garbage collection to prevent GC_FOR_ALLOC-type occurrences or to reduce fragmentation. You can verify which runtime is in use by calling System.getProperty("java.vm.version"). If ART is in use, the property's value is "2.0.0" or higher.
Furthermore, a compacting garbage collector is under development in the Android Open-Source Project (AOSP) to improve memory management. Because of this, you should avoid using techniques that are incompatible with compacting GC (such as saving pointers to object instance data). This is particularly important for apps that make use of the Java Native Interface (JNI). For more information, see Preventing JNI Issues.
ART's JNI is somewhat stricter than Dalvik's. It is an especially good idea to use CheckJNI mode to catch common problems. If your app makes use of C/C++ code, you should review the following article:
Also, you can use native memory (NDK & JNI), so you actually bypass the heap size limitation.
Here are some posts made about it:
and here's a library made for it:
If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!
Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
UPDATE - April '15:
If you want to get the count that is available in the Like button, you should use the engagement
field in the og_object
object, like so:
https://graph.facebook.com/v2.2/?id=http://www.MY-LINK.com&fields=og_object{engagement}&access_token=<access_token>
Result:
{
"og_object": {
"engagement": {
"count": 93,
"social_sentence": "93 people like this."
},
"id": "801998203216179"
},
"id": "http://techcrunch.com/2015/04/06/they-should-have-announced-at-420/"
}
It's possible with the Graph API, simply use:
http://graph.facebook.com/?id=YOUR_URL
something like:
http://graph.facebook.com/?id=http://www.google.com
Would return:
{
"id": "http://www.google.com",
"shares": 1163912
}
UPDATE: while the above would answer how to get the share count. This number is not equal to the one you see on the Like Button, since that number is the sum of:
So getting the Like Button number is possible with the Graph API through the fql
end-point (the link_stat
table):
https://graph.facebook.com/fql?q=SELECT url, normalized_url, share_count, like_count, comment_count, total_count,commentsbox_count, comments_fbid, click_count FROM link_stat WHERE url='http://www.google.com'
total_count
is the number that shows in the Like Button.
As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.
The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.
And last a basic example to give an idea how it looks like:
def func(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
See Also
--------
otherfunc : some related other function
Examples
--------
These are written in doctest format, and should illustrate how to
use the function.
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
return True
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
You paste this inside :
<A HREF = "index.html">Click here</A>
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
You can get the same effect as a default value by using a trigger
create table my_text
(
abc text
);
delimiter //
create trigger mytext_trigger before insert on my_text
for each row
begin
if (NEW.abc is null ) then
set NEW.abc = 'default text';
end if;
end
//
delimiter ;
You can for example do this in this way (full code with exceptions handlig):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID )
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql
Here is my customized solution.
const inBrowser = typeof window !== 'undefined'
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE =
UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
const isEdge = UA && /edg/i.test(UA)
const isAndroid = UA && UA.indexOf('android') > 0
const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
const isChrome =
UA &&
/chrome|crios/i.test(UA) &&
!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
const isGoogleBot = UA && /googlebot/i.test(UA)
const isChromium = UA && /chromium/i.test(UA)
const isUcBrowser = UA && /ucbrowser/i.test(UA)
const isSafari =
UA &&
/safari/i.test(UA) &&
!/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
const isOpera = UA && /opr|opera/i.test(UA)
const isMobile =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
const isSamsung = UA && /samsungbrowser/i.test(UA)
const isIPad = UA && /ipad/.test(UA)
const isIPhone = UA && /iphone/.test(UA)
const isIPod = UA && /ipod/.test(UA)
console.log({
UA,
isAndroid,
isChrome,
isChromium,
isEdge,
isFirefox,
isGoogleBot,
isIE,
isMobile,
isIOS,
isIPad,
isIPhone,
isIPod,
isOpera,
isSafari,
isSamsung,
isUcBrowser,
}
}
You (as in the process that runs b.php
, either you through CLI
or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod()
function to set the mode of a file or folder to 777
you should use 0777
to make sure the number is correctly interpreted as an octal number.
I think we can modify the UsedRange
code from @Readify's answer above to get the last used column even if the starting columns are blank or not.
So this lColumn = ws.UsedRange.Columns.Count
modified to
this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1
will give reliable results always
?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1
Above line Yields 9
in the immediate window.
I had this same exact problem, except that i have never used IIS. While I was fixing another system bug, I had set the apache service to manual start, hoping to reduce the complexity of my system. After I fixed the other bug, apache wouldn't start. I futzed for a while, but all it took was setting apache back to automatic start: Start > Administrative Tools > Services.
Apparently when Apache starts this way, it claims port 80 before the SYSTEM process can.
hth someone. all my googling turned up the 'can't have IIS and Apache on the same machine.' this is for the other one percent of us.
The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:
Route::post('test/register', array('uses'=>'TestController@create'));
Also, you need to hash your passwords:
public function create()
{
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::back();
}
And I removed the line:
$user= Input::all();
Because in the next command you replace its contents with
$user = new User;
To debug your Input, you can, in the first line of your controller:
dd( Input::all() );
It will display all fields in the input.
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
You can run this Powershell script as administrator to enable FL:
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds -Value 1 -Type DWord
Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath -Value 'C:\FusionLog\' -Type String
mkdir C:\FusionLog -Force
and this one to disable:
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds
Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath
document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something'))
.
Assuming the terminal app in question is named 'app' (and you expect it to be in your $PATH):
if [[ ! `which app` ]]; then
# run code if app not installed
else
# run code if app is installed
fi
It depends on your file path. For me, the current directory was [project]\bin\Debug
, so I had to move to the parent folder twice.
Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;
To find your current directory, you can make a dummy label called label2 and write this:
this.label2.Text = System.IO.Directory.GetCurrentDirectory();
Download Handle.
https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH
environment variable. And the file path is C:\path\path\file.txt", run this:
handle "C:\path\path\file.txt"
This will tell you what process(es) have the file (or folder) locked.
What I've found useful is to know which copy/paste buffer (register) is currently active: %{v:register}
. Otherwise, my complete status line looks almost exactly like the standard line.
:set statusline=%<%f\ %h%m%r\ %y%=%{v:register}\ %-14.(%l,%c%V%)\ %P
I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
You should set default values in migrations:
$table->tinyInteger('role')->default(1);
check if this is valid or not as far as my test cases I am able to get this working.
let's say number is k;
Careful with the eval, the JSON specs http://json.org/js.html recommend something like
var myObject = eval('(' + myJSONtext + ')');
And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:
This Is What I Would Do:
from datetime import *
months = ["Unknown",
"January",
"Febuary",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)
It Outputs:
>>> September
(This Was The Real Date When I Wrote This)
There is also an option to run code directly from the CLI, not the *.ts
file itself.
It's perfectly described in the ts-node manual.
ts-node
globally via npm, yarn, or whatever you like.ts-node -e 'console.log("Hello, world!")'
(you may also add the -p
flag for printing code)This little command is perfect for checking, does everything installed fine. And for finding some other error, relevant with tsconfig.json
options.
Example
public class myThread extends Thread{
@override
public void run(){
while(true){
threadCondWait();// Circle waiting...
//bla bla bla bla
}
}
public synchronized void threadCondWait(){
while(myCondition){
wait();//Comminucate with notify()
}
}
}
public class myAnotherThread extends Thread{
@override
public void run(){
//Bla Bla bla
notify();//Trigger wait() Next Step
}
}
I think there may be problem that you haven't added click listener for ok positive button.
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")
train_set = ["president of India",doc1, doc2, doc3]
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train) #here the first element of tfidf_matrix_train is matched with other three elements
Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.
Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III
the output will be as follows :
[[ 1. 0.07102631 0.02731343 0.06348799]]
here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.
There are pretty good solutions here but they don't help to understand why the problem actually happens.
But it's very simple, you just need to understand how logic OR ||
works. Whole expression will evaluate to true
when either of its sides evaluates to true
.
Now let's look at your case. Assume whole details.Payment[0].Status
is Status
and it's a number for brevity. Then we have Status != 0 || Status != 1 || ...
.
Imagine Status = 1
:
( 1 != 0 || 1 != 1 || ... ) =
( true || false || ... ) =
( true || ... ) = ... = true
Now imagine Status = 0
:
( 0 != 0 || 0 != 1 || ... ) =
( false || true || ... ) =
( true || ... ) = ... = true
As you it doesn't even matter what you have as ...
as logical OR
of first two expressions gives you true
which will be the result of the full expression.
What you actually need is logical AND
&&
that will be true only if both its sides are true
.
Either you can use CSV functions or PHPExcel
or you can try like below
<?php
$file="demo.xls";
$test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>
The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
You can bind to all of the radio buttons at once by name:
$('input[name=someRadioGroup]:radio').change(...);
Working example here: http://jsfiddle.net/Ey4fa/
I hide the warnings in the pink boxes by running the following code in a cell:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-
repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();
try like this
again this is all in the link you supplied
to change the text to white all you have to do is change the theme.
use this theme
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
You can use __CLASS__
within a class to get the name.
You can also define an environment variable (new feature in 2010 - i.e. python 2.7)
export PYTHONWARNINGS="ignore"
Test like this: Default
$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>
Ignore warnings
$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>>
For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python
Copied here...
From documentation of the warnings
module:
#!/usr/bin/env python -W ignore::DeprecationWarning
If you're on Windows: pass -W ignore::DeprecationWarning
as an argument to Python. Better though to resolve the issue, by casting to int.
(Note that in Python 3.2, deprecation warnings are ignored by default.)
Or:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import md5, sha
yourcode()
Now you still get all the other DeprecationWarning
s, but not the ones caused by:
import md5, sha
there are some mistakes in your code - the first: you havn't closed you p
-tag:
<a href="http//www.google.com"><p style="text-align:center">Search</p></a>
next: p
stands for 'paragraph' and is a block-element (so it's causing a line-break). what you wanted to use there is a span
, wich is just an inline-element for formatting:
<a href="http//www.google.com"><span style="text-align:center">Search</span></a>
but if you just want to add a style to your link, why don't you set the style for that link directly:
<a href="http//www.google.com" style="text-align:center">Search</a>
in the end, this would at least be correct html, but still not exactly what you want, because text-align:center
centers the text in that element, so you would have to set that for the element that contains this links (this piece of html isn't posted, so i can't correct you, but i hope you understand) - to show this, i'll use a simple div
:
<div style="text-align:center">
<a href="http//www.google.com">Search</a>
<!-- more links here -->
</div>
EDIT: some more additions to your question:
p
is not a 'function', but you're right, this is causing the problem (because it's a block-element)Using webpack and scss:
Install font-awesome using npm (using the setup instructions on https://fontawesome.com/how-to-use)
npm install @fortawesome/fontawesome-free
Next, using the copy-webpack-plugin, copy the webfonts folder from node_modules to your dist folder during your webpack build process. (https://github.com/webpack-contrib/copy-webpack-plugin)
npm install copy-webpack-plugin
In webpack.config.js, configure copy-webpack-plugin. NOTE: The default webpack 4 dist folder is "dist", so we are copying the webfonts folder from node_modules to the dist folder.
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyWebpackPlugin([
{ from: './node_modules/@fortawesome/fontawesome-free/webfonts', to: './webfonts'}
])
]
}
Lastly, in your main.scss file, tell fontawesome where the webfonts folder has been copied to and import the SCSS files you want from node_modules.
$fa-font-path: "/webfonts"; // destination folder in dist
//Adapt the path to be relative to your main.scss file
@import "../node_modules/@fortawesome/fontawesome-free/scss/fontawesome";
//Include at least one of the below, depending on what icons you want.
//Adapt the path to be relative to your main.scss file
@import "../node_modules/@fortawesome/fontawesome-free/scss/brands";
@import "../node_modules/@fortawesome/fontawesome-free/scss/regular";
@import "../node_modules/@fortawesome/fontawesome-free/scss/solid";
@import "../node_modules/@fortawesome/fontawesome-free/scss/v4-shims"; // if you also want to use `fa v4` like: `fa fa-address-book-o`
and apply the following font-family
to a desired region(s) in your html document where you want to use the fontawesome icons.
Example:
body {
font-family: 'Font Awesome 5 Free'; // if you use fa v5 (regular/solid)
// font-family: 'Font Awesome 5 Brands'; // if you use fa v5 (brands)
}
This is a work around.
[EDIT]
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<table cellspacing="1" width="100%" bgcolor="#cccccc">
<thead>
<tr>
<td bgcolor="#ffffff" width="70px">
</td>
<td class="csstablelisttd" width="70px">
<b>Time Slot </b>
</td>
<td class="csstablelisttd">
<b> Patient Name</b>
</td>
</tr>
</thead>
</table>
<!-- THIS GIVES THE SCROLLER -->
<div style="height: 500px; overflow-y: auto">
<table id="tableAppointment" cellspacing="1" width="100%" bgcolor="#cccccc">
<tbody>
<tr>
<td class="csstablelisttd" valign="top" width="70px">
8:00AM
</td>
<td class="csstablelisttd" width="70px">
0
</td>
<td class="csstablelisttd">
<span>Name 1</span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
9:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
10:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
11:00AM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
12:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
01:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
02:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
03:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
04:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
05:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
06:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
07:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
15
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
30
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd">
</td>
<td class="csstablelisttd">
45
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
<tr>
<td class="csstablelisttd" valign="top" width="90px">
08:00PM
</td>
<td class="csstablelisttd">
0
</td>
<td class="csstablelisttd">
<span></span>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Using top
instead of margin-top
is another possible solution, if appropriate.
You can use the formula INDIRECT()
.
This basically takes a string and treats it as a reference. In your case, you would use:
=INDIRECT("'"&A5&"'!G7")
The double quotes are to show that what's inside are strings, and only A5
here is a reference.
A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:
mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name | Value |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)
And then make sure you use that directory in your SELECT
statement's INTO OUTFILE
clause:
SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
FIELDS TERMINATED BY '#'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Original answer
I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.
In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
On linux the two most common locations are /etc/my.cnf
or /etc/mysql/my.cnf
.
Opening this file I can see that the secure-file-priv
option has been added under the [mysqld]
group in this new version of MySQL Server with a default value:
secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"
You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = ""
in order to disable the default). Don't forget to restart the service after making changes.
Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):
SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
FIELDS TERMINATED BY '#'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
It's more common to have comma seperate values using FIELDS TERMINATED BY ','
. See below for an example (also showing a Linux path):
SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
ESCAPED BY ''
LINES TERMINATED BY '\n';
This is not possible, you can however overwrite an existing table file. But be sure, that the line endings in your file are unix style (ending only with \n), not windows style (ending with \r\n), whether you are working under windows or not.
Simply convert int
to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:@"%d",x];
The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
if (getOrientation() == HORIZONTAL) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
heightSpec,
mMeasuredDimension);
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
recycler.bindViewToPosition(view, position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
An open source GUI tool is available at keystore-explorer.org
KeyStore Explorer
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Following screens will help (they are from the official site)
Default screen that you get by running the command:
shantha@shantha:~$./Downloads/kse-521/kse.sh
And go to Examine
and Examine a URL
option and then give the web URL that you want to import.
The result window will be like below if you give google site link.
This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
Parsing a string with date and time into a particular point in time (Java calls it an "Instant
") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time
and java.time.chrono
, covers almost all needs (except Time Dilation :) ).
However, that complexity brings a lot of confusion.
The key to understand date parsing is:
LocalDateTime
, ZonedDateTime
et al. so complicatedThere are time zones.
A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.
There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."
Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.
To make it a bit more complicated (but that's not too important for your use case) :
2040-12-31 24:00:00
may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.
Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.
Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00
may be off a couple of seconds from the future parsing.
java.util.Date
which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.java.sql.Date
was introduced, with it's own limitations.Calendar
API was introduced.java.time
When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.
Does it contain the date and the time?
Does it have a time offset?
A time offset is the +hh:mm
part. Sometimes, +00:00
may be substituted with Z
as 'Zulu time', UTC
as Universal Time Coordinated, or GMT
as Greenwich Mean Time. These also set the time zone.
For these timestamps, you use OffsetDateTime
.
Does it have a time zone?
For these timestamps, you use ZonedDateTime
.
Zone is specified either by
The list of time zones is compiled by a "TZ database", backed by ICAAN.
According to ZoneId
's javadoc, The zone id's can also somehow be specified as Z
and offset. I'm not sure how this maps to real zones.
If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle
, see below.
If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime
and converted to OffsetDateTime
by adding the missing info:
Duration
), or when you don't know and it doesn't really matter (e.g. local bus schedule).Partial time information
LocalDate
, LocalTime
, OffsetTime
, MonthDay
, Year
, or YearMonth
out of it.If you have the full information, you can get a java.time.Instant
. This is also internally used to convert between OffsetDateTime
and ZonedDateTime
.
There is an extensive documentation on DateTimeFormatter
which can both parse a timestamp string and format to string.
The pre-created DateTimeFormatter
s should cover moreless all standard timestamp formats. For instance, ISO_INSTANT
can parse 2011-12-03T10:15:30.123457Z
.
If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).
private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
.toFormatter();
I recommend to look at the source code of DateTimeFormatter
and get inspired on how to build one using DateTimeFormatterBuilder
. While you're there, also have a look at ResolverStyle
which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.
Now, the frequent mistake is to go into the complexity of TemporalAccessor
. This comes from how the developers were used to work with SimpleDateFormatter.parse(String)
. Right, DateTimeFormatter.parse("...")
gives you TemporalAccessor
.
// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");
But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);
You do not actually need to the DateTimeFormatter
either. The types you want to parse have the parse(String)
methods.
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");
Regarding TemporalAccessor
, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.
I hope I shed some light of understanding onto your soul :)
Note: There's a backport of java.time
to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.
[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )
Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
You have to use the SelectMany
extension method or its equivalent syntax in pure LINQ.
(from model in list
where model.application == "applicationname"
from user in model.users
where user.surname == "surname"
select new { user, model }).ToList();
One cannot disable the browser back button functionality. The only thing that can be done is prevent them.
The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:
<script>
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function() {
null
};
</script>
Suppose there are two pages Page1.php
and Page2.php
and Page1.php
redirects to Page2.php
.
Hence to prevent user from visiting Page1.php
using the back button you will need to place the above script in the head section of Page1.php
.
For more information: Reference
Just a simplified version of @T.J. Crowder and @RegarBoy's answers.
Less is more in my opinion.
Check out onmousemove event for more info about the event.
There's a new value of posX
and posY
every time the mouse moves according to the horizontal and vertical coordinates.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example Mouse Tracker</title>
<style>
body {height: 3000px;}
.dot {width: 2px;height: 2px;background-color: black;position: absolute;}
</style>
</head>
<body>
<p>Mouse tracker</p>
<script>
onmousemove = function(e){
//Logging purposes
console.log("mouse location:", e.clientX, e.clientY);
//meat and potatoes of the snippet
var pos = e;
var dot;
dot = document.createElement('div');
dot.className = "dot";
dot.style.left = pos.x + "px";
dot.style.top = pos.y + "px";
document.body.appendChild(dot);
}
</script>
</body>
</html>
Use whatever navigation key you want to get inside the parentheses, then you can use either yi(
or yi)
to copy everything within the matching parens. This also works with square brackets (e.g. yi]
) and curly braces. In addition to y
, you can also delete or change text (e.g. ci)
, di]
).
I tried this with double and single-quotes and it appears to work there as well. For your data, I do:
write (*, '(a)') 'Computed solution coefficients:'
Move cursor to the C
, then type yi'
. Move the cursor to a blank line, hit p
, and get
Computed solution coefficients:
As CMS noted, this works for visual mode selection as well - just use vi)
, vi}
, vi'
, etc.
In all these scenarios outerScopeVar
is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined
Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):
1.
Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png';
and alert(outerScopeVar);
meanwhile the event may not occur. i.e, funtion img.onload
wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.
2.
Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0
, but still it registers an asynchronous event it will be added to the last position of the Event Queue
for execution, which makes the guaranteed delay.
3.
4.
Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.
5.
Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?
https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript
Do you want to do this?
SELECT id, parent_id, name,
(select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id
Edit Another option based on OMG's one (but I think that will perform equally):
select
t1.id,
t1.parent_id,
t1.name,
t2.name AS parent_name,
t2.id AS parent_id
from
(select id, parent_id, name
from tbl
start with id = 1
connect by prior id = parent_id) t1
left join
tbl t2 on t2.id = t1.parent_id
It's essentially pointless to compare two structures for performance that behave differently. Use the structure that conveys the intent. Even if you say your List<T>
wouldn't have duplicates and iteration order doesn't matter making it comparable to a HashSet<T>
, its still a poor choice to use List<T>
because its relatively less fault tolerant.
That said, I will inspect some other aspects of performance,
+------------+--------+-------------+-----------+----------+----------+-----------+
| Collection | Random | Containment | Insertion | Addition | Removal | Memory |
| | access | | | | | |
+------------+--------+-------------+-----------+----------+----------+-----------+
| List<T> | O(1) | O(n) | O(n) | O(1)* | O(n) | Lesser |
| HashSet<T> | O(n) | O(1) | n/a | O(1) | O(1) | Greater** |
+------------+--------+-------------+-----------+----------+----------+-----------+
Even though addition is O(1) in both cases, it will be relatively slower in HashSet since it involves cost of precomputing hash code before storing it.
The superior scalability of HashSet has a memory cost. Every entry is stored as a new object along with its hash code. This article might give you an idea.
You can also use function:
//Works with negative numbers now
static int MyRound(double d) {
if (d < 0) {
return (int)(d - 0.5);
}
return (int)(d + 0.5);
}
Depending on the architecture it is several times faster.
This has happened with me too, python is space sensitive,
so after " : "(colon)
you might have left a space,
for example:
[space is represented by "."]
`if command == 'HOWMANY':.
opcodegroupr = "A0"
opcoder = "85"
elif command == 'IDENTIFY':.
opcodegroupr = "A0"
opcoder = "81"`
so try removing the unnecessary spaces,if you open it in IDE your cursor will be displayed away from ":" something like :- "if command == 'HOWMANY': |"
....whereas it should be:- "if command == 'HOWMANY':| "
The only difference between object literals and constructed objects are the properties inherited from the prototype.
var o = {
'a': 3, 'b': 4,
'doStuff': function() {
alert(this.a + this.b);
}
};
o.doStuff(); // displays: 7
You could make a struct factory.
function makeStruct(names) {
var names = names.split(' ');
var count = names.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[names[i]] = arguments[i];
}
}
return constructor;
}
var Item = makeStruct("id speaker country");
var row = new Item(1, 'john', 'au');
alert(row.speaker); // displays: john
This worked for me. Pseudocode:
// screen width and height
scr = {w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}
canvas.width = scr.w
canvas.height = scr.h
Also, like devyn said, you can replace "document.documentElement.client" with "inner" for both the width and height:
**document.documentElement.client**Width
**inner**Width
**document.documentElement.client**Height
**inner**Height
and it still works.
you just need to go to python console and type->
import nltk
press enter and retype->
nltk.download()
and then a interface will come. Just search for download button and press it. It will install all the required items and will take time. Give the time and just try it again. Your problem will get solved
Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler
, which defines a method that is invoked when a proxy method is invoked.
You create them by using the call
Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler
. When a method from any of the supported interfaces, or hashCode
, equals
, or toString
, is invoked, the method invoke
is invoked on the handler, passing the Method
object for the method to be invoked and the arguments passed.For more on this, see the documentation for the Proxy
class.
Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.
In my opinion the main form should be responsible for opening both child form. Here is some pseudo that explains what I would do:
// MainForm
private ChildForm childForm;
private MoreForm moreForm;
ButtonThatOpenTheFirstChildForm_Click()
{
childForm = CreateTheChildForm();
childForm.MoreClick += More_Click;
childForm.Show();
}
More_Click()
{
childForm.Close();
moreForm = new MoreForm();
moreForm.Show();
}
You will just need to create a simple event MoreClick in the first child. The main benefit of this approach is that you can replicate it as needed and you can very easily model some sort of basic workflow.
We can make a plugin pretty easily:
$.fn.filterData = function(key, value) {
return this.filter(function() {
return $(this).data(key) == value;
});
};
Usage (checking a radio button):
$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);
Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.
Create a view model class like this:
public class EmployeeAddViewModel
{
public Employee employee { get; set; }
public Dictionary<int, string> staffTypes { get; set; }
// really? a 1-to-many for genders
public Dictionary<int, string> genderTypes { get; set; }
public EmployeeAddViewModel() { }
public EmployeeAddViewModel(int id)
{
employee = someEntityContext.Employees
.Where(e => e.ID == id).SingleOrDefault();
// instantiate your dictionaries
foreach(var staffType in someEntityContext.StaffTypes)
{
staffTypes.Add(staffType.ID, staffType.Type);
}
// repeat similar loop for gender types
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
return View(new EmployeeAddViewModel());
}
[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View("Index"); // or wherever you go after successful add
}
return View(vm);
}
Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:
@Html.DropDownListFor(model => model.employee.staffTypeID,
new SelectList(model.staffTypes, "ID", "Type"))
and similarly for the gender dropdown
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(model.genderTypes, "ID", "Gender"))
Update per comments
For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList...
below, you would use your IEnumerable.
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(new SelectList()
{
new { ID = 1, Gender = "Male" },
new { ID = 2, Gender = "Female" }
}, "ID", "Gender"))
Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:
ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1 | Gender | 1 | Male | male gender | 1
2 | State | 50 | Hawaii | 50th state | 1
3 | Gender | 2 | Female | female gender | 1
4 | State | 49 | Alaska | 49th state | 1
5 | OrderType | 1 | Web | online order | 1
I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.
Hope this helps!
For business logic I usually find a decimal number (in years) is useful:
select months_between(TRUNC(sysdate),
to_date('15-Dec-2000','DD-MON-YYYY')
)/12
as age from dual;
AGE
----------
9.48924731
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:
if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
// ...
}
This link explains where you're going wrong:
Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.
This offers another solution:
How can I avoid linker errors with my template functions?
However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.
Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.
// MyClass.cpp
#include "MyClass.h"
// anonymous namespace
namespace
{
string RE_ANY = "([^\\n]*)";
string RE_ANY_RELUCTANT = "([^\\n]*?)";
}
// member function (static or not)
bool MyClass::foo()
{
// logic that uses constants
return RE_ANY_RELUCTANT.size() > 0;
}
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
http://code.google.com/p/roottools/
If you do not want to use the jar file just use the code:
public static boolean findBinary(String binaryName) {
boolean found = false;
if (!found) {
String[] places = { "/sbin/", "/system/bin/", "/system/xbin/",
"/data/local/xbin/", "/data/local/bin/",
"/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/" };
for (String where : places) {
if (new File(where + binaryName).exists()) {
found = true;
break;
}
}
}
return found;
}
Program will try to find su folder:
private static boolean isRooted() {
return findBinary("su");
}
Example:
if (isRooted()) {
textView.setText("Device Rooted");
} else {
textView.setText("Device Unrooted");
}
public static void main(string [] args)
public
-its the access specifier means from every where we can access it;
static
-access modifier means we can call this method directly using a class name without creating an object of it;
void
- its the return type;
main
- method name
string [] args
- it accepts only string type of argument... and stores it in a string array
you can use this:
try {
Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
"https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
activity.startActivity(followIntent);
} catch (Exception e) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
}
attention: you can get scoped user id from "link" permission facebook api
For Bootstrap v4 use:
has-danger
for form-group
wrapper,
form-control-danger
for input to show icon (will display ? at the end of input),
form-control-feedback
to message wrapper
Example:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="form-group has-danger">_x000D_
<input type="text" class="form-control form-control-danger">_x000D_
<div class="form-control-feedback">Not valid :(</div>_x000D_
</div>
_x000D_
With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
, you need to either use a list or use shell=True
;
Either of these will work. The former is preferable.
a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)
a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)
Also, instead of using Popen.stdout.read
/Popen.stderr.read
, you should use .communicate()
(refer to the subprocess documentation for why).
proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
The animation should be applied on the specific component.
EX : Using animation directive in other component and provided in another.
CompA --- @Component ({
animations : [animation] }) CompA --- @Component ({
animations : [animation] <=== this should be provided in used component })
If you have TensorFlow 2.x:
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
You can do it using javascript
Plain javascript
var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
jQuery
$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');
import pickle
intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()
Test your pickle quickly. pickle is a part of standard python library and available by default.
My issue is that I ran git diff
, then ran git reset --hard HEAD
, then realized I wanted to undo, so I tried copying the output from git diff
into a file and using git apply
, but I got an error that "patch does not apply". After switching to patch
and trying to use it, I realized that a chunk of the diff was repeated for some reason, and after removing the duplicate, patch
(and presumably also git apply
) worked.
I recently had to find out why this didn't work too.
The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="parent.abc();" href="#">Click Me</a>
</iframe>
</body>
Hope this helps anyone that stumbles upon this issue again.
We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:
Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>
Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />
NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.
Actually, this is not specific to display:inline-block
, but also applies to display:inline
. Thus, in addition to David HorĂ¡k's solution, this also works:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline;
}
You can find excellent information at http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html
To Summarize:
HashMap works on the principle of hashing
put(key, value): HashMap stores both key and value object as Map.Entry. Hashmap applies hashcode(key) to get the bucket. if there is collision ,HashMap uses LinkedList to store object.
get(key): HashMap uses Key Object's hashcode to find out bucket location and then call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.
Hi Edit your conf/core-site.xml and change localhost to 0.0.0.0. Use the conf below. That should work.
<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://0.0.0.0:9000</value>
</property>
Not really. Internally, passing by reference is performed by essentially passing the address of the referenced object. So, there really aren't any efficiency gains to be had by passing a pointer.
Passing by reference does have one benefit, however. You are guaranteed to have an instance of whatever object/type that is being passed in. If you pass in a pointer, then you run the risk of receiving a NULL pointer. By using pass-by-reference, you are pushing an implicit NULL-check up one level to the caller of your function.
If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.
Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.
JSF is a beast. I may be missing something, but I used to solve similar problems by saving the desired message to a property of the bean, and then displaying the property via an outputText:
<h:outputText
value="#{CreateNewPasswordBean.errorMessage}"
render="#{CreateNewPasswordBean.errorMessage != null}" />
This solution uses an intermediate step compressing two columns of the DataFrame to a single column containing a list of the values. This works not only for strings but for all kind of column-dtypes
import pandas as pd
df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
df['list']=df[['Year','quarter']].values.tolist()
df['period']=df['list'].apply(''.join)
print(df)
Result:
Year quarter list period
0 2014 q1 [2014, q1] 2014q1
1 2015 q2 [2015, q2] 2015q2
I disagree, here's a JS free solution, which works:
<html style="height: 100%;">
<body style="vertical-align: middle; margin: 0px; height: 100%;">
<div style="height: 100%; width: 100%; display: table; background-color: #ccc;">
<div style="display: table-cell; width: 100%; vertical-align: middle;">
<div style="height: 300px; width: 600px; background-color: wheat; margin-left: auto; margin-right: auto;">A</div>
</div>
</div>
</body>
</html>
Try this:
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake_Column FROM your_table_name;
It should concatenate all that data as a single column entry named "Cake_Column".
Pure Bash, without an extra process:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)
In Ubuntu 16.04 default PHP version is 7.0, if you want to use different version then you need to install PHP package according to PHP version:
sudo apt-get install php7.4-curl
sudo apt-get install php7.3-curl
sudo apt-get install php7.2-curl
sudo apt-get install php7.1-curl
sudo apt-get install php7.0-curl
sudo apt-get install php5.6-curl
sudo apt-get install php5.5-curl
You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.
>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
3
>>> a
[1, 4, 5]
>>>
I found 3 ways to return a variable's type at runtime:
Using string formatting
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
Using reflect package
func typeof(v interface{}) string {
return reflect.TypeOf(v).String()
}
Using type assertions
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case float64:
return "float64"
//... etc
default:
return "unknown"
}
}
Every method has a different best use case:
string formatting - short and low footprint (not necessary to import reflect package)
reflect package - when need more details about the type we have access to the full reflection capabilities
type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"
Okay, it took me a while to see this, but there's no way this compiles:
return String.(ConfigurationManager.AppSettings[paramName]);
You're not even calling a method on the String
type. Just do this:
return ConfigurationManager.AppSettings[paramName];
The AppSettings
KeyValuePair already returns a string. If the name doesn't exist, it will return null
.
Based on your edit you have not yet added a Reference to the System.Configuration
assembly for the project you're working in.
For those who stuck at this error as me and nothing helped from above: check if problem folder from error.log actually exists on your server. Mine was generated automatically by Django in wrong place (was messed with static root, then manage.py collectstatic
). Have no idea why one can not name errors correctly.
To complement these other answers, the //
operator also offers significant (3x) performance benefits over /
, presuming you want integer division.
$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop
$ python -m timeit '20.5 / 2'
10,000,000 loops, best of 3: 48.4 nsec per loop
$ python -m timeit '20 / 2'
10,000,000 loops, best of 3: 43.0 nsec per loop
$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop
Try using printf
function or the concatination operator
You may want to look at how this is done in the cat
utility, for example.
See code here.
If there is no filename as argument, or it is "-", then stdin
is used for input.
stdin
will be there, even if no data is pushed to it (but then, your read call may wait forever).
The Beautiful Soup package does this immediately for you.
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
text = soup.get_text()
print(text)
NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy
, you can compute this with the ppf
method of the scipy.stats.norm
object. The acronym ppf
stands for percent point function, which is another name for the quantile function.
In [20]: from scipy.stats import norm
In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722
Check that it is the inverse of the CDF:
In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996
By default, norm.ppf
uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc
and scale
arguments, respectively.
In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945
If you look at the source code for scipy.stats.norm
, you'll find that the ppf
method ultimately calls scipy.special.ndtri
. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:
In [43]: from scipy.special import ndtri
In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722
There's no Java collection in the standard library to do this. LinkedHashSet<E>
preserves ordering similarly to a List
, though, so if you wrap your set in a List
when you want to use it as a List
you'll get the semantics you want.
Alternatively, the Commons Collections (or commons-collections4
, for the generic version) has a List
which does what you want already: SetUniqueList
/ SetUniqueList<E>
.
curl -s http://google.com > temp.html
works for curl version 7.19.5 on Ubuntu 9.10 (no progress bar). But if for some reason that does not work on your platform, you could always redirect stderr to /dev/null:
curl http://google.com 2>/dev/null > temp.html
It means that you wrote to some variables on the stack in an illegal way, most likely as the result of a Buffer overflow.
Are you looking for actual infinity or the minimal finite value? If the former, use
-numeric_limits<double>::infinity()
which only works if
numeric_limits<double>::has_infinity
Otherwise, you should use
numeric_limits<double>::lowest()
which was introduces in C++11.
If lowest()
is not available, you can fall back to
-numeric_limits<double>::max()
which may differ from lowest()
in principle, but normally doesn't in practice.
Declare @GivenDate datetime
Declare @ResultDate datetime
DEclare @EOMDate datetime
Declare @Day int
set @GivenDate=getdate()
set @GivenDate= (dateadd(mm,1,@GivenDate))
set @Day =day(@GivenDate)
set @ResultDate=dateadd(dd,-@Day+1,@GivenDate)
select @EOMDate =dateadd(dd,-1 ,@ResultDate)
select @EOMDate
As recommended by the Tensorflow GPU guide.
# Place tensors on the CPU
with tf.device('/CPU:0'):
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
# Any additional tf code placed in this block will be executed on the CPU
On providing this as input ,
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)
Python returns this as output :
'server=mpilgrim;uid=sa;database=master;pwd=secret'
To display text in vertical (Bottom-top) we can simply use:
writing-mode: vertical-lr;
transform: rotate(180deg);
#myDiv{_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#mySpan{_x000D_
writing-mode: vertical-lr; _x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div id="myDiv"> _x000D_
_x000D_
<span id="mySpan"> Here We gooooo !!! </span>_x000D_
_x000D_
</div>
_x000D_
Note we can add this to ensure Browser Compatibility:
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
we can also read more about writing-mode
property here on Mozilla docs.
Hope below answer in this link will help, Multiple Value Filter
And take a look into the fiddle with example
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.
I am using Android Studio 3.0 canary 6.
To build apk,
Click to Build->Build APK(s)
.
After your apk is build, Go to:
C:\Users\your-pc-name\AndroidStudioProjects\your-app-name\app\build\outputs\apk\debug
Here is a simple way to define those constants, and I'm pretty sure it's portable:
const double inf = 1.0/0.0;
const double nan = 0.0/0.0;
When I run this code:
printf("inf = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan = %f\n", nan);
printf("-nan = %f\n", -nan);
I get:
inf = inf
-inf = -inf
nan = -nan
-nan = nan
Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).
And it is working well...
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
JavaScript
function printDiv()
{
var divToPrint=document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
Remember that in Python when you do:
list1 = ['apples','bananas','pineapples']
list2 = list1
List2 isn't storing the actual list, but a reference to list1. So when you do anything to list1, list2 changes as well. use the copy module (not default, download on pip) to make an original copy of the list(copy.copy()
for simple lists, copy.deepcopy()
for nested ones). This makes a copy that doesn't change with the first list.
When I faced this issue the following solved it for me:
I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.
You might have old invalid username/password cached in your browser. Try clearing them and check again.
If you are using IE and somesite.com is in your Intranet security zone, IE may be sending your windows credentials automatically.
Appache commons IO various
FilenameUtils.wildcardMatch
See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.
If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.
public ActionResult Index() {
return new RedirectResult("http://www.website.com");
}
Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
In my case an iframe
with a bound src
was trying to get host/null ( when the value of the bound variable was null ).
Adding an *ngIf
to it helped.
I changed:
<iframe [src]="iframeSource"></iframe>
to
<iframe [src]="iframeSource" *ngIf="iframeSource"></iframe>
You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
Kotlin version:
Use these extensions with infix functions that simplify later calls
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
infix fun View.leftOf(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}
infix fun View.alightParentRightIs(aligned: Boolean) {
val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
if (aligned) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
} else {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
}
this.layoutParams = layoutParams
}
Then use them as infix functions calls:
view1 below view2
view1 leftOf view2
view1 alightParentRightIs true
Or you can use them as normal functions:
view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)
You can use:
var dictionary = myList.ToDictionary(x => x);
When You want to open new tab/window (depends on Your browser configuration defaults):
output = 'Hello, World!';
window.open().document.write(output);
When output is an Object
and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)
output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));
Update
Google Chrome (60.0.3112.90) block this code:
Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9
When You want to append some data to existing page
output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;
output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Element is Clickable - it is Displayed and Enabled.
require(TSDT)
c(1,3,11) %nin% 1:10
# [1] FALSE FALSE TRUE
For more information, you can refer to: https://cran.r-project.org/web/packages/TSDT/TSDT.pdf
I had this same problem, and @AniaG's solution in the comments worked for me.
src
folderAlso if you're making it a console program, you can do: print(" ")
and continue your program. I've found it the easiest way to separate my text.
Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?
Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.
tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.
Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.
hth! Regards, Remco
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
As an extension to the accepted answer, you could switch the type of Exception resulting in a pattern that is somewhat like the original example:
try {
// Try something
} catch (Exception $e) {
switch (get_class($e)) {
case 'AError':
case 'BError':
// Handle A or B
break;
case 'CError':
// Handle C
break;
case default:
// Rethrow the Exception
throw $e;
}
}