This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
The 'c' means it's a character special file.
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
We can alter multiple columns in a single query like this:
ALTER TABLE `tblcommodityOHLC`
CHANGE COLUMN `updated_on` `updated_on` DATETIME NULL DEFAULT NULL AFTER `updated_by`,
CHANGE COLUMN `delivery_datetime` `delivery_datetime` DATETIME NULL DEFAULT CURRENT_TIMESTAMP AFTER `delivery_status`;
Just give the queries as comma separated.
I like Hrishikesh's answer, to which I only have this to add...because we saw a comma-delimited string coming across when multiple proxies along the way were used, we found it necessary to add an explode and grab the final value, like this:
$IParray=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
return end($IParray);
the array_filter is in there to remove empty entries.
Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :
select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';
You can add any condition or ignore based on your requirement.
The output of the query is resulted as :
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| 5 | ssss | localhost:41060 | somedb | Sleep | 3 | | NULL |
| 58169 | root | localhost | somedb | Query | 0 | executing | select * from sometable where tblColumnName = 'someName' |
A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.
A list doesn't use a hash for indexing, so it isn't restricted to hashable items.
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
Can you provide an example, because put should work fine as well?
Documentation -
The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url
) -
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "name=John&location=Boston",
success: function(data) {
alert('Load was performed.');
}
});
Demo tested from jQuery 1.3.2 onwards on Chrome.
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
I solved it doing
run devenv /resetuserdata
in this path:
[x64] C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
I assume that in x86 it works in this path:
[x86] C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE
Try this:
<img v-bind:src="'/media/avatars/' + joke.avatar" />
Don't forget single quote around your path string. also in your data check you have correctly defined image variable.
joke: {
avatar: 'image.jpg'
}
A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output
It became a popular question and I got a notification. I am sorry, I forgot to answer before which I should have done. I solved it long back.
net use \\10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes
Run it in a batch file and you should get what you are looking for.
Very Simple
private void button1_Click(object sender, EventArgs e)
{
ListViewItem item = new ListViewItem();
item.SubItems.Add(textBox2.Text);
item.SubItems.Add(textBox3.Text);
item.SubItems.Add(textBox4.Text);
listView1.Items.Add(item);
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}
You can also Do this stuff...
ListViewItem item = new ListViewItem();
item.SubItems.Add("Santosh");
item.SubItems.Add("26");
item.SubItems.Add("India");
I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:
UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')
You have Full data + Transaction log backups, right? You can restore to another Database from backups and then sync the deleted rows back. Lots of work though...
(Have you looked at Redgate's SQL Log Rescue? Update: it's SQL Server 2000 only)
There is Log Explorer
I got the color range to be asymmetric simply by changing the symkey argument to FALSE
symm=F,symkey=F,symbreaks=T, scale="none"
Solved the color issue with colorRampPalette with the breaks argument to specify the range of each color, e.g.
colors = c(seq(-3,-2,length=100),seq(-2,0.5,length=100),seq(0.5,6,length=100))
my_palette <- colorRampPalette(c("red", "black", "green"))(n = 299)
Altogether
heatmap.2(as.matrix(SeqCountTable), col=my_palette,
breaks=colors, density.info="none", trace="none",
dendrogram=c("row"), symm=F,symkey=F,symbreaks=T, scale="none")
You probably want to make a range query, for example, all items created after a given date:
db.gpsdatas.find({"createdAt" : { $gte : new ISODate("2012-01-12T20:15:31Z") }});
I'm using $gte
(greater than or equals), because this is often used for date-only queries, where the time component is 00:00:00.
If you really want to find a date that equals another date, the syntax would be
db.gpsdatas.find({"createdAt" : new ISODate("2012-01-12T20:15:31Z") });
When you run
install.packages("whatever")
you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:
.libPaths()
If libPaths shows 2 locations, then paste into second one. Load library:
library(whatever)
Fixed.
You can do like this.
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("Your URL goes here");
If you want your own custom Error Logging you can easily write your own code. I'll give you a snippet from one of my projects.
public void SaveLogFile(object method, Exception exception)
{
string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
try
{
//Opens a new file stream which allows asynchronous reading and writing
using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
{
//Writes the method name with the exception and writes the exception underneath
sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
sw.WriteLine(exception.ToString()); sw.WriteLine("");
}
}
catch (IOException)
{
if (!File.Exists(location + @"log.txt"))
{
File.Create(location + @"log.txt");
}
}
}
Then to actually write to the error log just write (q
being the caught exception)
SaveLogFile(MethodBase.GetCurrentMethod(), `q`);
Trying to depict with venn diagrams for better understanding..
Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.
Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.
Inner join : It selects rows that have matching values in both relations.
I've recently written a CSV parser for .NET that I'm claiming is currently the fastest available as a nuget package: Sylvan.Data.Csv.
Using this library to load a DataTable
is extremely easy.
using var dr = CsvDataReader.Create("data.csv");
var dt = new DataTable();
dt.Load(dr);
Assuming your file is a standard comma separated files with headers, that's all you need. There are also options to allow reading files without headers, and using alternate delimiters etc.
It is also possible to provide a custom schema for the CSV file so that columns can be treated as something other than string
values. This will allow the DataTable
columns to be loaded with values that can be easier to work with, as you won't have to coerce them when you access them.
This can be accomplished by providing an ICsvSchemaProvider implementation, which exposes a single method DbColumn? GetColumn(string? name, int ordinal)
. The DbColumn
type is an abstract type defined in System.Data.Common
, which means that you would have to provide an implementation of that too if you implement your own schema provider. The DbColumn type exposes a variety of metadata about a column, and you can choose to expose as much of the metadata as needed. The most important metadata is the DataType
and AllowDBNull
.
A very simple implementation that would expose type information could look like the following:
class TypedCsvColumn : DbColumn
{
public TypedCsvColumn(Type type, bool allowNull)
{
// if you assign ColumnName here, it will override whatever is in the csv header
this.DataType = type;
this.AllowDBNull = allowNull;
}
}
class TypedCsvSchema : ICsvSchemaProvider
{
List<TypedCsvColumn> columns;
public TypedCsvSchema()
{
this.columns = new List<TypedCsvColumn>();
}
public TypedCsvSchema Add(Type type, bool allowNull = false)
{
this.columns.Add(new TypedCsvColumn(type, allowNull));
return this;
}
DbColumn? ICsvSchemaProvider.GetColumn(string? name, int ordinal)
{
return ordinal < columns.Count ? columns[ordinal] : null;
}
}
To consume this implementation you would do the following:
var schema = new TypedCsvSchema()
.Add(typeof(int))
.Add(typeof(string))
.Add(typeof(double), true)
.Add(typeof(DateTime))
.Add(typeof(DateTime), true);
var options = new CsvDataReaderOptions
{
Schema = schema
};
using var dr = CsvDataReader.Create("data.csv", options);
...
The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage
blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... }
block, but as a result, you'll lose validation of syntax, parameters, etc within the script
block.
I think you are very confused about what is occurring.
In Python, everything is an object:
[]
(a list) is an object'abcde'
(a string) is an object1
(an integer) is an objectMyClass()
(an instance) is an objectMyClass
(a class) is also an objectlist
(a type--much like a class) is also an objectThey are all "values" in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.
When you call a class object (like MyClass()
or list()
), it returns an instance of that class. (list
is really a type and not a class, but I am simplifying a bit here.)
When you print an object (i.e. get a string representation of an object), that object's __str__
or __repr__
magic method is called and the returned value printed.
For example:
>>> class MyClass(object):
... def __str__(self):
... return "MyClass([])"
... def __repr__(self):
... return "I am an instance of MyClass at address "+hex(id(self))
...
>>> m = MyClass()
>>> print m
MyClass([])
>>> m
I am an instance of MyClass at address 0x108ed5a10
>>>
So what you are asking for, "I need that MyClass return a list, like list(), not the instance info," does not make any sense. list()
returns a list instance. MyClass()
returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print
them or look at them in the console, then create a __str__
and __repr__
method which represents them as you want them to be represented.
Once again, __str__
and __repr__
are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__
value does not mean they are equal!
MyClass() != MyClass()
because your class does not define how these would be equal, so it falls back to the default behavior (of the object
type), which is that objects are only equal to themselves:
>>> m = MyClass()
>>> m1 = m
>>> m2 = m
>>> m1 == m2
True
>>> m3 = MyClass()
>>> m1 == m3
False
If you want to change this, use one of the comparison magic methods
For example, you can have an object that is equal to everything:
>>> class MyClass(object):
... def __eq__(self, other):
... return True
...
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1 == m2
True
>>> m1 == m1
True
>>> m1 == 1
True
>>> m1 == None
True
>>> m1 == []
True
I think you should do two things:
Justify why you are not subclassing list
if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:
class MyClass(object):
def __init__(self):
self._list = []
def __getattr__(self, name):
return getattr(self._list, name)
# __repr__ and __str__ methods are automatically created
# for every class, so if we want to delegate these we must
# do so explicitly
def __repr__(self):
return "MyClass(%s)" % repr(self._list)
def __str__(self):
return "MyClass(%s)" % str(self._list)
This will now act like a list without being a list (i.e., without subclassing list
).
>>> c = MyClass()
>>> c.append(1)
>>> c
MyClass([1])
This did the trick for me: (solution from the msdn forum)
goto Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.
right click to get properties dialog. Goto Security tab and customize permissions accordingly.
In Launch and Application Permissions, select Customize, Edit. Add the user / group that calls the application.
@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000
If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:
...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'
or
...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06'
AND usagetime < '2012-09-03 08:03:07'
Here is my solution
-- Create the maximum number of words we want to pick (indexes in n)
with recursive n(i) as (
select
1 i
union all
select i+1 from n where i < 1000
)
select distinct
s.id,
s.oaddress,
-- n.i,
-- use the index to pick the nth word, the last words will always repeat. Remove the duplicates with distinct
if(instr(reverse(trim(substring_index(s.oaddress,' ',n.i))),' ') > 0,
reverse(substr(reverse(trim(substring_index(s.oaddress,' ',n.i))),1,
instr(reverse(trim(substring_index(s.oaddress,' ',n.i))),' '))),
trim(substring_index(s.oaddress,' ',n.i))) oth
from
app_schools s,
n
Check the jsfiddle http://jsfiddle.net/CdwB9/3/ and click on delete
function yesnodialog(button1, button2, element){
var btns = {};
btns[button1] = function(){
element.parents('li').hide();
$(this).dialog("close");
};
btns[button2] = function(){
// Do nothing
$(this).dialog("close");
};
$("<div></div>").dialog({
autoOpen: true,
title: 'Condition',
modal:true,
buttons:btns
});
}
$('.delete').click(function(){
yesnodialog('Yes', 'No', $(this));
})
This should help you
PHP's string length is limited by the way strings are represented in PHP; memory does not have anything to do with it.
According to phpinternalsbook.com, strings are stored in struct { char *val; int len; } and since the maximum size of an int in C is 4 bytes, this effectively limits the maximum string size to 2GB.
If you are sorting a random-accessible collection (like an array), it's general best to pick the physical middle item. With this, if the array is all ready sorted (or nearly sorted), the two partitions will be close to even, and you'll get the best speed.
If you are sorting something with only linear access (like a linked-list), then it's best to choose the first item, because it's the fastest item to access. Here, however,if the list is already sorted, you're screwed -- one partition will always be null, and the other have everything, producing the worst time.
However, for a linked-list, picking anything besides the first, will just make matters worse. It pick the middle item in a listed-list, you'd have to step through it on each partition step -- adding a O(N/2) operation which is done logN times making total time O(1.5 N *log N) and that's if we know how long the list is before we start -- usually we don't so we'd have to step all the way through to count them, then step half-way through to find the middle, then step through a third time to do the actual partition: O(2.5N * log N)
simple, try this
position: fixed;
width: 500px;
height: 300px;
top: calc(50% - 150px);
left: calc(50% - 250px);
background-color: red;
You may find QString::fromUtf8() also useful.
For QByteArray input
of "\010"
and "\000"
,
QString::fromLocal8Bit(input, 1) returns "\010"
and ""
QString::fromUtf8(input, 1) correctly returns "\010"
and "\000"
.
You can view which modules (compiled in) are available via terminal through php -m
Solution without page reload
<?php
function removeday() { echo 'Day removed'; }
if (isset($_GET['remove'])) { return removeday(); }
?>
<!DOCTYPE html><html><title>Days</title><body>
<a href="" onclick="removeday(event)" class="deletebtn">Delete</a>
<script>
async function removeday(e) {
e.preventDefault();
document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
}
</script>
</body></html>
Let uses a more immediate block level limited scope whereas var is function scope or global scope typically.
It seems let was chosen most likely because it is found in so many other languages to define variables, such as BASIC, and many others.
Reference - https://developer.android.com/training/system-ui/immersive.html
// This snippet shows the system bars. It does this by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
--another way to do this
df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0)).reset_index(drop=True)
df.columns.name = None
Sample Number Group Number Sample Name Group Name
0 1.0 1.0 s_1 g_1
1 2.0 1.0 s_2 g_1
2 3.0 1.0 s_3 g_1
3 4.0 2.0 s_4 g_2
If you like it hit up arrow. Thanks
pthread.h
isn't on Windows. But Windows has extensive threading functionality, beginning with CreateThread.
My advice is don't get caught looking at WinAPI through the lens of another system's API. These systems are different. It's like insisting on riding the Win32 bike with your comfortable Linux bike seat. Well, the seat might not fit right and in some cases it'll just fall off.
Threads pretty much work the same on different systems, you have ThreadPools and mutexes. Having worked with both pthreads
and Windows threads, I can say the Windows threading offers quite a bit more functionality than pthread
does.
Learning another API is pretty easy, just think in terms of the concepts (mutex, etc), then look up how to create one of those on MSDN.
I fixed my error. just removed "Value" from this line:
If drv.Item("Quantity").Value < 5 Then
So it will look like
If drv.Item("Quantity") < 5 Then
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
Other answers to this question do not return what the OP needs, they will return a string like:
test1 test2 test3 test1 test3 test4
(notice that test1
and test3
are duplicated) while the OP wants to return this string:
test1 test2 test3 test4
the problem here is that the string "test1 test3"
is duplicated and is inserted only once, but all of the others are distinct to each other ("test1 test2 test3"
is distinct than "test1 test3"
, even if some tests contained in the whole string are duplicated).
What we need to do here is to split each string into different rows, and we first need to create a numbers table:
CREATE TABLE numbers (n INT);
INSERT INTO numbers VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
then we can run this query:
SELECT
SUBSTRING_INDEX(
SUBSTRING_INDEX(tableName.categories, ' ', numbers.n),
' ',
-1) category
FROM
numbers INNER JOIN tableName
ON
LENGTH(tableName.categories)>=
LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1;
and we get a result like this:
test1
test4
test1
test1
test2
test3
test3
test3
and then we can apply GROUP_CONCAT aggregate function, using DISTINCT clause:
SELECT
GROUP_CONCAT(DISTINCT category ORDER BY category SEPARATOR ' ')
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
FROM
numbers INNER JOIN tableName
ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
) s;
Please see fiddle here.
I had luck with something similar:
Convert(DATETIME, CONVERT(VARCHAR(2), @Month) + '/' + CONVERT(VARCHAR(2), @Day)
+ '/' + CONVERT(VARCHAR(4), @Year))
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
I used your own pivot as a nested query and came to this result:
SELECT
[sub].[chardate],
SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
select *
from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
[sub].[chardate],
[sub].[numericmonth]
ORDER BY
[sub].[numericmonth] ASC
Node 7.4 now supports async/await calls with the harmony flag.
Try this:
async function getExample(){
let response = await returnPromise();
let response2 = await returnPromise2();
console.log(response, response2)
}
getExample()
and run the file with:
node --harmony-async-await getExample.js
Simple as can be!
Regex.Split("abc][rfd][5][,][.", @"\]\]");
Have you tried an approach like on this link? I'm not sure if createValueBinding()
is still available but code like this should be accessible from a plain old Servlet. This does require to bean to already exist.
http://www.coderanch.com/t/211706/JSF/java/access-managed-bean-JSF-from
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
// May be deprecated
ValueBinding binding = app.createValueBinding("#{" + expr + "}");
Object value = binding.getValue(context);
If you're trying to print a specific register in GDB, you have to omit the % sign. For example,
info registers eip
If your executable is 64 bit, the registers start with r. Starting them with e is not valid.
info registers rip
Those can be abbreviated to:
i r rip
If you only need to exclude out enter
, escape
and spacebar
keys, you can do the following:
$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
alert('test');
}
});
You can refer to the complete list of keycode here for your further modification.
word-wrap: break-word
recently changed to overflow-wrap: break-word
word-break: break-all
So if you have many fixed-size spans which get content dynamically, you might just prefer using word-wrap: break-word
, as that way only the continuous words are broken in between, and in case it’s a sentence comprising many words, the spaces are adjusted to get intact words (no break within a word).
And if it doesn’t matter, go for either.
i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified .
You are unable to install requests in python 3.4 because your python libraries are not updated .
use this command
apt-get install python3-requests
Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.
The pipe, |
, is a special-character in regex (meaning "or") and you'll have to escape it with a \
.
Using your current regex:
\|.*$
I've tried this in Notepad++, as you've mentioned, and it appears to work well.
This is the easiest way I think
var reverse = function(str) {_x000D_
var arr = [];_x000D_
_x000D_
for (var i = 0, len = str.length; i <= len; i++) {_x000D_
arr.push(str.charAt(len - i))_x000D_
}_x000D_
_x000D_
return arr.join('');_x000D_
}_x000D_
_x000D_
console.log(reverse('I want a '));
_x000D_
Laravel - htmlspecialchars() expects parameter 1 to be string, object given.
thank me latter.........................
when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error
->use any think who convert array into string it work.
solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}
implode is best way to do it and its 100% work.
Note : This answer is now out-of-date. You are now required to have an API key to use google maps. Read More
you need to change your API from V2 to V3, Since Google Map Version 3 don't required API Key
Check this out..
write your script
as
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;
grep -nh error logfile | cut -d: -f1 | deletelines logfile
(where deletelines
is the utility you are imagining you need) is the same as
grep -v error logfile
Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed
script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed
.
sed 's%$%d%' linenumbers
This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d
appended after each. This is a valid sed
script, which we can save to a file, or (on some platforms) pipe to another sed
instance:
sed 's%$%d%' linenumbers | sed -f - logfile
On some platforms, sed -f
does not understand the option argument -
to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin
or /proc/$pid/fd/1
if your OS (or shell) has that.
As always, you can add -i
before the -f
option to have sed
edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i
as well; a common idiom is to supply an empty argument; -i ''
.
Reading between the lines - Is this an innodb database? In which case the actual data is normally stored in that directory under the name ibdata1. This file contains all your tables unless you specifically set up mysql to use one-file-per-table (innodb-file-per-table)
The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:
Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
_: [Circular],
VERSION: '1.1.4',
forEach: [Function],
each: [Function],
map: [Function],
inject: [Function],
(...more functions...)
templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6
For this you need to check the value of navigator.appVersion or navigator.userAgent Try using:
console.log(navigator.appVersion)
This is very compact:
w['female'][w['female'] == 'female']=1
w['female'][w['female'] == 'male']=0
Another good one:
w['female'] = w['female'].replace(regex='female', value=1)
w['female'] = w['female'].replace(regex='male', value=0)
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:
cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""
Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).
From the website:
Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.
margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;
0 is for top-bottom and auto for left-right. The browser sets the margin.
This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)
var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();
Run this code in your powershell or cmd
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
You can also achieve this using the backreference technique
sed -i.bak 's/\(.*\)/\1:80/' foo.txt
You can also use with awk like this
awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution. This works for me fine.
i am using this function to truncate value after decimal in a string variable
public static string TruncateFunction(string value)
{
if (string.IsNullOrEmpty(value)) return "";
else
{
string[] split = value.Split('.');
if (split.Length > 0)
{
string predecimal = split[0];
string postdecimal = split[1];
postdecimal = postdecimal.Length > 6 ? postdecimal.Substring(0, 6) : postdecimal;
return predecimal + "." + postdecimal;
}
else return value;
}
}
to navigate directories quicky, there's $CDPATH, cdargs, and ways to generate aliases automatically
http://jackndempsey.blogspot.com/2008/07/cdargs.html
http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html
Typical usage might look like:
i=0
echo -e "hello1\nhello2\nhello3" | while read str ; do
echo "$((++i)): $str"
done
and output
1: hello1
2: hello2
3: hello3
These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
won't work because worksheet functions (when actually used on a worksheet) don't understand Range
or Cell
Try
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"
As many answers are written for the same domains, I'll write how to do this in cross domains.
First, you need to know the Post Message API. We need a messenger to communicate between two windows.
Here's a messenger I created.
/**
* Creates a messenger between two windows
* which have two different domains
*/
class CrossMessenger {
/**
*
* @param {object} otherWindow - window object of the other
* @param {string} targetDomain - domain of the other window
* @param {object} eventHandlers - all the event names and handlers
*/
constructor(otherWindow, targetDomain, eventHandlers = {}) {
this.otherWindow = otherWindow;
this.targetDomain = targetDomain;
this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));
}
post(event, data) {
try {
// data obj should have event name
var json = JSON.stringify({
event,
data
});
this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}
}
receive(e) {
var json;
try {
json = JSON.parse(e.data ? e.data : "{}");
} catch (e) {
return;
}
var eventName = json.event,
data = json.data;
if (e.origin !== this.targetDomain)
return;
if (typeof this.eventHandlers[eventName] === "function")
this.eventHandlers[eventName](data);
}
}
Using this in two windows to communicate can solve your problem.
In the main windows,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('\n');
msger.post("cssContent", {
css: cssContent
})
Then, receive the event from the Iframe.
In the Iframe:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
cssContent: (data) => {
var cssElem = document.createElement("style");
cssElem.innerHTML = data.css;
document.head.appendChild(cssElem);
}
})
See the Complete Javascript and Iframes tutorial for more details.
The HTTP 1.1 specification says:
URIs in HTTP can be represented in absolute form or relative to some
known base URI [11], depending upon the context of their use. The two
forms are differentiated by the fact that absolute URIs always begin
with a scheme name followed by a colon. For definitive information on
URL syntax and semantics, see "Uniform Resource Identifiers (URI): Generic Syntax and Semantics," RFC 2396 [42] (which replaces RFCs 1738 [4] and RFC 1808 [11]). This specification adopts the definitions of "URI-reference", "absoluteURI", "relativeURI", "port",
"host","abs_path", "rel_path", and "authority" from that
specification.The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs.* A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.
As mentioned by @Brian, the HTTP clients (e.g. browsers) may have their own limits, and HTTP servers will have different limits.
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:
pygame.draw.rect
draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect
object:
pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)
pygame.draw.circle
draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):
pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
pygame.draw.polygon(window, (255, 255, 0),
[(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])
pygame.display.flip()
pygame.quit()
exit()
i also have the same problem while parsing schema definition files(XSD) using XSOM library,
i was able to increase Stack memory upto 208Mb then it showed heap_out_of_memory_error
for which i was able to increase only upto 320mb.
the final configuration was -Xmx320m -Xss208m
but then again it ran for some time and failed.
My function prints recursively the entire tree of the schema definition,amazingly the output file crossed 820Mb for a definition file of 4 Mb(Aixm library) which in turn uses 50 Mb of schema definition library(ISO gml).
with that I am convinced I have to avoid Recursion and then start iteration and some other way of representing the output, but I am having little trouble converting all that recursion to iteration.
A more concise solution:
this._Http.get(`${API_URL}/api/v1/data/logs`, {
params: {
logNamespace: logNamespace
}
})
If you have a table with an IDENTITY column that you want to reset the next value for you can use the following command:
ALTER TABLE <table name>
ALTER COLUMN <column name>
RESTART WITH <new value to restart with>;
YOU HAVE TO BE CAREFUL when you initialize state
from props
in constructor. Even if props
changed to new one, the state wouldn't be changed because mount never happen again.
So getDerivedStateFromProps
exists for that.
class FirstComponent extends React.Component {
state = {
description: ""
};
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.description !== nextProps.description) {
return { description: nextProps.description };
}
return null;
}
render() {
const {state: {description}} = this;
return (
<input type="text" value={description} />
);
}
}
Or use key
props as a trigger to initialize:
class SecondComponent extends React.Component {
state = {
// initialize using props
};
}
<SecondComponent key={something} ... />
In the code above, if something
changed, then SecondComponent
will re-mount as a new instance and state
will be initialized by props
.
SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;
It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.
#include <iostream>
#include <string>
#include <array>
using namespace std;
void print(auto arg) {
cout<<arg<<" ";
}
int main()
{
string f = "String";//tok assigned
int x = 998;
double a = 4.785;
string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
print(a);
print(b);
print(x);
print(f);
}
upgrade numpy to the latest version
pip install numpy --upgrade
You're mixing the parts together instead of separating them cleanly.
printf '\e[1;34m%-6s\e[m' "This is text"
Basically, put the fixed stuff in the format and the variable stuff in the parameters.
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data
that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password@sid @tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
You have a string like this.
"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"
Then you can covert it to ArrayList via Gson like
var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()
Your HotelInfo class should like this.
import com.squareup.moshi.Json
data class HotelInfo(
@Json(name="cityName")
val cityName: String? = null,
@Json(name="id")
val id: Int? = null,
@Json(name="hotelId")
val hotelId: String? = null,
@Json(name="hotelName")
val hotelName: String? = null
)
x_train = x_train.reshape(-1,28, 28, 1) #Reshape for CNN - should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
Output:
Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906
You can simply convert the given number using Number primitive type in JavaScript as shown below.
var c = Number(first) + Number(second);
Classic technique (escape metacharacters):
if [ \( "$g" -eq 1 -a "$c" = "123" \) -o \( "$g" -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi
I've enclosed the references to $g
in double quotes; that's good practice, in general. Strictly, the parentheses aren't needed because the precedence of -a
and -o
makes it correct even without them.
Note that the -a
and -o
operators are part of the POSIX specification for test
, aka [
, mainly for backwards compatibility (since they were a part of test
in 7th Edition UNIX, for example), but they are explicitly marked as 'obsolescent' by POSIX. Bash (see conditional expressions) seems to preempt the classic and POSIX meanings for -a
and -o
with its own alternative operators that take arguments.
With some care, you can use the more modern [[
operator, but be aware that the versions in Bash and Korn Shell (for example) need not be identical.
for g in 1 2 3
do
for c in 123 456 789
do
if [[ ( "$g" -eq 1 && "$c" = "123" ) || ( "$g" -eq 2 && "$c" = "456" ) ]]
then echo "g = $g; c = $c; true"
else echo "g = $g; c = $c; false"
fi
done
done
Example run, using Bash 3.2.57 on Mac OS X:
g = 1; c = 123; true
g = 1; c = 456; false
g = 1; c = 789; false
g = 2; c = 123; false
g = 2; c = 456; true
g = 2; c = 789; false
g = 3; c = 123; false
g = 3; c = 456; false
g = 3; c = 789; false
You don't need to quote the variables in [[
as you do with [
because it is not a separate command in the same way that [
is.
Isn't it a classic question?
I would have thought so. However, there is another alternative, namely:
if [ "$g" -eq 1 -a "$c" = "123" ] || [ "$g" -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi
Indeed, if you read the 'portable shell' guidelines for the autoconf
tool or related packages, this notation — using '||
' and '&&
' — is what they recommend. I suppose you could even go so far as:
if [ "$g" -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ "$g" -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi
Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable — or you need to wrap the actions into a function that is invoked in the different then
blocks.
On Windows,
To run a python module without typing "python",
--> Right click any python(*.py) file
--> Set the open with property to "python.exe"
--> Check the "always use this program for this file type"
--> Append the path of python.exe to variable environment e.g. append C:\Python27 to PATH environment variable.
To Run a python module without typing ".py" extension
--> Edit PATHEXT system variable and append ".PY" extension to the list.
You can follow below steps to embed the files you want to your website.
References: https://www.steegle.com/websites/google-sites-howtos/embed-drive-pdf
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
/*
*DisplayMetrics: A structure describing general information about a display, such as its size, density, and font scaling.
* */
DisplayMetrics metrics = getResources().getDisplayMetrics();
int DeviceTotalWidth = metrics.widthPixels;
int DeviceTotalHeight = metrics.heightPixels;
Try this in case you do not want to install OpenJDK: JDK Source Installer for Ubuntu
This works for me. I use it as a redirect to a page that explains why we don't like < IE9 and provide links to browsers we prefer.
<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
Use:
1..10 | % { write "loop $_" }
Output:
PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10
There are two methods you can use. Both require creating a user and a database.
By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydatabase
as the example database name.
Using createuser and createdb, we can be explicit about the database name,
$ sudo -u postgres createuser -s $USER
$ createdb mydatabase
$ psql -d mydatabase
You should probably be omitting that entirely and letting all the commands default to the user's name instead.
$ sudo -u postgres createuser -s $USER
$ createdb
$ psql
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.
PHP Page: session.php
if (!isset($_SESSION))
{
session_start();
}
$_SESSION['variable'] = "hello world";
$sessions = array();
$sessions['variable'] = $_SESSION['variable'];
header('Content-Type: application/json');
echo json_encode($sessions);
Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.
JS All Together
var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {
Session.then(function(response){
$rootScope.session = response;
});
}]);
app.factory('Session', function($http) {
return $http.get('/session.php').then(function(result) {
return result.data;
});
});
HTML
Inside your html you can reference your session
<html ng-app="StarterApp">
<body ng-controller="AppCtrl">
{{ session.variable }}
</body>
The snippet below does the job as expected!
<input type="text" name="AUS" pattern="[0-9]{10}" title="You can enter only 10 digits..." />
//type="text" <!-- always -->
//name="AUS" <!-- for Australia -->
//pattern="[0-9]{10}" <!-- 10 digits from 0 to 9 -->
//title="You can enter only 10 digits..." <!-- Pops a warning when input mismatches -->
Kindly first of all check your latest sdk first step:
Now Run
run flutter doctor --android-licenses Press Y against each agreement
No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.
This should do it.
I found it here: http://forums.asp.net/p/1331581/2678206.aspx
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server" ImageUrl="~/site/img/icons/cross.png"
CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this event?');"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateField>
A not well known feature of numpy is to use r_
. This is a simple way to build up arrays quickly:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]
The purpose of a[None,:]
is to add an axis to array a
.
I would like to expand on acheron55's answer, since it is a very non-safe solution, for several reasons:
FileSystem
object.FileSystem
object already exists.This is somewhat a safer solution:
private static ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public void walk(String path) throws Exception {
URI uri = getClass().getResource(path).toURI();
if ("jar".equals(uri.getScheme()) {
safeWalkJar(path, uri);
} else {
Files.walk(Paths.get(path));
}
}
private void safeWalkJar(String path, URI uri) throws Exception {
synchronized (getLock(uri)) {
// this'll close the FileSystem object at the end
try (FileSystem fs = getFileSystem(uri)) {
Files.walk(fs.getPath(path));
}
}
}
private Object getLock(URI uri) {
String fileName = parseFileName(uri);
locks.computeIfAbsent(fileName, s -> new Object());
return locks.get(fileName);
}
private String parseFileName(URI uri) {
String schemeSpecificPart = uri.getSchemeSpecificPart();
return schemeSpecificPart.substring(0, schemeSpecificPart.indexOf("!"));
}
private FileSystem getFileSystem(URI uri) throws IOException {
try {
return FileSystems.getFileSystem(uri);
} catch (FileSystemNotFoundException e) {
return FileSystems.newFileSystem(uri, Collections.<String, String>emptyMap());
}
}
There's no real need to synchronize over the file name; one could simply synchronize on the same object every time (or make the method synchronized
), it's purely an optimization.
I would say that this is still a problematic solution, since there might be other parts in the code that use the FileSystem
interface over the same files, and it could interfere with them (even in a single threaded application).
Also, it doesn't check for null
s (for instance, on getClass().getResource()
.
This particular Java NIO interface is kind of horrible, since it introduces a global/singleton non thread-safe resource, and its documentation is extremely vague (a lot of unknowns due to provider specific implementations). Results may vary for other FileSystem
providers (not JAR). Maybe there's a good reason for it being that way; I don't know, I haven't researched the implementations.
Found an easy solution for Spring-Boot, Spring-Security and Java-based config:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
return new CorsConfiguration().applyPermitDefaultValues();
}
});
}
}
Looks like you are missing the printer name, driver, and port - in that order. Your final command should resemble:
AcroRd32.exe /t <file.pdf> <printer_name> <printer_driver> <printer_port>
For example:
"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "C:\Folder\File.pdf" "Brother MFC-7820N USB Printer" "Brother MFC-7820N USB Printer" "IP_192.168.10.110"
Note: To find the printer information, right click your printer and choose properties. In my case shown above, the printer name and driver name matched - but your information may differ.
You could use the timeout
setting in the ajax options like this:
$.ajax({
url: "test.html",
timeout: 3000,
error: function(){
//do something
},
success: function(){
//do something
}
});
Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/
Remember that when a timeout occurs, the error
handler is triggered and not the success
handler :)
You may want to try using the inttypes.h library that gives you types such as
int32_t
, int64_t
, uint64_t
etc.
You can then use its macros such as:
uint64_t x;
uint32_t y;
printf("x: %"PRId64", y: %"PRId32"\n", x, y);
This is "guaranteed" to not give you the same trouble as long
, unsigned long long
etc, since you don't have to guess how many bits are in each data type.
Maybe you're talking about the Reverse Polish Notation? If yes you can find on wikipedia a very detailed step-to-step example for the conversion; if not I have no idea what you're asking :(
You might also want to read my answer to another question where I provided such an implementation: C++ simple operations (+,-,/,*) evaluation class
Maybe I read the problem wrong, but I believe you already have inserted the course 11 records and simply need to update those that meet the criteria you listed with course 6's data.
If this is the case, you'll want to use an UPDATE
...FROM
statement:
UPDATE MyTable
SET
complete = 1,
complete_date = newdata.complete_date,
post_score = newdata.post_score
FROM
(
SELECT
userID,
complete_date,
post_score
FROM MyTable
WHERE
courseID = 6
AND complete = 1
AND complete_date > '8/1/2008'
) newdata
WHERE
CourseID = 11
AND userID = newdata.userID
By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?
The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:
this.dispose();
If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.
On Mac OS X Mojave
python
stands for python of version 2.7 and python3
for python of version 3. The same is pip
and pip3
. So, to upgrade pip
for python 3
do this:
~$ sudo pip3 install --upgrade pip
<div id='parent' style='width: 100%;text-align:center;'>
<div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>
There is too much data to be displayed on the screen, therefore a summary is displayed instead.
If you want to output the data anyway (it won't probably fit on a screen and does not look very well):
print paramdata.values
converts the dataframe to its numpy-array matrix representation.
paramdata.columns
stores the respective column names and
paramdata.index
stores the respective index (row names).
I found the issue by connecting the iPad to the computer and viewing the console through the XCode Organizer while trying to install the app. The error turns out to be:
Could not load non-https manifest URL: http://example.com/manifest.plist
Turns out that in iOS 7.1, the URL for the manifest.plist
file has to be HTTPS, where we were using HTTP. Changing the URL to HTTPS resolved the problem.
I.e.
itms-services://?action=download-manifest&url=http://example.com/manifest.plist
becomes
itms-services://?action=download-manifest&url=https://example.com/manifest.plist
I would assume you have to have a valid SSL certificate for the domain in question. We already did but I'd imagine you'll have issues without it.
With Swift 3, you can choose one of the following ways to solve your problem.
sorted(by:?)
with a Movie
class that does not conform to Comparable
protocolIf your Movie
class does not conform to Comparable
protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted(by:?)
with a Movie
class that conforms to Comparable
protocolHowever, by making your Movie
class conform to Comparable
protocol, you can have a much concise code when you want to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted()
with a Movie
class that conforms to Comparable
protocolBy making your Movie
class conform to Comparable
protocol, you can use Array's sorted()
method as an alternative to sorted(by:?)
.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
try this
$(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");
I would recommend creating a HashMap
from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|)
time (as there would be no collisions), whereas retainAll(Collection<?> c)
must run in O(|A|*|B|)
time.
This file (cygwin1.dll) is cygwin dependency similar to qt dependency.you must copy this file and similar files that appear in such messages error, from "cygwin/bin" to folder of the your program .Also this is necessary to run in another computer that have NOT cygwin!
Might be better choice:
@Override
public String toString() {
return new GsonBuilder().create().toJson(this, Producto.class);
}
Tensorflow version in Jupyter Notebook:-
!pip list | grep tensorflow
Web.config file
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS; Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>
.cs file
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Kotlin Solution:
1) Paste this extension function somewhere.
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
2) Use it, and never google this again.
val myDate = myLocalDate.toDate()
next = pow(2, ceil(log(x)/log(2)));
This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power.
This is a more general purpose (i.e. slower!) method than the bitwise methods linked elsewhere, but good to know the maths, eh?
Clearing a list in place will affect all other references of the same list.
For example, this method doesn't affect other references:
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]
But this one does:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
You could also do:
>>> a[:] = []
As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
globe
function results with is_file
is necessary, because it might return some directories as well..
in their names, so */*
pattern sucks in general.Visual mode map example to add single quotes around a selected block of text:
:vnoremap qq <Esc>`>a'<Esc>`<i'<Esc>
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
I'm not sure whether you think about:
select * from friend f
where not exists (
select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)
it works only if id1 is related with id1 and id2 with id2 not both.
In case you want to chain a lot of querysets, try this:
from itertools import chain
result = list(chain(*docs))
where: docs is a list of querysets
when we use the
php artisan serve
it will start with the default HTTP-server port mostly it will be 8000
when we want to run the more site in the localhost we have to change the port. Just add the --port argument:
php artisan serve --port=8081
untested but should give you the idea. the view:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>
upload.php controller:
$csv = array();
// check there are no errors
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$col_count = count($data);
// get the values from the csv
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
// inc the row
$row++;
}
fclose($handle);
}
}
}
this works with most types of elements:
$('selector').on('click',function(e){
log(e.currentTarget.id);
});
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
There seems to be a nice package by Yonatan Matalon called UrlUtil. Quoting its API:
isValidWebPageAddress(java.lang.String address, boolean validateSyntax,
boolean validateExistance)
Checks if the given address is a valid web page address.
Sun's Java site offers connect attempt as a solution for validating URLs.
There are regex validation attempts at Oracle's site and weberdev.com.
Directly using scanf(3)
and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)
At least if you fgets(3)
you know how many input lines your program will need, and you won't have any buffer overflows...
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
SELECT varchar_col
FROM table
GROUP BY varchar_col
HAVING COUNT(*) > 1;
Note that it may be better use subdomains instead of usual URL. So, set .example.com
instead of https://example.com/
.
Thanks to Jody Jacobus Geers and others I wrote so:
if (savedInstanceState == null) {
val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
val domain = ".example.com"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setCookie(domain, "token=$token") {
view.webView.loadUrl(url)
}
cookieManager.setAcceptThirdPartyCookies(view.webView, true)
} else {
cookieManager.setCookie(domain, "token=$token")
view.webView.loadUrl(url)
}
} else {
// Check whether we're recreating a previously destroyed instance.
view.webView.restoreState(savedInstanceState)
}
Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).
nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)
should work.
my two cents:
sed -i '1i /path/of/file.sh' filename
This will work even is the string containing forward slash "/"
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError
if dictionary[old_key]
is undefined. Note that this will delete dictionary[old_key]
.
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
You can compile a C# program :
c: > csc Hello.cs
You can run the program
c: > Hello
segmentation fault arrives when you access memory which is not declared by the program. You can do this through pointers i.e through memory addresses. Or this may also be due to stackoverflow for eg:
void rec_func() {int q = 5; rec_func();}
int main() {rec_func();}
This call will keep on consuming stack memory until it's completely filled and thus finally stackoverflow happens. Note: it might not be visible in some competitive questions as it leads to timeouterror first but for those in which timeout doesn't happens its a hard time figuring out sigsemv.
Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc
For example:
git clone https://github.com/zrax/pycdc
cd pycdc
make
./bin/pycdc Example.pyc > Example.py
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
Have you tried to define a custom background in xml? decreasing the Spinner background width which is doing your arrow look like that.
Define a layer-list with a rectangle background and your custom arrow icon:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/color_white" />
<corners android:radius="2.5dp" />
</shape>
</item>
<item android:right="64dp">
<bitmap android:gravity="right|center_vertical"
android:src="@drawable/custom_spinner_icon">
</bitmap>
</item>
</layer-list>
Here is what worked for me.
Install the userspace USB programming library development files
sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h
The path should appear as (or similar)
/usr/include/libusb-1.0/libusb.h
Include the header to your C code
#include <libusb-1.0/libusb.h>
Compile your C file
gcc -o example example.c -lusb-1.0
Swift 4.0, 4.1 & 4.2 First, I created mutable array of type imageFile() as shown below
var arr = [imageFile]()
Create mutable object image of type imageFile() and assign value to properties as shown below
var image = imageFile()
image.fileId = 14
image.fileName = "A"
Now, append this object to array arr
arr.append(image)
Now, assign the different properties to same mutable object i.e image
image = imageFile()
image.fileId = 13
image.fileName = "B"
Now, again append image object to array arr
arr.append(image)
Now, we will apply Ascending order on fileId property in array arr objects. Use < symbol for Ascending order
arr = arr.sorted(by: {$0.fileId < $1.fileId}) // arr has all objects in Ascending order
print("sorted array is",arr[0].fileId)// sorted array is 13
print("sorted array is",arr[1].fileId)//sorted array is 14
Now, we will apply Descending order on on fileId property in array arr objects. Use > symbol for Descending order
arr = arr.sorted(by: {$0.fileId > $1.fileId}) // arr has all objects in Descending order
print("Unsorted array is",arr[0].fileId)// Unsorted array is 14
print("Unsorted array is",arr[1].fileId)// Unsorted array is 13
In Swift 4.1. & 4.2 For sorted order use
let sortedArr = arr.sorted { (id1, id2) -> Bool in
return id1.fileId < id2.fileId // Use > for Descending order
}
Uncomment this line (in /conf/logging.properties
)
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Work's for me in tomcat 7.0.53!
There is a function in scipy named scipy.signal.find_peaks_cwt
which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..
http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Try this way of formation, it is rather fancy ...
Have a look at this jsfiddle
The idea is to choose a the radio as a button instead of the normal circle image.
I will share my code:
In your given example date:
$dateValue = '2012-01-05';
It will go like this:
dateName($dateValue);
function dateName($date) {
$result = "";
$convert_date = strtotime($date);
$month = date('F',$convert_date);
$year = date('Y',$convert_date);
$name_day = date('l',$convert_date);
$day = date('j',$convert_date);
$result = $month . " " . $day . ", " . $year . " - " . $name_day;
return $result;
}
and will return a value: January 5, 2012 - Thursday
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
One more solution:
#footer { display:table; margin:0 auto; }
#footer li { display:table-cell; padding: 0px 10px; }
Then ul doesn't jump to the next line in case of zooming text.
You can add the script tags like how we use in the asp.net while doing client side validations like below.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
//Your code
});
</script>
To understand the significance of field serialVersionUID, one should understand how Serialization/Deserialization works.
When a Serializable class object is serialized Java Runtime associates a serial version no.(called as serialVersionUID) with this serialized object. At the time when you deserialize this serialized object Java Runtime matches the serialVersionUID of serialized object with the serialVersionUID of the class. If both are equal then only it proceeds with the further process of deserialization else throws InvalidClassException.
So we conclude that to make Serialization/Deserialization process successful the serialVersionUID of serialized object must be equivalent to the serialVersionUID of the class. In case if programmer specifies the serialVersionUID value explicitly in the program then the same value will be associated with the serialized object and the class, irrespective of the serialization and deserialzation platform(for ex. serialization might be done on platform like windows by using sun or MS JVM and Deserialization might be on different platform Linux using Zing JVM).
But in case if serialVersionUID is not specified by programmer then while doing Serialization\DeSerialization of any object, Java runtime uses its own algorithm to calculate it. This serialVersionUID calculation algorithm varies from one JRE to another. It is also possible that the environment where the object is serialized is using one JRE (ex: SUN JVM) and the environment where deserialzation happens is using Linux Jvm(zing). In such cases serialVersionUID associated with serialized object will be different than the serialVersionUID of class calculated at deserialzation environment. In turn deserialization will not be successful. So to avoid such situations/issues programmer must always specify serialVersionUID of Serializable class.
You cant add add items in string array more than its size, i'll suggest you to use ArrayList you can add items dynamically at run time in arrayList if you feel any problem you can freely ask
You could fix it with the PHP constant __DIR__
require_once __DIR__ . '/common/configs/config_templates.inc.php';
It is the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname
__FILE__
. This directory name does not have a trailing slash unless it is the root directory. 1
You are missing an equality:
var query = (from p in tblPersoon where p.id == 5 select p).Single();
where
clause must result in a boolean.
OR you should not be using where
at all:
var query = (from p in tblPersoon select p).Single();
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.
Warning: Note that English is not restricted to just A-Z.
Try this to remove everything except a-z, A-Z and 0-9:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.
Try this to leave only A-Z:
$result = preg_replace("/[^A-Z]+/", "", $s);
The reason for the warning is that words like résumé contains the letter é
that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.
As a rule, if your "underline" is not the same color as your text [and the 'color:' is not overridden inline] it is not coming from "text-decoration:" It has to be "border-bottom:"
Don't forget to take the border off your pseudo classes too!
a, a:link, a:visited, a:active, a:hover {border:0!important;}
This snippet assumes its on an anchor, change to it's wrapper accordingly... and use specificity instead of "!important" after you track down the root cause.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
//Example to define how to do :
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
dt.Columns.Add("City");
// The table structure is:
//ID FirstName LastName Address City
//Now we want to add a PhoneNo column after the LastName column. For this we use the
//SetOrdinal function, as iin:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
//3 is the position number and positions start from 0.`enter code here`
//Now the table structure will be:
// ID FirstName LastName PhoneNo Address City
This is how I do it:
public static String readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
sb.append(mLine); // process line
mLine = reader.readLine();
}
reader.close();
return sb.toString();
}
use it as follows:
readFromAssets(context,"test.txt")
It means parent/child
example:
html>body
that's saying that body is a child of html
Check out: Selectors
Just in case you are using Boostrap in Angulajs: this is a simple directive that works for me (because data-toggle cited by Kam is not included in Angular-ui). Hope can help.
app.directive("myDataToggle", function(){
function link(scope, element, attrs) {
var e = angular.element(element);
e.on('click', function(){
e.parent().parent().children().removeClass('active');
e.parent().addClass("active");
})
}
return {
restrict: 'A',
link: link
};
});
<ul class="nav nav-sidebar">
<li><a href="#/page1" my-data-toggle>Page1</a></li>
<li><a href="#/page2" my-data-toggle>Page2</a></li>
<li><a href="#/page3" my-data-toggle>Page3</a></li>
</ul>
Something like this? Takes advantage of short-circuit evaluation. If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part.
os.path.exists("gogogo.php") and os.remove("gogogo.php")
I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),
1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install
2- Add "using Microsoft.SharePoint.Client; "
then the below code
string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
SecureString passWord = new SecureString();
var password = "Your password here";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
ClientContext clientContext = new ClientContext(siteUrl);
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["PK"] = "1";
oListItem["Precinct"] = "Mangere";
oListItem["Title"] = "Innovation";
oListItem["Project_x005F_x0020_Name"] = "test from C#";
oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
oListItem.Update();
clientContext.ExecuteQuery();
Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?
A few approaches:
1- Use MS flow and see them
2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column
3- Use a C# reader and read your sharepoint list
The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)
You can try this:
pip list
This will output all the packages with their versions. Output
First, JavaScript's switch
is no faster than if/else
(and sometimes much slower).
Second, the only way to use switch
with multiple variables is to combine them into one primitive (string, number, etc) value:
var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
case "foo-bar": ...
...
}
But, personally, I would rather see a set of if
/else
statements.
Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.
https://stackoverflow.com/a/30640097/2569475
For This Issue check My answer at above given url
Using a request scoped bean outside of an actual web request
Any Java collection can be made to be Thread-safe like so:
List newList = Collections.synchronizedList(oldList);
Or to create a brand new thread-safe list:
List newList = Collections.synchronizedList(new ArrayList());
DECLARE @MyDate datetime
-- ... set your datetime's initial value ...'
DATEADD(d, 1, @MyDate)
How does spark context in your application pick the value for spark master?
SparkConf
while creating SC.System.getProperties
(where SparkSubmit earlier put it after reading your --master
argument).Now, SparkSubmit
runs on the driver -- which in your case is the machine from where you're executing the spark-submit
script. And this is probably working as expected for you too.
However, from the information you've posted it looks like you are creating a spark context in the code that is sent to the executor -- and given that there is no spark.master
system property available there, it fails. (And you shouldn't really be doing so, if this is the case.)
Can you please post the GroupEvolutionES
code (specifically where you're creating SparkContext(s)
).
Use the correct doc type; it will solve the problem. Add the below line to the top of your HTML file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
Yes, you're looking for the ReDim
statement, which dynamically allocates the required amount of space in the array.
The following statement
Dim MyArray()
declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.
But you can use the ReDim
statement to resize the array:
ReDim MyArray(0 To 3)
And if you need to resize the array while preserving its contents, you can use the Preserve
keyword along with the ReDim
statement:
ReDim Preserve MyArray(0 To 3)
But do note that both ReDim
and particularly ReDim Preserve
have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.
However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim
at all. Just declare the array with explicit dimensions:
Dim MyArray(0 To 3)
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
You could skip the jquery and just use CSS style tagging:
<ul>
<li>India</li>
<li>Indonesia</li>
<li style="background-color:#343434;">China</li>
<li>United States</li>
<li>United Kingdom</li>
</ul>
UPDATE YourTable SET columnName = null WHERE YourCondition
ISNUMERIC will not do - it tells you that the string can be converted to any of the numeric types, which is almost always a pointless piece of information to know. For example, all of the following are numeric, according to ISNUMERIC:
£, $, 0d0
If you want to check for digits and only digits, a negative LIKE expression is what you want:
not Value like '%[^0-9]%'
I am not an expert but try white-space:nowrap;
The white-space property is supported in all major browsers.
Note: The value "inherit"
is not supported in IE7 and earlier. IE8 requires a !DOCTYPE
. IE9 supports "inherit"
.
Converted DateID having date in Int format to date format: Presto Query
Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
from
Table_Name
limit 10;
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
As @Heinzi mentioned the character set of the response should be used.
var encoding = response.CharacterSet == ""
? Encoding.UTF8
: Encoding.GetEncoding(response.CharacterSet);
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream, encoding);
var responseString = reader.ReadToEnd();
}
It turned out there were 2 versions of SQL Server installed on the machine.
Removing the old one solved the issues on my side.
More details:
During the startup the services of both services were trying to run.
And the one which was loaded first was working properly and was blocking the second to start.
P.S. Stopping the services of the first server and manually starting the second wasn't working as well.
I had similar issue on Windows 7. At first I setup M2, M2_HOME under User variable but when I echoed %PATH% , I did not see maven bin directory listed under PATH. Then I setup M2, M2_HOME under system variable and it worked.
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
You can set max connections using:
set global max_connections = '1 < your number > 100000';
This will set your number of mysql connection unti (Requires SUPER
privileges).
SQL 2005 or later, CTEs are the standard way to go as per the examples shown.
SQL 2000, you can do it using UDFs -
CREATE FUNCTION udfPersonAndChildren
(
@PersonID int
)
RETURNS @t TABLE (personid int, initials nchar(10), parentid int null)
AS
begin
insert into @t
select * from people p
where personID=@PersonID
while @@rowcount > 0
begin
insert into @t
select p.*
from people p
inner join @t o on p.parentid=o.personid
left join @t o2 on p.personid=o2.personid
where o2.personid is null
end
return
end
(which will work in 2005, it's just not the standard way of doing it. That said, if you find that the easier way to work, run with it)
If you really need to do this in SQL7, you can do roughly the above in a sproc but couldn't select from it - SQL7 doesn't support UDFs.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;