If you are using YAML for configuration, then it might be indentation problem. Thoroughly check the YAML files.
Using explicit parameters, it would be:
$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'
EDIT: quotes.
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
The link @gertvdijk provided shows a quick way to achieve the desired results without configuring a local repository:
$ yum --nogpgcheck localinstall packagename.arch.rpm
Just change packagename.arch.rpm
to the RPM filename you want to install.
Edit Just a clarification, this will automatically install all dependencies that are already available via system YUM repositories.
If you have dependencies satisfied by other RPMs that are not in the system's repositories, then this method will not work unless each RPM is also specified along with packagename.arch.rpm
on the command line.
The easiest way to do this is:
list.sort(key = lambda x:len(x))
Using scale_x_discrete (limits = ...)
to specify the order of bars.
positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)
It is not possible to assign values to an array all at once after initialization. The best alternative would be to use a loop.
for(i=0;i<N;i++)
{
array[i] = i;
}
You can hard code and assign values like --array[0] = 1
and so on.
Memcpy can also be used if you have the data stored in an array already.
function foo(Array $array)
{
return $array;
}
There should be an easier way to do this, but, depending on what you're trying to do, the best route might be to convert to a regular Python datetime object:
datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4
Based on comments below, this seems to only work in Python 2.7.x and Python 3.6+
Mongoose (Formerly Simple HTTP Daemon) is pretty good. In particular, it's embeddable and compiles under Windows, Windows CE, and UNIX.
Here is how you could do it with Java 11's java.net.http package:
var fileA = new File("a.pdf");
var fileB = new File("b.pdf");
var mimeMultipartData = MimeMultipartData.newBuilder()
.withCharset(StandardCharsets.UTF_8)
.addFile("file1", fileA.toPath(), Files.probeContentType(fileA.toPath()))
.addFile("file2", fileB.toPath(), Files.probeContentType(fileB.toPath()))
.build();
var request = HttpRequest.newBuilder()
.header("Content-Type", mimeMultipartData.getContentType())
.POST(mimeMultipartData.getBodyPublisher())
.uri(URI.create("http://somehost/upload"))
.build();
var httpClient = HttpClient.newBuilder().build();
var response = httpClient.send(request, BodyHandlers.ofString());
With the following MimeMultipartData:
public class MimeMultipartData {
public static class Builder {
private String boundary;
private Charset charset = StandardCharsets.UTF_8;
private List<MimedFile> files = new ArrayList<MimedFile>();
private Map<String, String> texts = new LinkedHashMap<>();
private Builder() {
this.boundary = new BigInteger(128, new Random()).toString();
}
public Builder withCharset(Charset charset) {
this.charset = charset;
return this;
}
public Builder withBoundary(String boundary) {
this.boundary = boundary;
return this;
}
public Builder addFile(String name, Path path, String mimeType) {
this.files.add(new MimedFile(name, path, mimeType));
return this;
}
public Builder addText(String name, String text) {
texts.put(name, text);
return this;
}
public MimeMultipartData build() throws IOException {
MimeMultipartData mimeMultipartData = new MimeMultipartData();
mimeMultipartData.boundary = boundary;
var newline = "\r\n".getBytes(charset);
var byteArrayOutputStream = new ByteArrayOutputStream();
for (var f : files) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + f.name + "\"; filename=\"" + f.path.getFileName() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Type: " + f.mimeType).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(Files.readAllBytes(f.path));
byteArrayOutputStream.write(newline);
}
for (var entry: texts.entrySet()) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(entry.getValue().getBytes(charset));
byteArrayOutputStream.write(newline);
}
byteArrayOutputStream.write(("--" + boundary + "--").getBytes(charset));
mimeMultipartData.bodyPublisher = BodyPublishers.ofByteArray(byteArrayOutputStream.toByteArray());
return mimeMultipartData;
}
public class MimedFile {
public final String name;
public final Path path;
public final String mimeType;
public MimedFile(String name, Path path, String mimeType) {
this.name = name;
this.path = path;
this.mimeType = mimeType;
}
}
}
private String boundary;
private BodyPublisher bodyPublisher;
private MimeMultipartData() {
}
public static Builder newBuilder() {
return new Builder();
}
public BodyPublisher getBodyPublisher() throws IOException {
return bodyPublisher;
}
public String getContentType() {
return "multipart/form-data; boundary=" + boundary;
}
}
Using Powershell 5.1
get-childitem *logs* -path .\ -directory -recurse | remove-item -confirm:$false -recurse -force
Replace logs with the directory name you want to delete.
get-childitem searches for the children directory with the name recursively from current path (.).
remove-item deletes the result.
PLease make sure to backup your changes before running these commmand in a separate folder
git checkout branch_name
Checkout on your branch
git merge --abort
Abort the merge
git status
Check status of the code after aborting the merge
git reset --hard origin/branch_name
these command will reset your changes and align your code with the branch_name (branch) code.
It is safer and more flexible to load the assembly into its own AppDomain
first.
So instead of the answer given previously:
var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
I would suggest the following (adapted from this answer to a related question):
var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
Now you can unload the assembly and have different security settings.
If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn
namespace). For more information, see this article on Add-ins and Extensibility on MSDN.
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.
For future searches as well, I had an mp4 file that I downscaled with Handbrake using handbrake-gtk
from apt-get
, e.g. sudo apt-get install handbrake-gtk
. In Ubuntu 14.04, the handbrake
repository doesn't include support for MP4 out of the box. I left the default settings, stripped the audio track out, and it generates an *.M4V file. For those wondering, they are the same container but M4V is primarily used on iOS to open in iTunes.
This worked in all browsers except Safari:
<video preload="yes" autoplay loop width="100%" height="auto" poster="http://cdn.foo.com/bar.png">
<source src="//cdn.foo.com/bar-video.m4v" type="video/mp4">
<source src="//cdn.foo.com/bar-video.webm" type="video/webm">
</video>
I changed the mime-type between video/mp4
and video/m4v
with no effect. I also tested adding the control
attribute and again, no effect.
This worked in all browsers tested including Safari 7 on Mavericks and Safari 8 on Yosemite. I simply renamed the same m4v file (the actual file, not just the HTML) to mp4 and reuploaded to our CDN:
<video preload="yes" autoplay loop width="100%" height="auto" poster="http://cdn.foo.com/bar.png">
<source src="//cdn.foo.com/bar-video.mp4" type="video/mp4">
<source src="//cdn.foo.com/bar-video.webm" type="video/webm">
</video>
Safari I think is fully expecting an actually-named MP4. No other combinations of file and mime-type worked for me. I think the other browsers opt for the WEBM file first, especially Chrome, even though I'm pretty sure the source list should select the first source that's technically supported.
This has not, however, fixed the video issue in iOS devices (iPad 3 "the new iPad" and iPhone 6 tested).
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
In android studio you can easily press:
android studio
, then press on app first.
Then, continue with step three as follows.You can also change the versionCode
of your app there.
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
// start to process your data / extract strings here...
}
Are you asking about this?
public class VariantDate {
public int day;
public int month;
public int year;
public VariantDate(int day) : this(day, 1) {}
public VariantDate(int day, int month) : this(day, month,1900){}
public VariantDate(int day, int month, int year){
this.day=day;
this.month=month;
this.year=year;
}
}
There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial
Message.js
module.exports = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg); // Hello World
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
Here's a pl/pgsql function that locates records where any column contains a specific value. It takes as arguments the value to search in text format, an array of table names to search into (defaults to all tables) and an array of schema names (defaults all schema names).
It returns a table structure with schema, name of table, name of column and pseudo-column ctid
(non-durable physical location of the row in the table, see System Columns)
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
JOIN information_schema.table_privileges p ON
(t.table_name=p.table_name AND t.table_schema=p.table_schema
AND p.privilege_type='SELECT')
JOIN information_schema.schemata s ON
(s.schema_name=t.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
AND t.table_type='BASE TABLE'
LOOP
FOR rowctid IN
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
)
LOOP
-- uncomment next line to get some progress report
-- RAISE NOTICE 'hit in %.%', schemaname, tablename;
RETURN NEXT;
END LOOP;
END LOOP;
END;
$$ language plpgsql;
See also the version on github based on the same principle but adding some speed and reporting improvements.
Examples of use in a test database:
select * from search_columns('foobar'); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | s3 | usename | (0,11) public | s2 | relname | (7,29) public | w | body | (0,2) (3 rows)
select * from search_columns('foobar','{w}'); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | w | body | (0,2) (1 row)
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | s2 | relname | (7,29) public | s3 | usename | (0,11) (2 rows)
select * from public.w where ctid='(0,2)'; title | body | tsv -------+--------+--------------------- toto | foobar | 'foobar':2 'toto':1
To test against a regular expression instead of strict equality, like grep, this part of the query:
SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L
may be changed to:
SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L
For case insensitive comparisons, you could write:
SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)
I haven't been able to get it to work without specifying a width but the following css worked
.wrapper {
background: #DDD;
padding: 10px;
display: inline-block;
height: 20px;
width: auto;
}
.contents {
background: #c3c;
overflow: hidden;
white-space: nowrap;
display: inline-block;
visibility: hidden;
width: 1px;
-webkit-transition: width 1s ease-in-out, visibility 1s linear;
-moz-transition: width 1s ease-in-out, visibility 1s linear;
-o-transition: width 1s ease-in-out, visibility 1s linear;
transition: width 1s ease-in-out, visibility 1s linear;
}
.wrapper:hover .contents {
width: 200px;
visibility: visible;
}
I'm not sure you will be able to get it working without setting a width on it.
Consider using the Comparator
interface described here which uses generics so you can avoid casting Object
to Student
.
As Eugene Retunsky said, your first part is the correct way to compare String
s. Also if the lastName
s are equal I think you meant to compare firstName
s, in which case just use compareTo
in the same way.
If you can't get this information from DNS (e.g. you aren't authorized) then one alternative is to use Wolfram Alpha.
stackexchange.com
)You will be able to see a list of sub-domains there. Although I suspect it does not show ALL sub-domains.
Try this:
colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ] # removing the first row.
However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.
The environment variable PYTHONPATH
is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this:
python -c "import sys; print(sys.path)"
Or if want the output in the UNIX directory list style (separated by :
) you can do this:
python -c "import sys; print(':'.join(x for x in sys.path if x))"
Which will output something like this:
/usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg:/usr/local/lib/ python2.7/dist-packages/stripogram-1.5-py2.7.egg:/home/qiime/lib:/home/debian:/us r/lib/python2.7:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib /python2.7/lib-old:/usr/lib/python2.7/lib- dynload:/usr/local/lib/python2.7/dist- packages:/usr/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages/PIL:/u sr/lib/python2.7/dist-packages/gst-0.10:/usr/lib/python2.7/dist-packages/gtk-2.0: /usr/lib/pymodules/python2.7
Use
.title{
display: inline-block;
height: 25px;
}
The only trick is browser support. Check if your list of supported browsers handles inline-block here.
save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.
update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.
I would do this slightly different by applying both the UNPIVOT
and the PIVOT
functions to get the final result. The unpivot takes the values from both the totalcount
and totalamount
columns and places them into one column with multiple rows. You can then pivot on those results.:
select chardate,
Australia_totalcount as [Australia # of Transactions],
Australia_totalamount as [Australia Total $ Amount],
Austria_totalcount as [Austria # of Transactions],
Austria_totalamount as [Austria Total $ Amount]
from
(
select
numericmonth,
chardate,
country +'_'+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (Australia_totalcount, Australia_totalamount,
Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth
See SQL Fiddle with Demo.
If you have an unknown number of country
names, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@colsName AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col)
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsName
= STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col)
+' as ['
+ country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT chardate, ' + @colsName + '
from
(
select
numericmonth,
chardate,
country +''_''+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (' + @cols + ')
) p
order by numericmonth'
execute(@query)
Both give the result:
| CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12 | 36 | 699.96 | 11 | 257.82 |
| Aug-12 | 44 | 1368.71 | 5 | 126.55 |
| Sep-12 | 52 | 1161.33 | 7 | 92.11 |
| Oct-12 | 50 | 1099.84 | 12 | 103.56 |
| Nov-12 | 38 | 1078.94 | 21 | 377.68 |
| Dec-12 | 63 | 1668.23 | 3 | 14.35 |
C:\....\wildfly-9.0.1.Final\standalone\deployments\YOUR-PROJEKT-FOLDER
Working with just one selector:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
I think the following snippet would help if you want to take a full screen(except for status bar),just replace AppDelegate with your app delegate name if necessary.
- (UIImage *)captureFullScreen {
AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
// for retina-display
UIGraphicsBeginImageContextWithOptions(_appDelegate.window.bounds.size, NO, [UIScreen mainScreen].scale);
[_appDelegate.window drawViewHierarchyInRect:_appDelegate.window.bounds afterScreenUpdates:NO];
} else {
// non-retina-display
UIGraphicsBeginImageContext(_bodyView.bounds.size);
[_appDelegate.window drawViewHierarchyInRect:_appDelegate.window.bounds afterScreenUpdates:NO];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
For users of GitHub, this worked for me:
git reset --hard <full_hash_of_commit_to_reset_to>
git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset
command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.
There isn't anything built-in, but you can easily create your own extension method to do it:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
Why not
getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
// ...
});
function getJSON(url,params,callback) {
return $.getJSON(url,params,callback)
.fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
console.dir(jqXMLHttpRequest);
alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
})
}
??
For details on the used .fail()
method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR
Since the jqXHR
is returned by the function, a chaining like
$.when(getJSON(...)).then(function() { ... });
is possible.
This is way late but for future reference to anyone who'd like to do this, you can use the following:
function require(file,callback){
var head=document.getElementsByTagName("head")[0];
var script=document.createElement('script');
script.src=file;
script.type='text/javascript';
//real browsers
script.onload=callback;
//Internet explorer
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
callback();
}
}
head.appendChild(script);
}
I did a short blog post on it some time ago http://crlog.info/2011/10/06/dynamically-requireinclude-a-javascript-file-into-a-page-and-be-notified-when-its-loaded/
Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.
The '::' is for static members.
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
Nice classes by Rich Tebb! I've been using DisplayAttribute and the code did not work for me. The only thing I've added is handling of DisplayAttribute. Brief search yielded that this attribute is new to MVC3 & .Net 4 and does almost the same thing plus more. Here's a modified version of the method:
public static string GetPropertyDisplayString<T>(Expression<Func<T, object>> propertyExpression)
{
var memberInfo = GetPropertyInformation(propertyExpression.Body);
if (memberInfo == null)
{
throw new ArgumentException(
"No property reference expression was found.",
"propertyExpression");
}
var displayAttribute = memberInfo.GetAttribute<DisplayAttribute>(false);
if (displayAttribute != null)
{
return displayAttribute.Name;
}
else
{
var displayNameAttribute = memberInfo.GetAttribute<DisplayNameAttribute>(false);
if (displayNameAttribute != null)
{
return displayNameAttribute.DisplayName;
}
else
{
return memberInfo.Name;
}
}
}
function cloneFunction(Func, ...args) {
function newThat(...args2) {
return new Func(...args2);
}
function clone() {
if (this instanceof clone) {
return newThat(...args);
}
return Func.apply(this, args);
}
for (const key in Func) {
if (Func.hasOwnProperty(key)) {
clone[key] = Func[key];
}
}
Object.defineProperty(clone, 'name', { value: Func.name, configurable: true })
return clone
};
function myFunction() {
console.log('Called Function')
}
myFunction.value = 'something';
const newFunction = cloneFunction(myFunction);
newFunction.another = 'somethingelse';
console.log('Equal? ', newFunction === myFunction);
console.log('Names: ', myFunction.name, newFunction.name);
console.log(myFunction);
console.log(newFunction);
console.log('InstanceOf? ', newFunction instanceof myFunction);
myFunction();
newFunction();
While I would never recommend using this, I thought it would be an interesting little challenge to come up with a more precise clone by taking some of the practices that seemed to be the best and fixing it up a bit. Heres the result of the logs:
Equal? false
Names: myFunction myFunction
{ [Function: myFunction] value: 'something' }
{ [Function: myFunction] value: 'something', another: 'somethingelse' }
InstanceOf? false
Called Function
Called Function
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.
if your text doesn't spill over two rows then you can do line-height: ;
in your CSS, the more line-height you give, the lower on the container it will hold.
In Swift
extension String {
var isPhoneNumber: Bool {
let PHONE_REGEX = "^[7-9][0-9]{9}$";
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: self)
return result
}
}
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.
The most Pythonic way is to use the len()
. Keep in mind that the '\' character in escape sequences is not counted and can be dangerous if not used correctly.
>>> len('foo')
3
>>> len('\foo')
3
>>> len('\xoo')
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape
as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.
var coolVar = '123-abc-itchy-knee';
var coolVarParts = coolVar.split('-'); // this is an array containing the items
var1=coolVarParts[0]; //this will retrieve 123
To access each item from the array just use the respective index(indices start at zero).
Try this:
private void NewNumber()
{
Random a = new Random(Guid.newGuid().GetHashCode());
MyNumber = a.Next(0, 10);
}
Some Explnations:
Guid
: base on here : Represents a globally unique identifier (GUID)
Guid.newGuid()
produces a unique identifier like "936DA01F-9ABD-4d9d-80C7-02AF85C822A8"
and it will be unique in all over the universe base on here
Hash code here produce a unique integer from our unique identifier
so Guid.newGuid().GetHashCode()
gives us a unique number and the random class will produce real random numbers throw this
Sample: https://rextester.com/ODOXS63244
generated ten random numbers with this approach with result of:
-1541116401
7
-1936409663
3
-804754459
8
1403945863
3
1287118327
1
2112146189
1
1461188435
9
-752742620
4
-175247185
4
1666734552
7
we got two 1
s next to each other, but the hash codes do not same.
You can use backticks (also known as accent graves) or $()
.
Like:
OUTPUT=$(x+2);
OUTPUT=`x+2`;
Both have the same effect. But OUTPUT=$(x+2) is more readable and the latest one.
You can also dynamically create a class by using DynamicObject.
public class DynamicClass : DynamicObject
{
private Dictionary<string, KeyValuePair<Type, object>> _fields;
public DynamicClass(List<Field> fields)
{
_fields = new Dictionary<string, KeyValuePair<Type, object>>();
fields.ForEach(x => _fields.Add(x.FieldName,
new KeyValuePair<Type, object>(x.FieldType, null)));
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_fields.ContainsKey(binder.Name))
{
var type = _fields[binder.Name].Key;
if (value.GetType() == type)
{
_fields[binder.Name] = new KeyValuePair<Type, object>(type, value);
return true;
}
else throw new Exception("Value " + value + " is not of type " + type.Name);
}
return false;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = _fields[binder.Name].Value;
return true;
}
}
I store all class fields in a dictionary _fields
together with their types and values. The both methods are to can get or set value to some of the properties. You must use the dynamic
keyword to create an instance of this class.
The usage with your example:
var fields = new List<Field>() {
new Field("EmployeeID", typeof(int)),
new Field("EmployeeName", typeof(string)),
new Field("Designation", typeof(string))
};
dynamic obj = new DynamicClass(fields);
//set
obj.EmployeeID = 123456;
obj.EmployeeName = "John";
obj.Designation = "Tech Lead";
obj.Age = 25; //Exception: DynamicClass does not contain a definition for 'Age'
obj.EmployeeName = 666; //Exception: Value 666 is not of type String
//get
Console.WriteLine(obj.EmployeeID); //123456
Console.WriteLine(obj.EmployeeName); //John
Console.WriteLine(obj.Designation); //Tech Lead
Edit: And here is how looks my class Field
:
public class Field
{
public Field(string name, Type type)
{
this.FieldName = name;
this.FieldType = type;
}
public string FieldName;
public Type FieldType;
}
You can use css with relative/absolute positioning if you want it responsive. Plus it can handle easily the multi-line.
https://jsfiddle.net/mgyp0jkk/
<div class="relative">
<canvas id="myChart"></canvas>
<div class="absolute-center text-center">
<p>Some text</p>
<p>Some text</p>
</div>
</div>
As mysql official documentation:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Online Documentation:
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
I hope it still not too late to share my solution. Before that, you can follow the tutorial as stated in Android Developer documentation. To achieve this, you need to use Cluster Manager with defaultRenderer
.
Create an object that implements ClusterItem
public class SampleJob implements ClusterItem {
private double latitude;
private double longitude;
//Create constructor, getter and setter here
@Override
public LatLng getPosition() {
return new LatLng(latitude, longitude);
}
Create a default renderer class. This is the class that do all the job (inflating custom marker/cluster with your own style). I am using Universal image loader to do the downloading and caching the image.
public class JobRenderer extends DefaultClusterRenderer< SampleJob > {
private final IconGenerator iconGenerator;
private final IconGenerator clusterIconGenerator;
private final ImageView imageView;
private final ImageView clusterImageView;
private final int markerWidth;
private final int markerHeight;
private final String TAG = "ClusterRenderer";
private DisplayImageOptions options;
public JobRenderer(Context context, GoogleMap map, ClusterManager<SampleJob> clusterManager) {
super(context, map, clusterManager);
// initialize cluster icon generator
clusterIconGenerator = new IconGenerator(context.getApplicationContext());
View clusterView = LayoutInflater.from(context).inflate(R.layout.multi_profile, null);
clusterIconGenerator.setContentView(clusterView);
clusterImageView = (ImageView) clusterView.findViewById(R.id.image);
// initialize cluster item icon generator
iconGenerator = new IconGenerator(context.getApplicationContext());
imageView = new ImageView(context.getApplicationContext());
markerWidth = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
markerHeight = (int) context.getResources().getDimension(R.dimen.custom_profile_image);
imageView.setLayoutParams(new ViewGroup.LayoutParams(markerWidth, markerHeight));
int padding = (int) context.getResources().getDimension(R.dimen.custom_profile_padding);
imageView.setPadding(padding, padding, padding, padding);
iconGenerator.setContentView(imageView);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.circle_icon_logo)
.showImageForEmptyUri(R.drawable.circle_icon_logo)
.showImageOnFail(R.drawable.circle_icon_logo)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
@Override
protected void onBeforeClusterItemRendered(SampleJob job, MarkerOptions markerOptions) {
ImageLoader.getInstance().displayImage(job.getJobImageURL(), imageView, options);
Bitmap icon = iconGenerator.makeIcon(job.getName());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon)).title(job.getName());
}
@Override
protected void onBeforeClusterRendered(Cluster<SampleJob> cluster, MarkerOptions markerOptions) {
Iterator<Job> iterator = cluster.getItems().iterator();
ImageLoader.getInstance().displayImage(iterator.next().getJobImageURL(), clusterImageView, options);
Bitmap icon = clusterIconGenerator.makeIcon(iterator.next().getName());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
}
@Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
return cluster.getSize() > 1;
}
Apply cluster manager in your activity/fragment class.
public class SampleActivity extends AppCompatActivity implements OnMapReadyCallback {
private ClusterManager<SampleJob> mClusterManager;
private GoogleMap mMap;
private ArrayList<SampleJob> jobs = new ArrayList<SampleJob>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setMapToolbarEnabled(true);
mClusterManager = new ClusterManager<SampleJob>(this, mMap);
mClusterManager.setRenderer(new JobRenderer(this, mMap, mClusterManager));
mMap.setOnCameraChangeListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
//Assume that we already have arraylist of jobs
for(final SampleJob job: jobs){
mClusterManager.addItem(job);
}
mClusterManager.cluster();
}
Result
it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.
the thing you have to do is to change your insertion query as below
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
Commands listed for use in normal mode (prefix with : for command mode).
Tested in Vim.
By line amount:
By line numbers:
Backwards range given, OK to swap (y/n)?
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
Use preventDefault()
to stop the event of submit button and in ajax call success submit the form using submit()
:
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
The value
attribute on submit
-type <input>
elements controls the text displayed.
<input type="submit" class="like" value="Like" />
just solved this issues with moving the project to a shorter path. It can happen if you exceed the Windows max path length
My two cents: as of 2019, 93% of browsers in use (and 100% of the last two version of every one of them) can handle SVG in <img>
elements:
Source: Can I Use
So we could say that there's no reason to use <object>
anymore.
However it's still has its pros:
When inspecting (e.g. with Chrome Dev Tools) you are presented with the whole SVG markup in case you wanted to tamper a bit with it and see live changes.
It provides a very robust fallback implementation in case your browser does not support SVGs (wait, but every one of them does!) which also works if the SVG isn't found. This was a key feature of XHTML2 spec, which is like betamax or HD-DVD
But there are also cons:
<object>
(tho it's perfectly safe to use it with <amp-img>
and use it inline too.<object>
tag might keep your PWA from being really offline capable.Try this, works!
Excel.Worksheet sheet = xlWorkSheet;
Excel.Series series1 = seriesCollection.NewSeries();
Excel.Range rng = (Excel.Range)xlWorkSheet.Range[xlWorkSheet.Cells[3, 13], xlWorkSheet.Cells[pp, 13]].Cells;
series1.Values = rng;
You might want to try this, could potentially be faster than doing two queries:
select <some columns>
from (
SELECT <some columns>,
row_number() over (order by date desc) as rn,
count(*) over () as total_count
FROM mytable
<maybe some joins here>
WHERE <various conditions>
) t
where rn = 1
or rn = total_count
ORDER BY date DESC
In XML, xmlns declares a Namespace. In fact, when you do:
<LinearLayout android:id>
</LinearLayout>
Instead of calling android:id
, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.
The namespace has pretty much the same uses as the package name in a Java application.
Here is an explanation.
Uniform Resource Identifier (URI)
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).
In our examples we will only use URLs.
Thank "Liko", just add a comment to his answer.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
Added single quotes ('
) to variable, otherwise it will give error message:
string jsFunc = "myFunc('" + MyBackValue + "')";
Without preg_replace()
$str = "This is a Text \n and so on \t Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, " ") !== false)
{
$str = str_replace(" ", " ", $str);
}
echo $str;
UPDATE: This solution stopped working as of Dec 2018.
I was looking for the same thing and it looks like most answers here are outdated due to Vimeo API v2 being deprecated.
my php 2¢:
$vidID = 12345 // Vimeo Video ID
$tnLink = json_decode(file_get_contents('https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/' . $vidID))->thumbnail_url;
with the above you will get the link to Vimeo default thumbnail image.
If you want to use different size image, you can add something like:
$tnLink = substr($tnLink, strrpos($tnLink, '/') + 1);
$tnLink = substr($tnLink, 0, strrpos($tnLink, '_')); // You now have the thumbnail ID, which is different from Video ID
// And you can use it with link to one of the sizes of crunched by Vimeo thumbnail image, for example:
$tnLink = 'https://i.vimeocdn.com/filter/overlay?src0=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F' . $tnLink . '_1280x720.jpg&src1=https%3A%2F%2Ff.vimeocdn.com%2Fimages_v6%2Fshare%2Fplay_icon_overlay.png';
It's working (mysql) :
SELECT TABLE_NAME , count(COLUMN_NAME)
FROM information_schema.columns
GROUP BY TABLE_NAME
I think that you can't control this. If the user had setup their browser to open links in a new window, you can't force this to open links in a new tab.
Depending on your content and space, you can use floats or inline display:
<table style="display: inline-block;">
<table style="float: left;">
Check it out here: http://jsfiddle.net/SM769/
Documentation
display
on MDN - https://developer.mozilla.org/en/CSS:displayfloat
on MDN - https://developer.mozilla.org/en/CSS/floatI am trying to write a class that is "both" a list
or a dict
. I want the programmer to be able to both "cast" this object to a list
(dropping the keys) or dict
(with the keys).
Looking at the way Python currently does the dict()
cast: It calls Mapping.update()
with the object that is passed. This is the code from the Python repo:
def update(self, other=(), /, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
The last subcase of the if statement, where it is iterating over other
is the one most people have in mind. However, as you can see, it is also possible to have a keys()
property. That, combined with a __getitem__()
should make it easy to have a subclass be properly casted to a dictionary:
class Wharrgarbl(object):
def __init__(self, a, b, c, sum, version='old'):
self.a = a
self.b = b
self.c = c
self.sum = 6
self.version = version
def __int__(self):
return self.sum + 9000
def __keys__(self):
return ["a", "b", "c"]
def __getitem__(self, key):
# have obj["a"] -> obj.a
return self.__getattribute__(key)
Then this will work:
>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
Add this to your css file
.jumbotron {
background-color:transparent !important;
}
It worked for me.
Use config something like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
and then you'll need three files:
The *-servlet.xml
files are used automatically and each creates an application context for that servlet.
From the Spring documentation, 13.2. The DispatcherServlet:
The framework will, on initialization of a
DispatcherServlet
, look for a file named [servlet-name]-servlet.xml in theWEB-INF
directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe
command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
JSON is not really meant for serializing arbitrary Python objects. It's great for serializing dict
objects, but the pickle
module is really what you should be using in general. Output from pickle
is not really human-readable, but it should unpickle just fine. If you insist on using JSON, you could check out the jsonpickle
module, which is an interesting hybrid approach.
Bootstrap3
CSS (gutter only, without margins around):
.row.row-gutter {
margin-bottom: -15px;
overflow: hidden;
}
.row.row-gutter > *[class^="col"] {
margin-bottom: 15px;
}
CSS (equal margins around, 15px/2):
.row.row-margins {
padding-top: 7px; /* or margin-top: 7px; */
padding-bottom: 7px; /* or margin-bottom: 7px; */
}
.row.row-margins > *[class^="col"] {
margin-top: 8px;
margin-bottom: 8px;
}
Usage:
<div class="row row-gutter">
<div class="col col-sm-9">first</div>
<div class="col col-sm-3">second</div>
<div class="col col-sm-12">third</div>
</div>
(with SASS or LESS 15px could be a variable from bootstrap)
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
I have same issue, i used simple solution
1)create sliding_out_right.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
2) create sliding_in_left.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
3) simply using fragment transaction setCustomeAnimations() with two custom xml and two default xml for animation as follows :-
fragmentTransaction.setCustomAnimations(R.anim.sliding_in_left, R.anim.sliding_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right );
This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.
$('#ff2').change(
function () {
var fileExtension = ['jpeg', 'jpg', 'pdf'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
return false; }
});
Syntax:
SELECT <Expression>[Arithmetic_Operator]<expression>...
FROM [Table_Name]
WHERE [expression];
The answer is:
gcc --version
Rather than searching on forums, for any possible option you can always type:
gcc --help
haha! :)
All these answers are superficially correct. However, the proper answer is
apropos disk # And pray your admin maintains the whatis database
because asking questions the answers of which lay at your fingertips in the manual wastes everybody's time.
Increase the Windows process limit to 3gb. (via boot.ini or Vista boot manager)
If you need it to have as a condition in an other event, I solved it this way:
$('.classname').hover(
function(){$(this).data('hover',true);},
function(){$(this).data('hover',false);}
);
Then in another event, you can easily use it:
if ($(this).data('hover')){
//...
}
(I see some using is(':hover')
to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)
You can do this:
var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();
With these extension methods:
public static class Extensions
{
public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
var grouped = source.GroupBy(selector);
var moreThan1 = grouped.Where(i => i.IsMultiple());
return moreThan1.SelectMany(i => i);
}
public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source)
{
return source.Duplicates(i => i);
}
public static bool IsMultiple<T>(this IEnumerable<T> source)
{
var enumerator = source.GetEnumerator();
return enumerator.MoveNext() && enumerator.MoveNext();
}
}
Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection.
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
Save file as .js
var maxVideos = 5;_x000D_
$(document).ready(function(){_x000D_
$.get(_x000D_
"https://www.googleapis.com/youtube/v3/videos",{_x000D_
part: 'snippet,contentDetails',_x000D_
id:'your_video_id',_x000D_
kind: 'youtube#videoListResponse',_x000D_
maxResults: maxVideos,_x000D_
regionCode: 'IN',_x000D_
key: 'Your_API_KEY'},_x000D_
function(data){_x000D_
var output;_x000D_
$.each(data.items, function(i, item){_x000D_
console.log(item);_x000D_
thumb = item.snippet.thumbnails.high.url;_x000D_
output = '<div id="img"><img src="' + thumb + '"></div>';_x000D_
$('#thumbnail').append(output);_x000D_
})_x000D_
_x000D_
}_x000D_
);_x000D_
});
_x000D_
.main{_x000D_
width:1000px;_x000D_
margin:auto;_x000D_
}_x000D_
#img{_x000D_
float:left;_x000D_
display:inline-block;_x000D_
margin:5px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Thumbnails</title>_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="main">_x000D_
<ul id="thumbnail"> </ul>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.
If you use maven, you can add this in pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<argLine>-Dspring.profiles.active=test</argLine>
</configuration>
</plugin>
...
Then, maven should run your integration tests (*IT.java) using this arugument, and also IntelliJ will start with this profile activated - so you can then specify all properties inside
application-test.yml
and you should not need "-default" properties.
Thanks Andy W
I found that the mid() did not quite work as I expected and I modified as follows:
def mid(s, offset, amount):
return s[offset-1:offset+amount-1]
I performed the following test:
print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))
Which resulted in:
[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23
Which was what I was expecting. The original mid() code produces this:
[1]23 2
1[2]3 3
12[3]
[12]3 23
1[23] 3
But the left() and right() functions work fine. Thank you.
Permgen space is always known as method area.When the classloader subsystem will load the the class file(byte code) to the method area(permGen). It contains all the class metadata eg: Fully qualified name of your class, Fully qualified name of the immediate parent class, variable info, constructor info, constant pool infor etc.
If it's too late at night and your table is already innoDB and you still don't see the link, maybe is due to the fact that now it's placed above the structure of the table, like in the picture is shown
I would rather not use any outside frameworks like log4j.net.
Why? Log4net would probably address most of your requirements. For example check this class: RollingFileAppender.
Log4net is well documented and there are thousand of resources and use cases on the web.
If reading the whole file is acceptable then use a deque.
from collections import deque
deque(f, maxlen=n)
Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.
import itertools
def maxque(items, size):
items = iter(items)
q = deque(itertools.islice(items, size))
for item in items:
del q[0]
q.append(item)
return q
If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.
def tail(f, n):
assert n >= 0
pos, lines = n+1, []
while len(lines) <= n:
try:
f.seek(-pos, 2)
except IOError:
f.seek(0)
break
finally:
lines = list(f)
pos *= 2
return lines[-n:]
Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)
edit: relevant paragraph follows:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:
'-' + vendor identifier + '-' + meaningful name '_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.
Other known examples:
-moz-box-sizing -moz-border-radius -wap-accesskey
An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.
Authors should avoid vendor-specific extensions
Some users have already given their answer and explained it very well.
I would like to add few more things related to thread.
How to work with functor and thread. Please refer to below example.
The thread will make its own copy of the object while passing the object.
#include<thread>
#include<Windows.h>
#include<iostream>
using namespace std;
class CB
{
public:
CB()
{
cout << "this=" << this << endl;
}
void operator()();
};
void CB::operator()()
{
cout << "this=" << this << endl;
for (int i = 0; i < 5; i++)
{
cout << "CB()=" << i << endl;
Sleep(1000);
}
}
void main()
{
CB obj; // please note the address of obj.
thread t(obj); // here obj will be passed by value
//i.e. thread will make it own local copy of it.
// we can confirm it by matching the address of
//object printed in the constructor
// and address of the obj printed in the function
t.join();
}
Another way of achieving the same thing is like:
void main()
{
thread t((CB()));
t.join();
}
But if you want to pass the object by reference then use the below syntax:
void main()
{
CB obj;
//thread t(obj);
thread t(std::ref(obj));
t.join();
}
One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).
What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then()
on the promise, and the result will be there when the promise has been resolved.
Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/
You can use SQLiteOpenHelper's onUpgrade
method. In the onUpgrade method, you get the oldVersion as one of the parameters.
In the onUpgrade
use a switch
and in each of the case
s use the version number to keep track of the current version of database.
It's best that you loop over from oldVersion
to newVersion
, incrementing version
by 1 at a time and then upgrade the database step by step. This is very helpful when someone with database version 1 upgrades the app after a long time, to a version using database version 7 and the app starts crashing because of certain incompatible changes.
Then the updates in the database will be done step-wise, covering all possible cases, i.e. incorporating the changes in the database done for each new version and thereby preventing your application from crashing.
For example:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " + "name_of_column_to_be_added" + " INTEGER";
db.execSQL(sql);
break;
case 2:
String sql = "SOME_QUERY";
db.execSQL(sql);
break;
}
}
I found a way to solve this problem:
If this does not work,
If that did not work and "World Wide Web Publishing Service" was not available,
If you have ubuntu-mate, you can install latest go by:
umake go
I have a script to download and install the last go from official website
# Change these varialbe to where ever you feel comfortable
DOWNLOAD_DIR=${HOME}/Downloads/GoLang
INSTALL_DIR=${HOME}/App
function install {
mkdir -p ${DOWNLOAD_DIR}
cd ${DOWNLOAD_DIR}
echo "Fetching latest Go version..."
typeset VER=`curl -s https://golang.org/dl/ | grep -m 1 -o 'go\([0-9]\)\+\(\.[0-9]\)\+'`
if uname -m | grep 64 > /dev/null; then
typeset ARCH=amd64
else
typeset ARCH=386
fi
typeset FILE=$VER.linux-$ARCH
if [[ ! -e ${FILE}.tar.gz ]]; then
echo "Downloading '$FILE' ..."
wget https://storage.googleapis.com/golang/${FILE}.tar.gz
fi
echo "Installing ${FILE} ..."
tar zxfC ${FILE}.tar.gz ${INSTALL_DIR}
echo "Go is installed"
}
install
Setup your GOROOT, GOPATH and PATH:
export GOROOT=${INSTALL_DIR}/go
export GOPATH=<your go path>
export PATH=${PATH}:${GOROOT}/bin:${GOPATH}/bin
In VS2017, have tried all the above solution but nothing works. We are using Azure devops for versioning.
Select the project which driving you nuts for a long time
Right click the branch or solution > Advanced > get specific version
select unique is not valid syntax for what you are trying to do
you want to use either select distinct or select distinctrow
And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.
the below query by itself will only provide distinct values
select col from table1
union
select col from table2
if you did want duplicates you would have to do
select col from table1
union all
select col from table2
TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.
Step 1
To Download TCPDF Click Here.
Step 2
Unzip the above download inside application/libraries/tcpdf.
Step 3
Create a new file inside application/libraries/Pdf.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */
Step 4
Create Controller file inside application/controllers/pdfexample.php.
<?php
class pdfexample extends CI_Controller{
function __construct()
{ parent::__construct(); } function index() {
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->Output('pdfexample.pdf', 'I'); }
}
?>
It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php
JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.
Level 1 annotations: @Entity
, @Id
, @OneToOne
, @OneToMany
, @ManyToOne
, @ManyToMany
.
You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.
Level 2 annotations: @Table
, @Column
, @JoinColumn
, ...
Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.
In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.
To answer the questions: the @OneToMany
/mappedBy
is nicest because it only uses the annotations from the entity domain. The @oneToMany
/@JoinColumn
is also fine but it uses an implementation annotation where this is not strictly necessary.
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
Or this:
Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
Order1:=xlAscending, Header:=xlYes
So after carping about this along with many others, I came across a note posted by Dorian B in this article that solved the specific problem I was having where I would develop modules and classes for use with a web service, but I also want to be able to test them as I'm coding, using the debugger facilities in PyCharm. To run tests in a self-contained class, I would include the following at the end of my class file:
if __name__ == '__main__':
# run test code here...
but if I wanted to import other classes or modules in the same folder, I would then have to change all my import statements from relative notation to local references (i.e. remove the dot (.)) But after reading Dorian's suggestion, I tried his 'one-liner' and it worked! I can now test in PyCharm and leave my test code in place when I use the class in another class under test, or when I use it in my web service!
# import any site-lib modules first, then...
import sys
parent_module = sys.modules['.'.join(__name__.split('.')[:-1]) or '__main__']
if __name__ == '__main__' or parent_module.__name__ == '__main__':
from codex import Codex # these are in same folder as module under test!
from dblogger import DbLogger
else:
from .codex import Codex
from .dblogger import DbLogger
The if statement checks to see if we're running this module as main or if it's being used in another module that's being tested as main. Perhaps this is obvious, but I offer this note here in case anyone else frustrated by the relative import issues above can make use of it.
I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)
I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.
Hope that helps.
I had a similar issue in Mac where svn was picking mac login as user name and I was getting error as
svn: E170013: Unable to connect to a repository at URL 'https://repo:8443/svn/proj/trunk'
svn: E175013: Access to '/svn/proj/trunk' forbidden
I used the --username
along with svn command to pass the correct username which helped me.
Alternatively, you can delete ~/.subversion/auth
file, after which svn will prompt you for username.
The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.
Here are simple regex to understand (verified, and no preceding 0)
Between 0 to 100 (Try it here):
^(0|[1-9][0-9]?|100)$
Between 1 to 100 (Try it here):
^([1-9][0-9]?|100)$
For anyone trying to format the current date for use in an HTTP header use the "r" format (short for RFC1123) but beware the caveat...
PS C:\Users\Me> (get-date).toString("r")
Thu, 16 May 2019 09:20:13 GMT
PS C:\Users\Me> get-date -format r
Thu, 16 May 2019 09:21:01 GMT
PS C:\Users\Me> (get-date).ToUniversalTime().toString("r")
Thu, 16 May 2019 16:21:37 GMT
I.e. Don't forget to use "ToUniversalTime()"
In addition, strip has some variations:
Remove spaces in the BEGINNING and END of a string:
sentence= sentence.strip()
Remove spaces in the BEGINNING of a string:
sentence = sentence.lstrip()
Remove spaces in the END of a string:
sentence= sentence.rstrip()
All three string functions strip
lstrip
, and rstrip
can take parameters of the string to strip, with the default being all white space. This can be helpful when you are working with something particular, for example, you could remove only spaces but not newlines:
" 1. Step 1\n".strip(" ")
Or you could remove extra commas when reading in a string list:
"1,2,3,".strip(",")
As per my analysis and search on the internet also, I could not found a way to centre the image vertically centred using <div>
it was possible only using <table>
because table provides the following property:
valign="middle"
I happen all the time when you install a new plugin. You just have to delete maintenance.flag file in your root directory
For mysql8
and python 3.7
on windows, I find previous solutions seems not work for me.
Here is what worked for me:
pip install wheel
pip install mysqlclient-1.4.2-cp37-cp37m-win_amd64.whl
python -m pip install mysql-connector-python
python -m pip install SQLAlchemy
Reference: https://mysql.wisborg.dk/2019/03/03/using-sqlalchemy-with-mysql-8/
Try this:
<script>
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
</script>
more info here MDN.
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
You have to load jdbc driver
. Consider below Code.
try {
Class.forName("com.mysql.jdbc.Driver");
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/aavikme";
String user = "root";
String password = "aa";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/aavikme";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "aa");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use parentheses to group the individual branches:
IF EXIST D:\RPS_BACKUP\backups_to_zip\ (goto zipexist) else goto zipexistcontinue
In your case the parser won't ever see the else
belonging to the if
because goto
will happily accept everything up to the end of the command. You can see a similar issue when using echo
instead of goto
.
Also using parentheses will allow you to use the statements directly without having to jump around (although I wasn't able to rewrite your code to actually use structured programming techniques; maybe it's too early or it doesn't lend itself well to block structures as the code is right now).
SWIFT 5, Xcode 11.0
Pass your (date in string) in "dateString" and in "dateFormat" pass format you want. To choose format, use NDateFormatter website.
func getDateFrom(dateString: String, dateFormat: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = Locale(identifier: "en_US")
guard let date = dateFormatter.date(from: dateString) else {return nil}
return date
}
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
When you first open a web/app project, do a Ctrl-F5, which is the shortcut for starting the application without debugging. Then when you subsequently hit F5 and launch the debugger, it will use that instance of IE. Then stop and start the debugging in Visual Studio instead of closing IE.
It works on my machines. I'm using the built in dev web server. Don't know if that makes a difference.
Firefox will also stay open so you can debug in either or both at the same time.
Or is ||
And is &&
Update for changed question:
You need to specify what you are comparing against in each logical section of the if statement.
if (title == "User greeting" || title == "User name")
{
// do stuff
}
Another case which happened to me, is I did a CURL to some of my pages, and got internal server error and nothing was in the apache logs, even when I enabled all error reporting.
My problem was that in the CURL I set
curl_setopt($CR, CURLOPT_FAILONERROR, true);
Which then didn't show me my error, though there was one, this happened because the error was on a framework level and not a PHP one, so it didn't appear in the logs.
Have a try on the listings
package. Here is an example of what I used some time ago to have a coloured Java listing:
\usepackage{listings}
[...]
\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}
[...]
\begin{lstlisting}
public void here() {
goes().the().code()
}
[...]
\end{lstlisting}
You may want to customize that. There are several references of the listings package. Just google them.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
With the caveat of it not working in IE and some older mobile browsers, a simple object-fit: cover;
is often the best option.
.cropper {
position: relative;
width: 100px;
height: 100px;
overflow: hidden;
}
.cropper img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
Without the object-fit: cover
support, the image will be stretched oddly to fit the box so, if support for IE is needed, I'd recommend using one of the other answers' approach with -100%
top, left, right and bottom values as a fallback.
You might also consider the smart_open
module, which supports iterators:
from smart_open import smart_open
# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
print(line.decode('utf8'))
and context managers:
with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
for line in s3_source:
print(line.decode('utf8'))
s3_source.seek(0) # seek to the beginning
b1000 = s3_source.read(1000) # read 1000 bytes
Find smart_open
at https://pypi.org/project/smart_open/
I don't often develop in asp.net, however when it comes to loggers I think a lot of best practices are universal. Here are some of my random thoughts on logging that I have learned over the years:
</xxx>
tag, your log is broken.-- Invoking Class: com.foocorp.foopackage.FooClass:9021 SELECT * FROM foo;
This is my logging statement - Repeated 100 times
Also see this question of mine.
If you are using Gradle then you can find the line that applies the java plugin:
apply plugin: 'java'
Then set the encoding for the compile task to be UTF-8:
compileJava {options.encoding = "UTF-8"}
If you have unit tests, then you probably want to compile those with UTF-8 too:
compileTestJava {options.encoding = "UTF-8"}
This means that the overall gradle code would look something like this:
apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}
If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL
for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual
from the backend.
Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...
You have a file myFile.txt you want to commit.
The right procedure is :
svn up
svn commit myFile.txt -m "Insert here a commit message!!!"
Hope this will help someone.
It will depend on the implementation, but from the Sun Java 6 source code:
int newCapacity = (oldCapacity * 3)/2 + 1;
That's in the ensureCapacity
method. Other JDK implementations may vary.
Complete Code to send Email Using nodemailer Module
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "[email protected]",
pass: "gmail_password"
}
});
var mail = {
from: "Yashwant Chavan <[email protected]>",
to: "[email protected]",
subject: "Send Email Using Node.js",
text: "Node.js New world for me",
html: "<b>Node.js New world for me</b>"
}
smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
smtpTransport.close();
});
Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.
Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.
If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
For servers with PHP 5.6
sudo apt-get install zip unzip php5.6-zip
Building on @Michael Kropat's answer I added a parameter to prepend the new path to the existing PATH
variable and a check to avoid the addition of a non-existing path:
function Add-EnvPath {
param(
[Parameter(Mandatory=$true)]
[string] $Path,
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container = 'Session',
[Parameter(Mandatory=$False)]
[Switch] $Prepend
)
if (Test-Path -path "$Path") {
if ($Container -ne 'Session') {
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
$persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
if ($persistedPaths -notcontains $Path) {
if ($Prepend) {
$persistedPaths = ,$Path + $persistedPaths | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
else {
$persistedPaths = $persistedPaths + $Path | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
}
}
$envPaths = $env:Path -split ';'
if ($envPaths -notcontains $Path) {
if ($Prepend) {
$envPaths = ,$Path + $envPaths | where { $_ }
$env:Path = $envPaths -join ';'
}
else {
$envPaths = $envPaths + $Path | where { $_ }
$env:Path = $envPaths -join ';'
}
}
}
}
I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.
"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206
"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206
"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156
you have following errors which in turn is causing you that exception, let me explain it
this is your existing code:
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
System.out.print("Enter an integer: ");
usrInput= sc.nextInt();
}
in the above code if(!scan.hasNextInt())
will become true
only when user input contains both characters as well as integers like your input adfd 123
.
but you are trying to read only integers inside the if condition using usrInput= sc.nextInt();
. Which is incorrect,that's what is throwing Exception in thread "main" java.util.InputMismatchException
.
so correct code should be
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
System.out.print("Enter an integer: ");
sc.next();
continue;
}
in the above code sc.next()
will help to read new input from user and continue
will help in executing same if condition(i.e if(!scan.hasNextInt())
) again.
Please use code in my first answer to build your complete logic.let me know if you need any explanation on it.
Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.
# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD
$ cat .git/HEAD
ref: refs/heads/master
$ ls .git/refs/heads/
$ cat .git/packed-refs
# pack-refs with: peeled
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master
$ git fsck --full
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc
# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects
# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack
# Check reflogs...
$ git reflog
# ...then clean
$ git reflog expire --expire=0 --all
# Now garbage collect again
$ git gc
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
I looked and found a cross browser way:
function myFunction(){_x000D_
if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
var w = window.innerWidth;_x000D_
var h = window.innerHeight;_x000D_
} else { _x000D_
var w = document.documentElement.clientWidth;_x000D_
var h = document.documentElement.clientHeight;_x000D_
}_x000D_
var txt = "Page size: width=" + w + ", height=" + h;_x000D_
document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body onresize="myFunction()" onload="myFunction()">_x000D_
<p>_x000D_
Try to resize the page._x000D_
</p>_x000D_
<p id="demo">_x000D_
_x000D_
</p>_x000D_
</body>_x000D_
</html>
_x000D_
This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:
declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
begin
set @str = @str + '|' + char(@i)
set @i = @i + 1
end
select col1
from YourTable
where col1 like '%[^' + @str + ']%' escape '|'
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
If using function onclick DIV and then want to disable click it again you can use this :
for (var i=0;i<document.getElementsByClassName('ads').length;i++){
document.getElementsByClassName('ads')[i].onclick = false;
}
Example :
HTML
<div id='mybutton'>Click Me</div>
Javascript
document.getElementById('mybutton').onclick = function () {
alert('You clicked');
this.onclick = false;
}
Test the value against NaN:
<xsl:if test="string(number(myNode)) != 'NaN'">
<!-- myNode is a number -->
</xsl:if>
This is a shorter version (thanks @Alejandro):
<xsl:if test="number(myNode) = myNode">
<!-- myNode is a number -->
</xsl:if>
I use following templates for Android development:
Verbose (Logv)
Log.v(TAG, ${word_selection}${});${cursor}
Debug (Logd)
Log.d(TAG, ${word_selection}${});${cursor}
Info (Logi)
Log.i(TAG, ${word_selection}${});${cursor}
Warn (Logw)
Log.w(TAG, ${word_selection}${});${cursor}
Error (Loge)
Log.e(TAG, ${word_selection}${});${cursor}
Assert (Loga)
Log.a(TAG, ${word_selection}${});${cursor}
TAG is a Constant I define in every activity.
You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:
<input type="text" onChange={e => this.setState({ text: e.target.value })}/>
Anyone using Jenkins, might get it useful
You need to define a global variable name ANDROID_HOME
with the value of the path to android sdk.
For mac, it is /Users/YOUR_USER_NAME/Library/Android/sdk
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate
as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.
def get_class(fully_qualified_path, module_name, class_name, *instantiation):
"""
Returns an instantiated class for the given string descriptors
:param fully_qualified_path: The path to the module eg("Utilities.Printer")
:param module_name: The module name eg("Printer")
:param class_name: The class name eg("ScreenPrinter")
:param instantiation: Any fields required to instantiate the class
:return: An instance of the class
"""
p = __import__(fully_qualified_path)
m = getattr(p, module_name)
c = getattr(m, class_name)
instance = c(*instantiation)
return instance
I was able to copy a file from my host to the container within a dockerfile as such:
The contents of the docker file as follows,to copy a file from local host to the root of the container: FROM ubuntu:16.04
COPY test.txt /
You should see the file.
With Python 3.6, sometimes I still run into this problem. For example, when getting response from a REST API and loading the response text to JSON, I still get the unicode strings. Found a simple solution using json.dumps().
response_message = json.loads(json.dumps(response.text))
print(response_message)
You get all tables containing the column product using this statment:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('Product')
AND TABLE_SCHEMA='YourDatabase';
Then you have to run a cursor on these tables so you select eachtime:
Select * from OneTable where product like '%XYZ%'
The results should be entered into a 3rd table or view, take a look here.
Notice: This can work only if the structure of all table is similar, otherwise aou will have to see which columns are united for all these tables and create your result table / View to contain only these columns.
Named export
In TS you can export with the export
keyword. It then can be imported via import {name} from "./mydir";
. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:
// foo.js file
export class foo{}
export class bar{}
// main.js file in same dir
import {foo, bar} from "./foo";
The following alternative syntax is also valid:
// foo.js file
function foo() {};
function bar() {};
export {foo, bar};
// main.js file in same dir
import {foo, bar} from './foo'
Default export
We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.
// foo.js file
export default class foo{}
// main.js file in same directory
import abc from "./foo";
It's just JavaScript
Modules and their associated keyword like import
, export
, and export default
are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.
This question came first on Google although an old one so I'm posting the working answer I found, which can be of use to someone else.
This requires 3 divs including the fixed div.
HTML
<div class="wrapper">
<div class="parent">
<div class="child"></div>
</div>
</div>
CSS
.wrapper { position:relative; width:1280px; }
.parent { position:absolute; }
.child { position:fixed; width:960px; }
Using @angular/forms
when you use a <form>
tag it automatically creates a FormGroup
.
For every contained ngModel
tagged <input>
it will create a FormControl
and add it into the FormGroup
created above; this FormControl
will be named into the FormGroup
using attribute name
.
Example:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
Said this, the answer to your question follows.
When you mark it as standalone: true
this will not happen (it will not be added to the FormGroup
).
Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474
This works for me
select * from stuff
update stuff
set TYPE1 = TYPE2
where TYPE1 is null;
update stuff
set TYPE1 = TYPE2
where TYPE1 ='Blank';
select * from stuff
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo
will be closed over by each function returned by make_foo
. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
I needed to pass both: a file and an integer. I did it this way:
needed to pass a file to upload: did it as per Sumit's answer.
Request type : POST
Body -> form-data
under the heading KEY, entered the name of the variable ('file' in my backend code).
in the backend:
file = request.files['file']
Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.
2. needed to pass an integer:
went to:
Params
entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE
in the backend:
id = request.args.get('id')
Worked!
See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.
But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)
Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD
The newest version of the Anaconda installer for Windows will also install a windows launcher for "Anaconda Prompt" and "Anaconda Powershell Prompt". If you use one of those instead of the regular windows cmd shell, the conda
command, python etc. should be available by default in this shell.
To get the ASCII code of a character, you can use the ord()
function.
Here is an example code:
value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)
Output:
Your value here: qwerty
[113, 119, 101, 114, 116, 121]
compiler will make a capture for each wildcard (e.g., question mark in List) when it makes up a function like:
foo(List<?> list) {
list.put(list.get()) // ERROR: capture and Object are not identical type.
}
However a generic type like V would be ok and making it a generic method:
<V>void foo(List<V> list) {
list.put(list.get())
}
Call Application.DoEvents()
after setting the label, but you should do all the work in a separate thread instead, so the user may close the window.
If you're only looking for a webkit version this is nifty: http://s3.amazonaws.com/37assets/svn/463-single_spinner.html from http://37signals.com/svn/posts/2577-loading-spinner-animation-using-css-and-webkit
Try ng-inspector. Download the add-on for Firefox from the website http://ng-inspector.org/. It is not available on the Firefox add on menu.
http://ng-inspector.org/ - website
http://ng-inspector.org/ng-inspector.xpi - Firefox Add-on?
innerHTML
sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.
For your case you want to set the value of an input element. So you should use the value
attribute.
Change innerHTML
to value
document.getElementById('add').value = sum;
Everyone knows (hopefully) its bad to terminate thread. The problem is when you don't own a piece of code you're calling. If this code is running in some do/while infinite loop , itself calling some native functions, etc. you're basically stuck. When this happens in your own code termination, stop or Dispose call, it's kinda ok to start shooting the bad guys (so you don't become a bad guy yourself).
So, for what it's worth, I've written those two blocking functions that use their own native thread, not a thread from the pool or some thread created by the CLR. They will stop the thread if a timeout occurs:
// returns true if the call went to completion successfully, false otherwise
public static bool RunWithAbort(this Action action, int milliseconds) => RunWithAbort(action, new TimeSpan(0, 0, 0, 0, milliseconds));
public static bool RunWithAbort(this Action action, TimeSpan delay)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var source = new CancellationTokenSource(delay);
var success = false;
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
action();
success = true;
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return success;
}
// returns what's the function should return if the call went to completion successfully, default(T) otherwise
public static T RunWithAbort<T>(this Func<T> func, int milliseconds) => RunWithAbort(func, new TimeSpan(0, 0, 0, 0, milliseconds));
public static T RunWithAbort<T>(this Func<T> func, TimeSpan delay)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
var source = new CancellationTokenSource(delay);
var item = default(T);
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
item = func();
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return item;
}
[DllImport("kernel32")]
private static extern bool TerminateThread(IntPtr hThread, int dwExitCode);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(IntPtr lpThreadAttributes, IntPtr dwStackSize, Delegate lpStartAddress, IntPtr lpParameter, int dwCreationFlags, out int lpThreadId);
[DllImport("kernel32")]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32")]
private static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);
Here I like to use https://www.netresize.net/index.php?c=3a&id=11#buyopt. But it is paid version.
You also can get their source codes if you buy 1 Site License (Unlimited Developers).
How ever I am finding the nuget package solution.
If you have not committed:
git stash
git checkout some-branch
git stash pop
If you have committed and have not changed anything since:
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
If you have committed and then done extra work:
git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop
I'd start by completely filling in the Notification
. Here is a sample project demonstrating the use of startForeground()
.
I had a similar issue with Datagrip and none of these solutions worked.
Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
I heard a good description (parable) which illustrates ports as different delivery points for a large building, e.g. Post office for letters and small parcels, Goods In for large deliveries / pallets, Doors for people.
You should change/add in your PostController: (and change PostsController to PostController)
public function create()
{
$categories = Category::all();
return view('create',compact('categories'));
}
public function store(Request $request)
{
$post = new Posts;
$post->title = $request->get('title'); // CHANGE THIS
$post->body = $request->get('body'); // CHANGE THIS
$post->save(); // ADD THIS
$post->categories()->attach($request->get('categories_id')); // CHANGE THIS
return redirect()->route('posts.index'); // PS ON THIS ONE
}
PS: using route() means you have named your route as such
Route::get('example', 'ExampleController@getExample')->name('getExample');
UPDATE
The comments above are also right, change your 'Posts' Model to 'Post'
this will work,too
$("#CompanyList").autocomplete({
source : yourSource,
change : yourChangeHandler
})
// deprecated
//$("#CompanyList").data("autocomplete")._trigger("change")
// use this now
$("#CompanyList").data("ui-autocomplete")._trigger("change")
There is also this syntax, e.g. if you want to delete the 2nd element :
array=("${array[@]:0:1}" "${array[@]:2}")
which is in fact the concatenation of 2 tabs. The first from the index 0 to the index 1 (exclusive) and the 2nd from the index 2 to the end.
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
SELECT t1.* FROM table t1 JOIN table t2 ON t1.Id=t2.Id WHERE t1.C4=t2.C4;
Giving Accurate Result for me.
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
As of now:
To add the bot to your channel:
* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.
** the bot doesn't need to be in your contact list.
Log in :URL = "localhost:8080/" Enter username and pass word Click Manager App Scroll Down and find "WAR file to deploy" Chose file and click deploy
Done
Go to Webapp folder of you Apache tomcat you will see a folder name matching with your war file name.
Type link in your url address bar:: localhost:8080/HelloWorld/HelloWorld.html and press enter
Done
This is very possible. I mocked up 3 pages which should give you a proof of concept:
.aspx page:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each s As String In Request.Form.AllKeys
Response.Write(s & ": " & Request.Form(s) & "<br />")
Next
End Sub
Separate HTML page:
<form action="http://localhost/MyTestApp/Default.aspx" method="post">
<input name="TextBox1" type="text" value="" id="TextBox1" />
<input name="TextBox2" type="password" id="TextBox2" />
<input type="submit" name="Button1" value="Button" id="Button1" />
</form>
...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.