If you join the facilities table twice you will get what you are after:
select u.*
from room u
JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3'
where 1 and vizibility='1'
group by id_uc
order by u_premium desc, id_uc desc
You could try implemeting something like this: http://www.codeproject.com/KB/cs/reporting__windowsforms.aspx
Go to File -> preferences -> settings.
On the right panel you will see all customized user settings so you can remove the ones you want to reset. On doing so the default settings mentioned in left pane will become active instantly.
app.get('*',function(req,res){
res.redirect('/login');
});
You can set a default option for the column in the migration
....
add_column :status, :string, :default => "P"
....
OR
You can use a callback, before_save
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
end
end
mysql>show processlist;
mysql> kill "number from first col";
Ideally, the source code file should go within the src/default package even if you haven't provided any package name. For some reason, the source file might be outside src folder. Create within the scr folder it will work!
UPDATE: Twitter API 1 is now deprecated. Refer to above answer.
Twitter 1.1 does not work with that syntax (when I wrote this answer). Needs to be 1, not 1.1. This will work:
http://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=username
You could also just use jQuery to remove the contents of the div that contains your svg.
$("#container_div_id").html("");
It is called favicon.ico and you can generate it from this site.
Both answers provide solutions a bit more complex, as they
need to be. Say the payment was created on January 6, 2013
.
And we want to know the difference between this date and today.
sqlite> SELECT julianday() - julianday('2013-01-06');
34.7978485878557
The difference is 34 days. We can use julianday('now')
for
better clarity. In other words, we do not need to put
date()
or datetime()
functions as parameters to julianday()
function.
Using execComand:
<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">
In the next link: execCommand
Open below application
C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Apache Tomcat 8.5 Tomcat8
right click on Apache tomcat in system tray and click on stop services
Run your application from eclipse.
http://siddartech.com/apache/apachi-tomcat-server-already-in-use/
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
Adding for completeness of the answers: preloading with HTML
<link rel="preload" href="bg-image-wide.png" as="image">
Other preloading features exist, but none are quite as fit for purpose as <link rel="preload">
:
<link rel="prefetch">
has been supported in browsers for a long time,
but it is intended for prefetching resources that will be used in the
next navigation/page load (e.g. when you go to the next page). This
is fine, but isn't useful for the current page! In addition, browsers
will give prefetch resources a lower priority than preload ones — the
current page is more important than the next. See Link prefetching
FAQ for more details. <link rel="prerender">
renders a specified
webpage in the background, speeding up its load if the user navigates
to it. Because of the potential to waste users bandwidth, Chrome
treats prerender as a NoState prefetch instead. <link rel="subresource">
was supported in Chrome a while ago, and was
intended to tackle the same issue as preload, but it had a problem:
there was no way to work out a priority for the items (as didn't
exist back then), so they all got fetched with fairly low priority.There are a number of script-based resource loaders out there, but they don't have any power over the browser's fetch prioritization queue, and are subject to much the same performance problems.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
// styles.css
html {
scroll-behavior: smooth
}
Source: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2
In server proxy set like that
location / {
proxy_pass http://ip:80;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
}
In server php set like that
server {
client_body_timeout 120;
location = /index.php {
#include fastcgi.conf; //example
#fastcgi_pass unix:/run/php/php7.3-fpm.sock;//example veriosn
fastcgi_read_timeout 120s;
}
}
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
Try
num.toString(2);
The 2 is the radix and can be any base between 2 and 36
source here
UPDATE:
This will only work for positive numbers, Javascript represents negative binary integers in two's-complement notation. I made this little function which should do the trick, I haven't tested it out properly:
function dec2Bin(dec)
{
if(dec >= 0) {
return dec.toString(2);
}
else {
/* Here you could represent the number in 2s compliment but this is not what
JS uses as its not sure how many bits are in your number range. There are
some suggestions https://stackoverflow.com/questions/10936600/javascript-decimal-to-binary-64-bit
*/
return (~dec).toString(2);
}
}
I had some help from here
I'm not sure whether this could help, but I had a similar problem and I managed to solve it, by defining an apposite function:
def sor_dic_key(diction):
lista = []
diction2 = {}
for x in diction:
lista.append([x, diction[x]])
lista.sort(key=lambda x: x[0])
for l in lista:
diction2[l[0]] = l[1]
return diction2
This function returns another dictionary with the same keys and relative values, but sorted by its keys.
Similarly, I defined a function that could sort a dictionary by its values. I just needed to use x[1]
instead of x[0]
in the lambda function. I find this second function mostly useless, but one never can tell!
Taken from another post
$checktable = mysql_query("SHOW TABLES LIKE '$this_table'");
$table_exists = mysql_num_rows($checktable) > 0;
Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".
People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.
You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:
...
Two two = new Two();
x = two.fxn(x)
...
That is, make a Two-Object and call the method on that object.
...or make the fxn method static.
Try reducing the range of the for loop to range(len(a)-1)
:
a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)
Dont work for me, need to put scope in plural
validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]
A slightly more efficient approach might be
Map<String, AtomicInteger> instances = new HashMap<String, AtomicInteger>();
void add(String name) {
AtomicInteger value = instances.get(name);
if (value == null)
instances.put(name, new AtomicInteger(1));
else
value.incrementAndGet();
}
If your XML contains namespaces, then you can do the following in order to obtain the value of an attribute:
var xmlDoc = new XmlDocument();
// content is your XML as string
xmlDoc.LoadXml(content);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
// make sure the namespace identifier, URN in this case, matches what you have in your XML
nsmgr.AddNamespace("ns", "urn:oasis:names:tc:SAML:2.0:protocol");
// get the value of Destination attribute from within the Response node with a prefix who's identifier is "urn:oasis:names:tc:SAML:2.0:protocol" using XPath
var str = xmlDoc.SelectSingleNode("/ns:Response/@Destination", nsmgr);
if (str != null)
{
Console.WriteLine(str.Value);
}
There are two ways-
whoami
or
echo $USER
The cluster module allows you to utilise all cores of your machine. In fact you can take advantage of this in just 2 commands and without touching your code using a very popular process manager pm2.
npm i -g pm2
pm2 start app.js -i max
Credit goes to Sushil
Create your AlertDialog as usual:
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
Dialog dialog = dialog.create();
dialog.show();
After calling show() on your dialog, set the background color like this:
dialog.getWindow().setBackgroundDrawableResource(android.R.color.background_dark);
Technically, there's no built-in command to edit an existing symbolic link. It can be easily achieved with a few short commands.
Here's a little bash/zsh function I wrote to update an existing symbolic link:
# -----------------------------------------
# Edit an existing symbolic link
#
# @1 = Name of symbolic link to edit
# @2 = Full destination path to update existing symlink with
# -----------------------------------------
function edit-symlink () {
if [ -z "$1" ]; then
echo "Name of symbolic link you would like to edit:"
read LINK
else
LINK="$1"
fi
LINKTMP="$LINK-tmp"
if [ -z "$2" ]; then
echo "Full destination path to update existing symlink with:"
read DEST
else
DEST="$2"
fi
ln -s $DEST $LINKTMP
rm $LINK
mv $LINKTMP $LINK
printf "Updated $LINK to point to new destination -> $DEST"
}
Just incase anyone else stumbles across this, I use the fs-extra library in node and write javascript objects to a file like this:
const fse = require('fs-extra');
fse.outputJsonSync('path/to/output/file.json', objectToWriteToFile);
Using old C++ version, you can use this snippet :
template<typename T>
string toBinary(const T& t)
{
string s = "";
int n = sizeof(T)*8;
for(int i=n-1; i>=0; i--)
{
s += (t & (1 << i))?"1":"0";
}
return s;
}
int main()
{
char a, b;
short c;
a = -58;
c = -315;
b = a >> 3;
cout << "a = " << a << " => " << toBinary(a) << endl;
cout << "b = " << b << " => " << toBinary(b) << endl;
cout << "c = " << c << " => " << toBinary(c) << endl;
}
a = => 11000110
b = => 11111000
c = -315 => 1111111011000101
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
Go to build.Gradle file and replace 27 and 29 by 25 at these places 1. targetSdkVersion 25 2. implementation 'com.android.support:appcompat-v7:25.+'
it really works for me Thanks.
Scrolling an element requires changing its scrollTop
value over time. For a given point in time, calculate a new scrollTop
value. To animate smoothly, interpolate using a smooth-step algorithm.
Calculate scrollTop
as follows:
var point = smooth_step(start_time, end_time, now);
var scrollTop = Math.round(start_top + (distance * point));
Where:
start_time
is the time the animation started;end_time
is when the animation will end (start_time + duration)
;start_top
is the scrollTop
value at the beginning; anddistance
is the difference between the desired end value and the start value (target - start_top)
.A robust solution should detect when animating is interrupted, and more. Read my post about Smooth Scrolling without jQuery for details.
See the JSFiddle.
The code:
/**
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
*/
var smooth_scroll_to = function(element, target, duration) {
target = Math.round(target);
duration = Math.round(duration);
if (duration < 0) {
return Promise.reject("bad duration");
}
if (duration === 0) {
element.scrollTop = target;
return Promise.resolve();
}
var start_time = Date.now();
var end_time = start_time + duration;
var start_top = element.scrollTop;
var distance = target - start_top;
// based on http://en.wikipedia.org/wiki/Smoothstep
var smooth_step = function(start, end, point) {
if(point <= start) { return 0; }
if(point >= end) { return 1; }
var x = (point - start) / (end - start); // interpolation
return x*x*(3 - 2*x);
}
return new Promise(function(resolve, reject) {
// This is to keep track of where the element's scrollTop is
// supposed to be, based on what we're doing
var previous_top = element.scrollTop;
// This is like a think function from a game loop
var scroll_frame = function() {
if(element.scrollTop != previous_top) {
reject("interrupted");
return;
}
// set the scrollTop for this frame
var now = Date.now();
var point = smooth_step(start_time, end_time, now);
var frameTop = Math.round(start_top + (distance * point));
element.scrollTop = frameTop;
// check if we're done!
if(now >= end_time) {
resolve();
return;
}
// If we were supposed to scroll but didn't, then we
// probably hit the limit, so consider it done; not
// interrupted.
if(element.scrollTop === previous_top
&& element.scrollTop !== frameTop) {
resolve();
return;
}
previous_top = element.scrollTop;
// schedule next frame for execution
setTimeout(scroll_frame, 0);
}
// boostrap the animation process
setTimeout(scroll_frame, 0);
});
}
I found the answer.
Cast integer to string:
myOldIntValue|string
Cast string to integer:
myOldStrValue|int
Yes. Thanks
Ctrl + F11 for Portrait
and
Ctrl + F12 for Landscape
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
While deciding which characters are allowed, please remember your apostrophed and hyphenated friends. I have no control over the fact that my company generates my email address using my name from the HR system. That includes the apostrophe in my last name. I can't tell you how many times I have been blocked from interacting with a website by the fact that my email address is "invalid".
Directly from the docs:
$comma_separated = implode(",", $array);
I was the same problem because I did import incorrect library, so i checked the documentation from the library and the route was changed with the new versión, the solution was this:
import {Ionicons} from '@expo/vector-icons';
and I was writing the incorrect way:
import {Ionicons} from 'expo';
For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.
public static string GetCurrentWebsiteRoot()
{
return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
}
[
is the same as the test
builtin, and works like the test
binary (man test)
[
in all the other sh-based shells in many UNIX-like environments&&
and ||
operators must be in separate brackets. !
outside the first bracket to use the shell's facility for inverting command return values.==
and !=
are literal string comparisons[[
is a bash
==
and !=
apply bash pattern matching rules, see "Pattern Matching" in man bash
=~
regex match operator!
, &&
, and ||
logical operators within the brackets to combine subexpressionsAside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.
Here is the official answer of IntelliJ IDEA 2018.3 Help. I tried and It worked.
To build a JAR file from a module;
On the main menu, choose Build | Build Artifact.
From the drop-down list, select the desired artifact of the type JAR. The list shows all the artifacts configured for the current project. To have all the configured artifacts built, choose the Build all artifacts option.
MS's query explaining the use of the KILL
command is quite useful providing connection's information:
SELECT conn.session_id, host_name, program_name,
nt_domain, login_name, connect_time, last_request_end_time
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
ON sess.session_id = conn.session_id;
You can use exec
:
exec("import myapp.commands.%s" % command)
To clearly answer OP's question of how to determine whether a variable is set, @Lionel's answer is correct:
if test "${name+x}"; then
echo 'name is set'
else
echo 'name is not set'
fi
This question already has a lot of answers, but none of them offered bona fide boolean expressions to clearly differentiate between variables values.
Here are some unambiguous expressions that I worked out:
+-----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+-----------------------+-------------+---------+------------+
| test "$name" | TRUE | f | f |
| test -n "$name" | TRUE | f | f |
| test ! -z "$name" | TRUE | f | f |
| test ! "${name-x}" | f | TRUE | f |
| test ! "${name+x}" | f | f | TRUE |
+-----------------------+-------------+---------+------------+
By the way, these expressions are equivalent:
test <expression>
<=> [ <expression> ]
Other ambiguous expressions to be used with caution:
+----------------------+-------------+---------+------------+
| Expression in script | name='fish' | name='' | unset name |
+----------------------+-------------+---------+------------+
| test "${name+x}" | TRUE | TRUE | f |
| test "${name-x}" | TRUE | f | TRUE |
| test -z "$name" | f | TRUE | TRUE |
| test ! "$name" | f | TRUE | TRUE |
| test ! -n "$name" | f | TRUE | TRUE |
| test "$name" = '' | f | TRUE | TRUE |
+----------------------+-------------+---------+------------+
You can find the setting here in IIS:
It can be found at the server level, web site level, or app level under "ASP".
I think you can set it at the web.config level here. Please confirm this for yourself.
<configuration>
<system.web>
<!-- Session Timeout in Minutes (Also in Global.asax) -->
<sessionState timeout="1440"/>
</system.web>
</configuration>
Above answers are correct. This version is easy to follow:
Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:
Step [1] In your file which extends the RoomDatabase, change the line to:
`@Database(entities = ???.class,version = 1, exportSchema = true)`
Or
`@Database(entities = ???.class,version = 1)`
(because the default value is always true)
Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:
android{
defaultConfig{
//javaComplieOptions SECTION
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
}
}
//Other SECTION
...
}
}
$projectDir:is a variable name, you cannot change it. it will get your own project directory
schemas:is a string, you can change it to any you like. For example:
"$projectDir/MyOwnSchemas".toString()
Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.
Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none
version: '3.7'
services:
app:
image: ramansharma/einwohnertomcat:v0.0.1
deploy:
replicas: 1
ports:
- '8080:8080'
volumes:
- type: bind
source: /proc
target: /hostfs/proc
read_only: true
- type: bind
source: /sys/fs/cgroup
target: /hostfs/sys/fs/cgroup
read_only: true
- type: bind
source: /
target: /hostfs
read_only: true
networks:
hostnet: {}
networks:
- einwohner_net
- elk_elk_net
networks:
einwohner_net:
elk_elk_net:
external: true
hostnet:
external: true
name: host
For SEO reason:
<div itemscope itemtype="https://schema.org/Organization">
<p id="logo"><a href="/"><span itemprop="Brand">Your business</span> <span class="icon fa-stg"></span> - <span itemprop="makesOffer">sell staff</span></a></p>
</div>
<h1>Your awesome title</h1>
Yes, Microsoft announced that xamrin is now free with VS15 and other latest versions.
The simplest way is the platform-specific solution:
#!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`
Probably you are searching for:
require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
resp = http.get("/flv/sample/sample.flv")
open("sample.flv", "wb") do |file|
file.write(resp.body)
end
end
puts "Done."
Edit: Changed. Thank You.
Edit2: The solution which saves part of a file while downloading:
# instead of http.get
f = open('sample.flv')
begin
http.request_get('/sample.flv') do |resp|
resp.read_body do |segment|
f.write(segment)
end
end
ensure
f.close()
end
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
You can't do that using open. use codecs.
when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:
import codecs
file = codecs.open('data.txt','w','utf-8')
go to Help
-> Install New Software...
-> Add
-> Archive...
. Done.
You can find more information about which services it affects on the Microsoft docs.
see nditer
import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
y += 3
Y == np.array([6, 7, 8, 9])
y = 3
would not work, usey *= 0
andy += 3
instead.
You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.
It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.
-showsplash
org.eclipse.platform
-vm
C:\jrmc-3.1.2-1.6.0\bin\javaw.exe
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20
I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4
Using the data points from the accepted answer you can use polynomial interpolation to obtain a formula.
WolframAlpha Input: interpolating polynomial {{1,.63},{2,.82}, {3,1}, {4,1.13}, {5,1.5}, {6, 2}, {7,3}}
Formula: 0.00223611x^6 - 0.0530417x^5 + 0.496319x^4 - 2.30479x^3 + 5.51644x^2 - 6.16717x + 3.14
And use in Groovy code:
import java.math.* def convert = {x -> (0.00223611*x**6 - 0.053042*x**5 + 0.49632*x**4 - 2.30479*x**3 + 5.5164*x**2 - 6.167*x + 3.14).setScale(2, RoundingMode.HALF_UP) } (1..7).each { i -> println(convert(i)) }
2 things to mention if focus()
not working:
This way works in both Firefox and Chrome without any setTimeOut()
.
Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).
So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker
****UPDATE****
Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.
Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.
Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.
Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).
yourView.setLayoutParams(new LinearLayout.LayoutParams(width, height));
Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)
The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.
You can use memmove()
, but you have to keep track of the array size yourself:
size_t array_size = 5;
int array[5] = {1, 2, 3, 4, 5};
// delete element at index 2
memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int));
array_size--;
In C++, though, it would be better to use a std::vector
:
std::vector<int> array;
// initialize array...
// delete element at index 2
array.erase(array.begin() + 2);
You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.
Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.
From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
Make sure to double up the @@ if you are using MVC Razor:
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i
Hungry for spaghetti?
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
Here is what i found googling around:
var fileupload = require("express-fileupload");
app.use(fileupload());
Which is pretty simple mechanism for uploads
app.post("/upload", function(req, res)
{
var file;
if(!req.files)
{
res.send("File was not found");
return;
}
file = req.files.FormFieldName; // here is the field name of the form
res.send("File Uploaded");
});
Well, Pavel was close, but there's even a more simple and elegant solution to initialize a sequential container from a c style array.
In your case:
w_ (array, std::end(array))
Not possible, I believe ie has a content changed event but it is certainly not x-browser
Should I say not possible without some nasty interval chugging away in the background!
The answers above all over complicate the story.
That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.
If the user cancel the request, the data will be returned as NULL
. The thread will throw a nullPointerException
when you call data.getExtras().get("data");
. I think you just need to add a conditional to check if the data returned is null.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
I would like introduce simple script to parse RSS:
$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser
// RSS items loop
print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src
foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}
$i++;
}
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"
Closing the path in r"string" also solved this problem very well.
My device had disappeared from the adb devices list after connecting it to adb on another laptop.
I selected "Charge only" on the phone and then re-enabled USB debugging.
That resolved the problem for me.
CA5386 : Vulnerability analysis tools will alert you to these codes.
Correct code :
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
Spring MVC and Spring Boot are exist for the different purpose. So, it is not wise to compare each other as the contenders.
What is Spring Boot?
Spring Boot is a framework for packaging the spring application with sensible defaults. What does this mean?. You are developing a web application using Spring MVC, Spring Data, Hibernate and Tomcat. How do you package and deploy this application to your web server. As of now, we have to manually write the configurations, XML files, etc. for deploying to web server.
Spring Boot does that for you with Zero XML configuration in your project. Believe me, you don't need deployment descriptor, web server, etc. Spring Boot is magical framework that bundles all the dependencies for you. Finally your web application will be a standalone JAR file with embeded servers.
If you are still confused how this works, please read about microservice framework development using spring boot.
What is Spring MVC?
It is a traditional web application framework that helps you to build web applications. It is similar to Struts framework.
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.
A Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps it to the right resource such as controllers, models, and views.
I hope this helps you to understand the difference.
If you are using kotlin,consider these library. It's build for kotlin language.
AndroidHttpServer is a simple demo using ServerSocket to handle http request
https://github.com/weeChanc/AndroidHttpServer
https://github.com/ktorio/ktor
AndroidHttpServer is very small , but the feature is less as well.
Ktor is a very nice library,and the usage is simple too
Set the class .fill
to height: 100%
.fill {
min-height: 100%;
height: 100%;
}
(I put a red background for #map
so you can see it takes up 100% height)
A little speed comparison:
Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec 7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l] # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l) # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l) # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 739 ns per loop
So list comprehension and itemgetter are the fastest ways to do this.
UPDATE: For large random lists and maps I had a bit different results:
Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec 7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l] # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l) # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop
So in this case the clear winner is f = operator.itemgetter(*l); f(m)
, and clear outsider: map(lambda _: m[_], l)
.
UPDATE for Python 3.6.4:
import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l] # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l) # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
So, results for Python 3.6.4 is almost the same.
The below 'd help you to add the cert to the Root Store-
certutil -enterprise -f -v -AddStore "Root" <Cert File path>
This worked for me perfectly.
Try this one:
First set up tab order.
Then in form load event we can send a tab key press programmatically to application. So that application will give focus to 1st contol in the tab order.
in form load even write this line.
SendKeys.Send("{TAB}");
This did work for me.
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
As @birryree said, add msysgit's binary to your PATH, or use Git Bash (installed with msysgit as far as I remember) which is better than Windows' console and similar to the Unix one.
You can join
the table on itself to get the PK:
Select cpe1.PK, cpe2.MaxDate, cpe1.fmgcms_cpeclaimid
from Filteredfmgcms_claimpaymentestimate cpe1
INNER JOIN
(
select MAX(createdon) As MaxDate, fmgcms_cpeclaimid
from Filteredfmgcms_claimpaymentestimate
group by fmgcms_cpeclaimid
) cpe2
on cpe1.fmgcms_cpeclaimid = cpe2.fmgcms_cpeclaimid
and cpe1.createdon = cpe2.MaxDate
where cpe1.createdon < 'reportstartdate'
You need to Enable security and set the security realm on the Configure Global Security page (see: Standard Security Setup) and choose the appropriate Authorization method (Security Realm).
Depending on your selection, create the user using appropriate method. Recommended method is to select Jenkins’ own user database and tick Allow users to sign up, hit Save button, then you should be able to create user from the Jenkins interface. Otherwise if you've chosen external database, you need to create the user there (e.g. if it's Unix database, use credentials of existing Linux/Unix users or create a standard user using shell interface).
See also: Creating user in Jenkins via API
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
Write the following method using Java:
protected boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
Call the above method during assertion.
Please check "top" command then if your script or any are running please note 'PID'
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1384 root 20 0 514m 32m 2188 S 0.3 5.4 55:09.88 example
14490 root 20 0 15140 1216 920 R 0.3 0.2 0:00.02 example2
kill <you process ID>
Example : kill 1384
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
I think you don't need to update only some specific field. Just update whole data.
@Update query
It is a given query basically. No need to make some new query.
@Dao
interface MemoDao {
@Insert
suspend fun insert(memo: Memo)
@Delete
suspend fun delete(memo: Memo)
@Update
suspend fun update(memo: Memo)
}
Memo.class
@Entity
data class Memo (
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "title") val title: String?,
@ColumnInfo(name = "content") val content: String?,
@ColumnInfo(name = "photo") val photo: List<ByteArray>?
)
Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this
val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)
Just used this solution with Homebrew 0.9.5 and it seemed like a quick solution to upgrade to the latest stable version of node.
brew update
This will install the latest version
brew install node
Unlink your current version of node use, node -v, to find this
brew unlink node012
This will change to the most up to date version of node.
brew link node
Note: This solution worked as a result of me getting this error:
Error: No such keg: /usr/local/Cellar/node
Answer for unknown source encoding type
based on @Sébastien RoccaSerra
python3.6
import os
from chardet import detect
# get file encoding type
def get_encoding_type(file):
with open(file, 'rb') as f:
rawdata = f.read()
return detect(rawdata)['encoding']
from_codec = get_encoding_type(srcfile)
# add try: except block for reliability
try:
with open(srcfile, 'r', encoding=from_codec) as f, open(trgfile, 'w', encoding='utf-8') as e:
text = f.read() # for small files, for big use chunks
e.write(text)
os.remove(srcfile) # remove old encoding file
os.rename(trgfile, srcfile) # rename new encoding
except UnicodeDecodeError:
print('Decode Error')
except UnicodeEncodeError:
print('Encode Error')
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
It works for me...
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback = @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback
{
public static void Ignore()
{
if(ServicePointManager.ServerCertificateValidationCallback ==null)
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate
(
Object obj,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors
)
{
return true;
};
}
}
}
"@
Add-Type $certCallback
}
[ServerCertificateValidationCallback]::Ignore()
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/
My answer would be "be careful". A lot of jQuery table-sorting add-ons only sort what you pass to the browser. In many cases, you have to keep in mind that tables are dynamic sets of data, and could potentially contain zillions of lines of data.
You do mention that you only have 4 columns, but much more importantly, you don't mention how many rows we're talking about here.
If you pass 5000 lines to the browser from the database, knowing that the actual database-table contains 100,000 rows, my question is: what's the point in making the table sortable? In order to do a proper sort, you'd have to send the query back to the database, and let the database (a tool actually designed to sort data) do the sorting for you.
In direct answer to your question though, the best sorting add-on I've come across is Ingrid. There are many reasons that I don't like this add-on ("unnecessary bells and whistles..." as you call it), but one of it's best features in terms of sort, is that it uses ajax, and doesn't assume that you've already passed it all the data before it does its sort.
I recognise that this answer is probably overkill (and over 2 years late) for your requirements, but I do get annoyed when developers in my field overlook this point. So I hope someone else picks up on it.
I feel better now.
The following article helped me to combine two plots generated by ggplot2 on a single row:
Multiple graphs on one page (ggplot2) by Cookbook for R
And here is what the code may look like in this case:
p1 <-
ggplot() + aes(mns)+ geom_histogram(aes(y=..density..), binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1) + geom_density(alpha=.2)
p2 <-
ggplot() + aes(mns)+ geom_histogram( binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1)
multiplot(p1,p2,cols=2)
You can try intersection()
and subtract()
methods from CollectionUtils
.
intersection()
method gives you a collection containing common elements and the subtract()
method gives you all the uncommon ones.
They should also take care of similar elements
Does anything, easy like that, exists?? THANKS :))
C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.
You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.
In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.
Something I just found to be interesting is Django Scripts, which allows you to write scripts to be run with python manage.py runscript foobar. More detailed information on implementation and scructure can be found here, http://django-extensions.readthedocs.org/en/latest/index.html
If you don't want to implement your connector customizer
, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer
. According to the README, you only have to create your keystore, configure connector.https.*
, import the library and add @ComponentScan("org.ycavatars.sboot.kit")
. Then you'll have HTTPS connection.
''' Set Range you want to export to the folder
Workbooks("your workbook name").Sheets("yoursheet name").Select
Dim rgExp As Range: Set rgExp = Range("A1:H31")
''' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied
With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
.Name = "ChartVolumeMetricsDevEXPORT"
.Activate
End With
''' Paste into chart area, export to file, delete chart.
ActiveChart.Paste
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export "C:\ExportmyChart.jpg"
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete
Or, to get a pseudo-random int in the range 0 to 19, for example, you could use the higher bits like this:
j = ((rand() >> 15) % 20;
You could simply have: var result = (str == "true")
.
If you use Sass, there are Bootstrap variables are defined with !default
, among which you'll find font families. You can just set the variables in your own .scss
file before including the Bootstrap Sass file and !default
will not overwrite yours. Here's a good explanation of how !default
works: https://thoughtbot.com/blog/sass-default.
Here's an untested example using Bootstrap 4, npm, Gulp, gulp-sass and gulp-cssmin to give you an idea how you could hook this up together.
package.json
{
"devDependencies": {
"bootstrap": "4.0.0-alpha.6",
"gulp": "3.9.1",
"gulp-sass": "3.1.0",
"gulp-cssmin": "0.2.0"
}
}
mysite.scss
@import "./myvariables";
// Bootstrap
@import "bootstrap/scss/variables";
// ... need to include other bootstrap files here. Check node_modules\bootstrap\scss\bootstrap.scss for a list
_myvariables.scss
// For a list of Bootstrap variables you can override, look at node_modules\bootstrap\scss\_variables.scss
// These are the defaults, but you can override any values
$font-family-sans-serif: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !default;
$font-family-serif: Georgia, "Times New Roman", Times, serif !default;
$font-family-monospace: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
$font-family-base: $font-family-sans-serif !default;
gulpfile.js
var gulp = require("gulp"),
sass = require("gulp-sass"),
cssmin = require("gulp-cssmin");
gulp.task("transpile:sass", function() {
return gulp.src("./mysite.scss")
.pipe(sass({ includePaths: "./node_modules" }).on("error", sass.logError))
.pipe(cssmin())
.pipe(gulp.dest("./css/"));
});
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="mysite.css" />
</head>
<body>
...
</body>
</html>
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If you'd like to use C# 6.0:
.config
file to perform the following modifications.Look for the system.codedom
and modify it so that it will look as shown below:
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
No one commenting on the randomAge
method?
This is so awfully wrong, it couldn't be any wronger.
NSInteger
is a primitive type - it is most likely typedef'd as int
or long
.
In the randomAge
method, you calculate a number from about 1 to 98.
Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.
If you access an NSInteger
through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.
Change it either to NSInteger
or int
, which is probably the best, or to NSNumber
if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.
In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.
So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:
CREATE OR REPLACE TYPE array is table of number;
/
Then you can use it as in these two examples within PL/SQL:
SQL> l
1 declare
2 p array := array();
3 begin
4 for i in (select level from dual connect by level < 10) loop
5 p.extend;
6 p(p.count) := i.level;
7 end loop;
8 for x in (select column_value from table(cast(p as array))) loop
9 dbms_output.put_line(x.column_value);
10 end loop;
11* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
SQL> l
1 declare
2 p array := array();
3 begin
4 select level bulk collect into p from dual connect by level < 10;
5 for x in (select column_value from table(cast(p as array))) loop
6 dbms_output.put_line(x.column_value);
7 end loop;
8* end;
SQL> /
1
2
3
4
5
6
7
8
9
PL/SQL procedure successfully completed.
Additional example based on comments
Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.
CREATE OR REPLACE PACKAGE p_cache AS
FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/
CREATE OR REPLACE PACKAGE BODY p_cache AS
cache_array array;
FUNCTION get_p_cursor RETURN sys_refcursor IS
pCursor sys_refcursor;
BEGIN
OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
RETURN pCursor;
END get_p_cursor;
-- Package initialization runs once in each session that references the package
BEGIN
SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
END p_cache;
/
Using C++11:
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Using Boost.Assign:
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
While you can do
value = d.values()[index]
It should be faster to do
value = next( v for i, v in enumerate(d.itervalues()) if i == index )
edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.
Also, note that this assumes that your index is not negative
That doesn't work because distToPoint
is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p)
. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p)
.
with python2
pip show tensorflow
to check install
python test.py
to run test
with python3
pip3 show tensorflow
to check install
python3 test.py
to run test
test.py
import tensorflow as tf
import numpy as np
c = np.array([[3.,4], [5.,6], [6.,7]])
step = tf.reduce_mean(c, 1)
with tf.Session() as sess:
print(sess.run(step))
Or, if you haven't install tensorflow yet, try the offical document
I recently used ez_setup.py
as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:
Installing easy_install Using ez_setup.py
I hope you find this helpful.
I think that there is no easy answer to this question. How you might really approach this solution depends on your requirements. Do you need a cross platform solution? Are you using new/delete or malloc/free (or both)? Are you really looking for just "leaks" or do you want better protection, such as detecting buffer overruns (or underruns)?
If you are working on the windows side, the MS debug runtime libraries have some basic debug detection functionality, and as another has already pointed out, there are several wrappers that can be included in your source to help with leak detection. Finding a package that can work with both new/delete and malloc/free obviously gives you more flexibility.
I don't know enough about the unix side to provide help, although again, others have.
But beyond just leak detection, there is the notion of detecting memory corruption via buffer overruns (or underruns). This type of debug functionality is I think more difficult than plain leak detection. This type of system is also further complicated if you are working with C++ objects because polymorhpic classes can be deleted in varying ways causing trickiness in determining the true base pointer that is being deleted. I know of no good "free" system that does decent protection for overruns. we have written a system (cross platform) and found it to be pretty challenging.
string DemoLimit = "02/28/2018";
string pattern = "MM/dd/yyyy";
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(DemoLimit, pattern, enUS,
DateTimeStyles.AdjustToUniversal, out datelimit);
For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
You need to CAST your numeric data to strings before you do string concatenation, so for example use CAST(@Actual_Dims_Lenght AS VARCHAR)
instead of just @Actual_Dims_Lenght
, &c.
I've just tested the following in Chrome (79), Firefox (71) and Edge (44) and it works fine. It applies the script solution as others noted above.
Just add a "Logout" link and when clicked return the following html
<div>You have been logged out. Redirecting to home...</div>
<script>
var XHR = new XMLHttpRequest();
XHR.open("GET", "/Home/MyProtectedPage", true, "no user", "no password");
XHR.send();
setTimeout(function () {
window.location.href = "/";
}, 3000);
</script>
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
I was facing same issue. I solved it with retrofit. Let me show this...
If your error JSON structure are like
{
"error": {
"status": "The email field is required."
}
}
My ErrorRespnce.java
public class ErrorResponse {
@SerializedName("error")
@Expose
private ErrorStatus error;
public ErrorStatus getError() {
return error;
}
public void setError(ErrorStatus error) {
this.error = error;
}
}
And this my Error status class
public class ErrorStatus {
@SerializedName("status")
@Expose
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Now we need a class which can handle our json.
public class ErrorUtils {
public static ErrorResponse parseError (Response<?> response){
Converter<ResponseBody , ErrorResponse> converter = ApiClient.getClient().responseBodyConverter(ErrorResponse.class , new Annotation[0]);
ErrorResponse errorResponse;
try{
errorResponse = converter.convert(response.errorBody());
}catch (IOException e){
return new ErrorResponse();
}
return errorResponse;
}
}
Now we can check our response in retrofit api call
private void registrationRequest(String name , String email , String password , String c_password){
final Call<RegistrationResponce> registrationResponceCall = apiInterface.getRegistration(name , email , password , c_password);
registrationResponceCall.enqueue(new Callback<RegistrationResponce>() {
@Override
public void onResponse(Call<RegistrationResponce> call, Response<RegistrationResponce> response) {
if (response.code() == 200){
}else if (response.code() == 401){
ErrorResponse errorResponse = ErrorUtils.parseError(response);
Toast.makeText(MainActivity.this, ""+errorResponse.getError().getStatus(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<RegistrationResponce> call, Throwable t) {
}
});
}
That's it now you can show your Toast
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
To complement ruslik's answer, in C++14 you can use this construction:
delete std::exchange(heapObject, nullptr);
I had a 12GB file to edit today. The vim LargeFile plugin did not work for me. It still used up all my memory and then printed an error message :-(. I could not use hexedit for either, as it cannot insert anything, just overwrite. Here is an alternative approach:
You split the file, edit the parts and then recombine it. You still need twice the disk space though.
Grep for something surrounding the line you would like to edit:
grep -n 'something' HUGEFILE | head -n 1
Extract that range of the file. Say the lines you want to edit are at line 4 and 5. Then do:
sed -n -e '4,5p' -e '5q' HUGEFILE > SMALLPART
-n
option is required to suppress the default behaviour of sed to print everything4,5p
prints lines 4 and 55q
aborts sed after processing line 5 Edit SMALLPART
using your favourite editor.
Combine the file:
(head -n 3 HUGEFILE; cat SMALLPART; sed -e '1,5d' HUGEFILE) > HUGEFILE.new
HUGEFILE.new
will now be your edited file, you can delete the original HUGEFILE
.
For Swift with a UINavigationController:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if self.navigationController?.topViewController != self {
print("back button tapped")
}
}
This helped me:
bool fileExists = (System.IO.File.Exists(filePath) ? true : false);
Update June 2017 (from VSCode 1.14)
The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch
" command.
And PR 27405 added handling the diff3-style merge correctly.
Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers
From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.
Original answer 2016:
The Version Control doc does not mention merge commands, only merge status and conflict support.
Even the latest 1.3 June release does not bring anything new to the VCS front.
This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool
, because:
Is this feature being included in the next iteration, by any chance?
Probably not, this is a big endeavour, since a merge UI needs to be implemented.
That leaves the actual merge to be initiated from command line only.
Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.
interface A { }
interface B { }
class Base { }
class AnotherClass { }
Possible ways to inherit:
class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)
This is not legal:
class SomeClass : Base, AnotherClass { }
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String cunvertCurrentDate="06/09/2015";
Date date = new Date();
date = df.parse(cunvertCurrentDate);
I was getting this error when executing in python3,I got the same program working by simply executing in python2
Here's a way you can do it asynchronously and manage things like you would normally. Everything is still shared. You get a reference to the object that you want updated. Whenever you update that in your service, it gets updated globally without having to watch or return a promise. This is really nice because you can update the underlying object from within the service without ever having to rebind. Using Angular the way it's meant to be used. I think it's probably a bad idea to make $http.get/post synchronous. You'll get a noticeable delay in the script.
app.factory('AssessmentSettingsService', ['$http', function($http) {
//assessment is what I want to keep updating
var settings = { assessment: null };
return {
getSettings: function () {
//return settings so I can keep updating assessment and the
//reference to settings will stay in tact
return settings;
},
updateAssessment: function () {
$http.get('/assessment/api/get/' + scan.assessmentId).success(function(response) {
//I don't have to return a thing. I just set the object.
settings.assessment = response;
});
}
};
}]);
...
controller: ['$scope', '$http', 'AssessmentSettingsService', function ($scope, as) {
$scope.settings = as.getSettings();
//Look. I can even update after I've already grabbed the object
as.updateAssessment();
And somewhere in a view:
<h1>{{settings.assessment.title}}</h1>
The division operator is /
, not \
I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.
This looks like a homework question, so I'll just give you a few pointers:
Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.
You're not using Scanner for anything, and it's not needed here, get rid of it.
Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0;
may return true or false, depending on the value of a. But return fileName;
will just return the value of fileName, which is a String.
You can use git rebase --interactive
, using the edit
command on the commit you want to amend.
CSTR({number_field}, 0, '')
The second placeholder is for decimals.
The last placeholder is for thousands separator.
How about merging 2 data tables and then comparing the changes? Not sure if that will fill 100% of your needs but for the quick compare it will do a job.
public DataTable GetTwoDataTablesChanges(DataTable firstDataTable, DataTable secondDataTable)
{
firstDataTable.Merge(secondDataTable);
return secondDataTable.GetChanges();
}
You can read more about DataTable.Merge()
The purpose of interfaces is polymorphism, a.k.a. type substitution. For example, given the following method:
public void scale(IBox b, int i) {
b.setSize(b.getSize() * i);
}
When calling the scale
method, you can provide any value that is of a type that implements the IBox
interface. In other words, if Rectangle
and Square
both implement IBox
, you can provide either a Rectangle
or a Square
wherever an IBox
is expected.
Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.
You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad
SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate
SET ROWCOUNT 0
I have tried this and quite Simple process:
Created a new Package with required name--> Moved all my classes to this new package (Right click on previous package --> Refractor--> Move)
Do not use CDATA in HTML4 but you should use CDATA in XHTML and must use CDATA in XML if you have unescaped symbols like < and >.
data
will return you a string representation of a list, but it is actually still a string. Just check the type of data
with type(data)
. That means if you try using indexing on this string representation of a list as such data['fruits'][0]
, it will return you "[" as it is the first character of data['fruits']
You can do json.loads(data['fruits'])
to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here
To get the exact file name from the URI, I would use this method:
<?php
$file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;
//basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.
echo $basename = substr($file1, 0, strpos($file1, '?'));
?>
I really like the approach posted by "orange80". It's elegant because you can set it once and forget it.
The other approaches require you to do something different (call something other than plain console.log()
every time), which is just asking for trouble… I know that I'd eventually forget.
I've taken it a step further, by wrapping the code in a utility function that you can call once at the beginning of your javascript, anywhere as long as it's before any logging. (I'm installing this in my company's event data router product. It will help simplify the cross-browser design of its new admin interface.)
/**
* Call once at beginning to ensure your app can safely call console.log() and
* console.dir(), even on browsers that don't support it. You may not get useful
* logging on those browers, but at least you won't generate errors.
*
* @param alertFallback - if 'true', all logs become alerts, if necessary.
* (not usually suitable for production)
*/
function fixConsole(alertFallback)
{
if (typeof console === "undefined")
{
console = {}; // define it if it doesn't exist already
}
if (typeof console.log === "undefined")
{
if (alertFallback) { console.log = function(msg) { alert(msg); }; }
else { console.log = function() {}; }
}
if (typeof console.dir === "undefined")
{
if (alertFallback)
{
// THIS COULD BE IMPROVED… maybe list all the object properties?
console.dir = function(obj) { alert("DIR: "+obj); };
}
else { console.dir = function() {}; }
}
}
It looks like you want the return
keyword
def check_ping():
hostname = "taylor"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:
pingstatus = check_ping()
NOTE: ping -c
is for Linux, for Windows use ping -n
Some info on python functions:
http://www.tutorialspoint.com/python/python_functions.htm
http://www.learnpython.org/en/Functions
It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com
1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.
2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.
One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install
, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.
This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.
So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.
What if you wanna update? Then in your dev environment run: composer update
, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.
3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.
Try this: sed -i '/^[ \t]*$/d' file-name
It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.
Note: there is a 'space' followed by '\t' inside the square bracket.
The modifier -i
will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on @davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
def if_lives_overlap(s1, s2):
"""
https://stackoverflow.com/a/325964/827391
5 10 15 20
----------------
s1: -----
s2: -----
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 10)},
... s2={'start': datetime(2020, 1, 15),
... 'end': datetime(2020, 1, 20)})
False
s1: -----
s2: -----
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 15),
... 'end': datetime(2020, 1, 20)},
... s2={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 10)})
False
s1: ----------
s2: ----------
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 15)},
... s2={'start': datetime(2020, 1, 10),
... 'end': datetime(2020, 1, 20)})
True
s1: ----------
s2: ----------
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 10),
... 'end': datetime(2020, 1, 20)},
... s2={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 15)})
True
s1: ---------------
s2: -----
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 20)},
... s2={'start': datetime(2020, 1, 10),
... 'end': datetime(2020, 1, 15)})
True
s1: -----
s2: ---------------
>>> if_lives_overlap(s1={'start': datetime(2020, 1, 10),
... 'end': datetime(2020, 1, 15)},
... s2={'start': datetime(2020, 1, 5),
... 'end': datetime(2020, 1, 20)})
True
"""
return (s1['start'] <= s2['end']) and (s1['end'] >= s2['start'])
I tried the binding according to the answer by @Szymon but It did not work for me. I tried basicHttpsBinding which is new in .net 4.5 and It solved the issue. Here is the complete configuration that works for me.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpsBinding>
<binding name="basicHttpsBindingForYourService">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"/>
</security>
</binding>
</basicHttpsBinding>
</bindings>
<services>
<service name="YourServiceName">
<endpoint address="" binding="basicHttpsBinding" bindingName="basicHttpsBindingForYourService" contract="YourContract" />
</service>
</services>
</system.serviceModel>
FYI: My application's target framework is 4.5.1. IIS web site that I created to deploy this wcf service only has https binding enabled.
There are different ways to do that.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })
def getMonth(s): return s.split("-")[1] def getDay(s): return s.split("-")[0] def getYear(s): return s.split("-")[2] def getYearMonth(s): return s.split("-")[1]+"-"+s.split("-")[2]
year
, month
, day
and 'yearMonth
'. In your case, you need one of both. You can group using two columns 'year','month'
or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x)) df['month']= df['Date'].apply(lambda x: getMonth(x)) df['day']= df['Date'].apply(lambda x: getDay(x)) df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
3 20-Jan-14 25 15 14 Jan 20 Jan-14
4 21-Feb-14 60 80 14 Feb 21 Feb-14
In this case, we are grouping by two columns:
for key,g in df.groupby(['year','month']): print key,g
Output:
('13', 'Jun') Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
('13', 'Aug') Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
('14', 'Jan') Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
('14', 'Feb') Date abc xyz year month day YearMonth
In this case, we are grouping by one column:
for key,g in df.groupby(['YearMonth']): print key,g
Output:
Jun-13 Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
Aug-13 Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
Jan-14 Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
Feb-14 Date abc xyz year month day YearMonth
4 21-Feb-14 60 80 14 Feb 21 Feb-14
get_group
print df.groupby(['YearMonth']).get_group('Jun-13')
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
get_group
. This hack would help to filter values and get the grouped values.This also would give the same result.
print df[df['YearMonth']=='Jun-13']
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
You can select list of abc
or xyz
values during Jun-13
print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values
Output:
[100 -20] #abc values
[200 50] #xyz values
You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.
for x in set(df.YearMonth):
print df[df['YearMonth']==x].abc.values
print df[df['YearMonth']==x].xyz.values
I recommend also to check this answer as well.
This can be resolved by specifying the specific column names desired from the specific table like so:
$c = Customer::leftJoin('orders', function($join) {
$join->on('customers.id', '=', 'orders.customer_id');
})
->whereNull('orders.customer_id')
->first([
'customers.id',
'customers.first_name',
'customers.last_name',
'customers.email',
'customers.phone',
'customers.address1',
'customers.address2',
'customers.city',
'customers.state',
'customers.county',
'customers.district',
'customers.postal_code',
'customers.country'
]);
This should be equivalent to your current code, only a lot faster:
output <- matrix(unlist(z), ncol = 10, byrow = TRUE)
I've the same message, I have a webpage with do on visual studio 2010, I read a file.xls on that page,in my project visual has not any problem, when I put it on my IIS local throw me a 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine' ,I fixed that problem next following this steps,
1.-Open IIS
2.-Change the appPool on Advanced Settings
3.-true to enable to 32-bit application.
and that's all
ps.I changed Configuration Manager to X86 on Active Solution Platform
Have a look at this article: Tracing python memory leaks
Also, note that the garbage collection module actually can have debug flags set. Look at the set_debug
function. Additionally, look at this code by Gnibbler for determining the types of objects that have been created after a call.
concat
also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe
df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column
review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame
# Gets rows in df where IDs match in the userID column and combines them
dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])
If you can use pandas
, then value_counts
is there for rescue.
>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1 3
4 2
3 1
2 1
dtype: int64
It automatically sorts the result based on frequency as well.
If you want the result to be in a list of list, do as below
>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]
mhh. I got another solution which helped me, 'cause I just have two different sates:
In my .xml I define the ImageButton like this:
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selector" />
The corresponding selector file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ico_100_checked" android:state_selected="true"/>
<item android:drawable="@drawable/ico_100_unchecked"/>
</selector>
And in my onCreate I call:
final ImageButton ib = (ImageButton) value.findViewById(R.id.imageButton);
OnClickListener ocl =new OnClickListener() {
@Override
public void onClick(View button) {
if (button.isSelected()){
button.setSelected(false);
} else {
ib.setSelected(false);
//put all the other buttons you might want to disable here...
button.setSelected(true);
}
}
};
ib.setOnClickListener(ocl);
//add ocl to all the other buttons
done. hope this helps. took me a while to figure out.
You can either set
border-bottom: none;
or
border-bottom: 0;
One sets the border-style
to none
.
One sets the border-width
to 0px
.
div {_x000D_
border: 3px solid #900;_x000D_
_x000D_
background-color: limegreen; _x000D_
width: 28vw;_x000D_
height: 10vw;_x000D_
margin: 1vw;_x000D_
text-align: center;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.stylenone {_x000D_
border-bottom: none;_x000D_
}_x000D_
.widthzero {_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div>_x000D_
(full border)_x000D_
</div>_x000D_
<div class="stylenone">_x000D_
(style)<br><br>_x000D_
_x000D_
border-bottom: none;_x000D_
</div>_x000D_
<div class="widthzero">_x000D_
(width)<br><br>_x000D_
border-bottom: 0;_x000D_
</div>
_x000D_
Side Note:
If you ever have to track down why a border is not showing when you expect it to,
It is also good to know that either of these could be the culprit.
Also verify the border-color
is not the same as the background-color
.
Renames all .pdf
files based on current system date. For example a file named Gross Profit.pdf
is renamed to Gross Profit 2014-07-31.pdf
. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf
.
You could replace the ?
with the report name Gross Profit
, but it will only rename the one report. The ?
renames everything in the Conduit
folder. The reason there are so many ?
, is that some .pdf
s have long names. If you just put 12 ?
s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?
, then try it with many ?
s. The ?
length should be a little longer or as long as the longest report name.
@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"
Print arbitrarily named remote fetch URLs:
git remote -v | grep fetch | awk '{print $2}'
Run
cordova -v
to see the currently running version. Run the npm info command
npm info cordova
for a longer listing that includes the current version along with other available version numbers
Most importantly you need to mount the drive
net use z: \\yourserver\sharename
Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:
"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.
Then run your batch script with the following changes
copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"
this is just a shot in the dark : when you call connect without a bind first, the system allocates your local port, and if you have multiple threads connecting and disconnecting it could possibly try to allocate a port already in use. the kernel source file inet_connection_sock.c hints at this condition. just as an experiment try doing a bind to a local port first, making sure each bind/connect uses a different local port number.
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
You could try with android:background="@android:drawable/list_selector_background"
to get the same effect as the "Add alarm" in the default "Alarm Clock" (now Desk Clock).
run the below code in Terminal
makesure You are inside your project folder in terminal
ng g s servicename --module=app.module
div#a {
background-image: url('../images/spacer.png');
background-image: none !important;
}
I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none
even though it is marked !important
.
ProgressDialog dialog =
ProgressDialog.show(yourActivity.this, "", "Please Wait...");
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
The string is a .NET string so you can use .NET methods. In your case:
$index = "The string".IndexOf(" ")
will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx
For your need try something like:
$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)
Or you could use regexps:
if ($s -Match '(_)(.*)(\.)[^.]*$') { $matches[2] }
(has to be adjusted depending on exactly what you need).
i like the bootstrap3 style as the device width of bootstrap4
so i modify the css as below
<pre>
.visible-xs, .visible-sm, .visible-md, .visible-lg { display:none !important; }
.visible-xs-block, .visible-xs-inline, .visible-xs-inline-block,
.visible-sm-block, .visible-sm-inline, .visible-sm-inline-block,
.visible-md-block, .visible-md-inline, .visible-md-inline-block,
.visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display:none !important; }
@media (max-width:575px) {
table.visible-xs { display:table !important; }
tr.visible-xs { display:table-row !important; }
th.visible-xs, td.visible-xs { display:table-cell !important; }
.visible-xs { display:block !important; }
.visible-xs-block { display:block !important; }
.visible-xs-inline { display:inline !important; }
.visible-xs-inline-block { display:inline-block !important; }
}
@media (min-width:576px) and (max-width:767px) {
table.visible-sm { display:table !important; }
tr.visible-sm { display:table-row !important; }
th.visible-sm,
td.visible-sm { display:table-cell !important; }
.visible-sm { display:block !important; }
.visible-sm-block { display:block !important; }
.visible-sm-inline { display:inline !important; }
.visible-sm-inline-block { display:inline-block !important; }
}
@media (min-width:768px) and (max-width:991px) {
table.visible-md { display:table !important; }
tr.visible-md { display:table-row !important; }
th.visible-md,
td.visible-md { display:table-cell !important; }
.visible-md { display:block !important; }
.visible-md-block { display:block !important; }
.visible-md-inline { display:inline !important; }
.visible-md-inline-block { display:inline-block !important; }
}
@media (min-width:992px) and (max-width:1199px) {
table.visible-lg { display:table !important; }
tr.visible-lg { display:table-row !important; }
th.visible-lg,
td.visible-lg { display:table-cell !important; }
.visible-lg { display:block !important; }
.visible-lg-block { display:block !important; }
.visible-lg-inline { display:inline !important; }
.visible-lg-inline-block { display:inline-block !important; }
}
@media (min-width:1200px) {
table.visible-xl { display:table !important; }
tr.visible-xl { display:table-row !important; }
th.visible-xl,
td.visible-xl { display:table-cell !important; }
.visible-xl { display:block !important; }
.visible-xl-block { display:block !important; }
.visible-xl-inline { display:inline !important; }
.visible-xl-inline-block { display:inline-block !important; }
}
@media (max-width:575px) { .hidden-xs{display:none !important;} }
@media (min-width:576px) and (max-width:767px) { .hidden-sm{display:none !important;} }
@media (min-width:768px) and (max-width:991px) { .hidden-md{display:none !important;} }
@media (min-width:992px) and (max-width:1199px) { .hidden-lg{display:none !important;} }
@media (min-width:1200px) { .hidden-xl{display:none !important;} }
</pre>
<kdb></kdb>
is required when we have a space in Alias Name like
SELECT employee_id,department_id AS "Department ID"
FROM employees
order by department
Use x86 images and download "Intel Hardware Accelerated Execution Manager" from the sdk manager.
See here how to enable it: http://developer.android.com/tools/devices/emulator.html#accel-vm
Your emulator will be super fast!
I started creating a Node.js/browserify application following the Cross Platform JavaScript blog post. And I ran into this issue, because my brand new Gruntfile didn't pass jshint.
Luckily I found an answer in the Leanpub book on Grunt:
If we try it now, we will scan our Gruntfile… and get some errors:
$ grunt jshint Running "jshint:all" (jshint) task Linting Gruntfile.js...ERROR [L1:C1] W097: Use the function form of "use strict". 'use strict'; Linting Gruntfile.js...ERROR [L3:C1] W117: 'module' is not defined. module.exports = function (grunt) { Warning: Task "jshint:all" failed. Use --force to continue.
Both errors are because the Gruntfile is a Node program, and by default JSHint does not recognise or allow the use of
module
and the string version ofuse strict
. We can set a JSHint rule that will accept our Node programs. Let’s edit our jshint task configuration and add an options key:jshint: { options: { node: true }, }
Adding node: true
to the jshint options
, to put jshint into "Node mode", removed both errors for me.
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference
package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml
like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
A succinct solution:
public static double round(double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
See also, https://stackoverflow.com/a/22186845/212950 Thanks to jpdymond for offering this.
As is described in this GitHub issue the build actually happens in /tmp/docker-12345
, so a relative path like ../relative-add/some-file
is relative to /tmp/docker-12345
. It would thus search for /tmp/relative-add/some-file
, which is also shown in the error message.*
It is not allowed to include files from outside the build directory, so this results in the "Forbidden path" message."
<script type="text/javascript">document.write(new Date().getFullYear());</script>
In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :
android:button="@null"
Also it would be better to use styles as there are several radio buttons :
<RadioButton style="@style/RadioButtonStyle" ... />
<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
<item name="android:background">@drawable/customButtonBackground</item>
<item name="android:button">@null</item>
</style>
You'll need the Seslyn customButtonBackground drawable too.
You should not execute resource intensive tasks in the main thread. It will make the UI unresponsive and you will get an ANR. It seems like you will be doing resource intensive stuff and want the user to see the ProgressDialog
. You can take a look at http://developer.android.com/reference/android/os/AsyncTask.html to do resource intensive tasks. It also shows you how to use a ProgressDialog
.
One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.
What you can do to prevent this (thanks Wade) is:
if (inType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
You might also want to handle the UIWebViewNavigationTypeFormSubmitted
and UIWebViewNavigationTypeFormResubmitted
types.
@Jon's :parse
/:endparse
scheme is a great start, and he has my gratitude for the initial pass, but if you think that the Windows torturous batch system would let you off that easy… well, my friend, you are in for a shock. I have spent the whole day with this devilry, and after much painful research and experimentation I finally managed something viable for a real-life utility.
Let us say that we want to implement a utility foobar
. It requires an initial command. It has an optional parameter --foo
which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default
. It also has an optional parameter --bar
which takes a required value. Lastly it can take a flag --baz
with no value allowed. Oh, and these parameters can come in any order.
In other words, it looks like this:
foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]
Complicated? No, that seems pretty typical of real life utilities. (git
anyone?)
Without further ado, here is a solution:
@ECHO OFF
SETLOCAL
REM FooBar parameter demo
REM By Garret Wilson
SET CMD=%~1
IF "%CMD%" == "" (
GOTO usage
)
SET FOO=
SET DEFAULT_FOO=default
SET BAR=
SET BAZ=
SHIFT
:args
SET PARAM=%~1
SET ARG=%~2
IF "%PARAM%" == "--foo" (
SHIFT
IF NOT "%ARG%" == "" (
IF NOT "%ARG:~0,2%" == "--" (
SET FOO=%ARG%
SHIFT
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE (
SET FOO=%DEFAULT_FOO%
)
) ELSE IF "%PARAM%" == "--bar" (
SHIFT
IF NOT "%ARG%" == "" (
SET BAR=%ARG%
SHIFT
) ELSE (
ECHO Missing bar value. 1>&2
ECHO:
GOTO usage
)
) ELSE IF "%PARAM%" == "--baz" (
SHIFT
SET BAZ=true
) ELSE IF "%PARAM%" == "" (
GOTO endargs
) ELSE (
ECHO Unrecognized option %1. 1>&2
ECHO:
GOTO usage
)
GOTO args
:endargs
ECHO Command: %CMD%
IF NOT "%FOO%" == "" (
ECHO Foo: %FOO%
)
IF NOT "%BAR%" == "" (
ECHO Bar: %BAR%
)
IF "%BAZ%" == "true" (
ECHO Baz
)
REM TODO do something with FOO, BAR, and/or BAZ
GOTO :eof
:usage
ECHO FooBar
ECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]
EXIT /B 1
Yes, it really is that bad. See my similar post at https://stackoverflow.com/a/50653047/421049, where I provide more analysis of what is going on in the logic, and why I used certain constructs.
Hideous. Most of that I had to learn today. And it hurt.
Removing the proxy settings resolved the issue:
If you are no using any proxy:
npm config rm proxy
npm config rm https-proxy
If you are using Proxy:
npm config set proxy http://proxyhostname:proxyport
npm config set https-proxy https://proxyhostname:proxyport
Hopefully this will solve your problem :)
The code as posted in the question cannot generate that error, because Project
is not a user-defined function / valid constructor.
function x(a,b,c){}
new x(1,2,3); // produces no errors
You've probably done something like this:
function Project(a,b,c) {}
Project = {}; // or possibly Project = new Project
new Project(1,2,3); // -> TypeError: Project is not a constructor
Variable declarations using var
are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:
function Project(){}
function localTest() {
new Project(1,2,3); // `Project` points to the local variable,
// not the global constructor!
//...some noise, causing you to forget that the `Project` constructor was used
var Project = 1; // Evaluated first
}
Declare correct sys.path list before you call module:
import os, sys
#'/home/user/example/parent/child'
current_path = os.path.abspath('.')
#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)
sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')
You can get the url like this:
Request.Headers["Referer"]
Explanation
The Request.UrlReferer
will throw a System.UriFormatException
if the referer HTTP header is malformed (which can happen since it is not usually under your control).
As for using Request.ServerVariables
, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
I guess I don't understand why you would prefer the Request.ServerVariables
over Request.Headers
, since Request.ServerVariables
contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.
So the best solution is to use the Request.Headers
collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.
cd "`dirname $(readlink -f ${0})`"
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
I'm working on firefox. and I was having the same issue, input type text are auto defined something looks like boxshadow inset, but it's not.
the you want to change is border... just setting border:0;
and you're done.
If somebody needs this solution in Swift 5:
private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}