seeing how the rules are fairly complicated, I'd suggest the following:
/^[a-z](\w*)[a-z0-9]$/i
match the whole string and capture intermediate characters. Then either with the string functions or the following regex:
/__/
check if the captured part has two underscores in a row. For example in Python it would look like this:
>>> import re
>>> def valid(s):
match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
if match is not None:
return match.group(1).count('__') == 0
return False
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines)
out.close()
And then:
replace_line('stats.txt', 0, 'Mage')
You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:
<body oncopy="return false" oncut="return false" onpaste="return false">
How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers
A more advanced aproach:
How to detect Ctrl+V, Ctrl+C using JavaScript?
Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.
if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.
-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.
I think that second thing is better because you give to java the automatic memory management.
With CSS3 we can easily adjust an image. But remember this does not change the image. It only displays the adjusted image.
See the following code for more details.
To make an image gray:
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
}
To give a sepia look:
img {
-webkit-filter: sepia(100%);
-moz-filter: sepia(100%);
}
To adjust brightness:
img {
-webkit-filter: brightness(50%);
-moz-filter: brightness(50%);
}
To adjust contrast:
img {
-webkit-filter: contrast(200%);
-moz-filter: contrast(200%);
}
To Blur an image:
img {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
}
I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell
and change the date manually.
Like has been repeated, functors are classes that can be treated as functions (overload operator ()).
They are most useful for situations in which you need to associate some data with repeated or delayed calls to a function.
For example, a linked-list of functors could be used to implement a basic low-overhead synchronous coroutine system, a task dispatcher, or interruptable file parsing. Examples:
/* prints "this is a very simple and poorly used task queue" */
class Functor
{
public:
std::string output;
Functor(const std::string& out): output(out){}
operator()() const
{
std::cout << output << " ";
}
};
int main(int argc, char **argv)
{
std::list<Functor> taskQueue;
taskQueue.push_back(Functor("this"));
taskQueue.push_back(Functor("is a"));
taskQueue.push_back(Functor("very simple"));
taskQueue.push_back(Functor("and poorly used"));
taskQueue.push_back(Functor("task queue"));
for(std::list<Functor>::iterator it = taskQueue.begin();
it != taskQueue.end(); ++it)
{
*it();
}
return 0;
}
/* prints the value stored in "i", then asks you if you want to increment it */
int i;
bool should_increment;
int doSomeWork()
{
std::cout << "i = " << i << std::endl;
std::cout << "increment? (enter the number 1 to increment, 0 otherwise" << std::endl;
std::cin >> should_increment;
return 2;
}
void doSensitiveWork()
{
++i;
should_increment = false;
}
class BaseCoroutine
{
public:
BaseCoroutine(int stat): status(stat), waiting(false){}
void operator()(){ status = perform(); }
int getStatus() const { return status; }
protected:
int status;
bool waiting;
virtual int perform() = 0;
bool await_status(BaseCoroutine& other, int stat, int change)
{
if(!waiting)
{
waiting = true;
}
if(other.getStatus() == stat)
{
status = change;
waiting = false;
}
return !waiting;
}
}
class MyCoroutine1: public BaseCoroutine
{
public:
MyCoroutine1(BaseCoroutine& other): BaseCoroutine(1), partner(other){}
protected:
BaseCoroutine& partner;
virtual int perform()
{
if(getStatus() == 1)
return doSomeWork();
if(getStatus() == 2)
{
if(await_status(partner, 1))
return 1;
else if(i == 100)
return 0;
else
return 2;
}
}
};
class MyCoroutine2: public BaseCoroutine
{
public:
MyCoroutine2(bool& work_signal): BaseCoroutine(1), ready(work_signal) {}
protected:
bool& work_signal;
virtual int perform()
{
if(i == 100)
return 0;
if(work_signal)
{
doSensitiveWork();
return 2;
}
return 1;
}
};
int main()
{
std::list<BaseCoroutine* > coroutineList;
MyCoroutine2 *incrementer = new MyCoroutine2(should_increment);
MyCoroutine1 *printer = new MyCoroutine1(incrementer);
while(coroutineList.size())
{
for(std::list<BaseCoroutine *>::iterator it = coroutineList.begin();
it != coroutineList.end(); ++it)
{
*it();
if(*it.getStatus() == 0)
{
coroutineList.erase(it);
}
}
}
delete printer;
delete incrementer;
return 0;
}
Of course, these examples aren't that useful in themselves. They only show how functors can be useful, the functors themselves are very basic and inflexible and this makes them less useful than, for example, what boost provides.
You need to make your datetime objects timezone aware. from the datetime docs:
There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
When you have an aware datetime object, you can use isoformat() and get the output you need.
To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil
Using pytz, this would look like:
import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()
You can also control the output format, if you use strftime with the '%z' format directive like
datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.
For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />
Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>
Try:
return $this->sendRequest($uri);
Since PHP is not a pure Object-Orieneted language, it interprets sendRequest()
as an attempt to invoke a globally defined function (just like nl2br()
for example), but since your function is part of a class ('InstagramController'), you need to use $this
to point the interpreter in the right direction.
user@host> g++ hw.cpp
user@host> ./a.out
$com1 = new-object PSobject #Task1
$com2 = new-object PSobject #Task1
$com3 = new-object PSobject #Task1
$com1 | add-member noteproperty -name user -value jindpal #Task2
$com1 | add-member noteproperty -name code -value IT01 #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com2 | add-member noteproperty -name user -value singh #Task2
$com2 | add-member noteproperty -name code -value IT02 #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com3 | add-member noteproperty -name user -value dhanoa #Task2
$com3 | add-member noteproperty -name code -value IT03 #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$arr += $com1, $com2, $com3 #Task4
write-host "windows version of computer1 is: "$com1.ver() #Task3
write-host "user name of computer1 is: "$com1.user #Task6
write-host "code of computer1 is: "$com1,code #Task5
write-host "windows version of computer2 is: "$com2.ver() #Task3
write-host "user name of computer2 is: "$com2.user #Task6
write-host "windows version of computer3 is: "$com3.ver() #Task3
write-host "user name of computer3 is: "$com1.user #Task6
write-host "code of computer3 is: "$com3,code #Task5
read-host
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} }
then perform:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify()
was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
For SharePoint Can find the web config file in C:\inetpub\wwwroot\wss\VirtualDirectories\Sitecollection port number - and Make changes
<system.web>
<pages enableSessionState="true" />
</system.web>
and using SharePoint Management Shell Run below Command
Enable-SPSessionStateService -DefaultProvision
I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream"
:
<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>
To create a Twitter share link with a photo, you first need to tweet out the photo from your Twitter account. Once you've tweeted it out, you need to grab the pic.twitter.com link and place that inside your twitter share url.
note: You won't be able to see the pic.twitter.com url so what I do is use a separate account and hit the retweet button. A modal will pop up with the link inside.
You Twitter share link will look something like this:
<a href="https://twitter.com/home?status=This%20photo%20is%20awesome!%20Check%20it%20out:%20pic.twitter.com/9Ee63f7aVp">Share on Twitter</a>
When you use a blade echo {{ $data }}
it will automatically escape the output. It can only escape strings. In your data $data->ac
is an array and $data
is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }}
(not sure why you have two nested arrays but I'm just following your data structure).
@foreach($data->ac['0'] as $link)
<a href="{{ $link['url'] }}">This is a link</a>
@endforeach
That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.
Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431
You can also try out cliqr
. Its pretty new and in active development. But there are stable releases ready to be used. Here is the git repo: https://github.com/anshulverma/cliqr
Look into the example folder to get an idea on how it can be used.
You can tell whether Apache is using preform or worker by issuing the following command
apache2ctl -l
In the resulting output, look for mentions of prefork.c or worker.c
If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:
if(theHref){
// do stuff
}else{
// do other stuff
}
An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)
If you don't have readlink or realpath utilities than you can use following function which works in bash and zsh (not sure about the rest).
abspath () { case "$1" in /*)printf "%s\n" "$1";; *)printf "%s\n" "$PWD/$1";; esac; }
This also works for nonexistent files (as does the python function os.path.abspath
).
Unfortunately abspath ./../somefile
doesn't get rid of the dots.
Use the Azure CLI
az account get-access-token --query tenant --output tsv
I was getting the same error with building USBView project in VS2015. I removed this error by selecting 'Platform Toolset' settings to to "Visual Studio 2015 (v140)" and than right click on solution (in VS2015) and select 'Retarget Solution' and selected 10.0.10240.0 on that dialog.
It seems like there is also ProjectUpgradeTool from microsoft which is suppose to convert older projects to upgrade to post VS2012 VS but I couldn't locate that tool on my machine.
I still have to fix some new linker error with help of this.
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
There are CSS options for the audio tag.
Like: html 5 audio tag width
But if you play around with it you'll see results can be unexpected - as of August 2012.
You might want to try one of the following ways:
createNativeQuery(sqlString, resultClass)
Native queries can also be defined dynamically using the EntityManager.createNativeQuery()
API.
String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
Query query = em.createNativeQuery(sql, User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
@NamedNativeQuery
Native queries are defined through the @NamedNativeQuery
and @NamedNativeQueries
annotations, or <named-native-query>
XML element.
@NamedNativeQuery(
name="complexQuery",
query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
resultClass=User.class
)
public class User { ... }
Query query = em.createNamedQuery("complexQuery", User.class);
query.setParameter(1, id);
User user = (User) query.getSingleResult();
You can read more in the excellent open book Java Persistence (available in PDF).
-------
NOTE: With regard to use of getSingleResult()
, see Why you should never use getSingleResult()
in JPA.
if you are just using the simulator and just upgraded then this solved the issue for me: go to menu->project-edit project setting. find code signing section (you can type 'code' in the quick search) in the code signing identity select 'any sdk' and set the value to 'Don't Code Sign'
Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.sp_alarmSelection:
//Do something
Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
case R.id.sp_optionSelection:
//Do another thing
Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
use JSON.stringify(param1, param2, param3);
What is: -
param1 --> value to convert to JSON
param2 --> function to stringify in your own way. Alternatively, it serves as a white list for which objects need to be included in the final JSON.
param3 --> A Number data type which indicates number of whitespaces to add. Max allowed are 10.
Few Operation relates to Array in Swift
Create Array
var stringArray = ["One", "Two", "Three", "Four"]
Add Object in Array
stringArray = stringArray + ["Five"]
Get Value from Index object
let x = stringArray[1]
Append Object
stringArray.append("At last position")
Insert Object at Index
stringArray.insert("Going", at: 1)
Remove Object
stringArray.remove(at: 3)
Concat Object value
var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
For Hive external tables I use this function in PySpark:
def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
print("Saving result in {}.{}".format(database, table_name))
output_schema = "," \
.join(["{} {}".format(x.name.lower(), x.dataType) for x in list(dataframe.schema)]) \
.replace("StringType", "STRING") \
.replace("IntegerType", "INT") \
.replace("DateType", "DATE") \
.replace("LongType", "INT") \
.replace("TimestampType", "INT") \
.replace("BooleanType", "BOOLEAN") \
.replace("FloatType", "FLOAT")\
.replace("DoubleType","FLOAT")
output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)
sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))
query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
.format(database, table_name, output_schema, save_format, database, table_name)
sparkSession.sql(query)
dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)
Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it
CASE
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens
-
or colons:
.
So:
^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$
The second option is feasible also if you're using safe updates mode (and you're getting an error indicating that you've tried to update a table without a WHERE that uses a KEY column), by adding:
UPDATE TableB
SET TableB.value = (
SELECT TableA.value
FROM TableA
WHERE TableA.name = TableB.name
)
**where TableB.id < X**
;
I think this should work:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
you can configure eslint overrides property to turn off specific rules on files which matches glob pattern like below.
Here, I want to turn off the no-duplicate-string
rule for tests all files.
overrides: [
{
files: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
rules: {
'sonarjs/no-duplicate-string': 'off'
}
}
]
A Trie data structure would work the best, better than DP. Here is the code.
class TrieNode:
def __init__(self):
self.child = [None]*26
self.endWord = False
class Trie:
def __init__(self):
self.root = self.getNewNode()
def getNewNode(self):
return TrieNode()
def insert(self,value):
root = self.root
for i,character in enumerate(value):
index = ord(character) - ord('a')
if not root.child[index]:
root.child[index] = self.getNewNode()
root = root.child[index]
root.endWord = True
def search(self,value):
root = self.root
for i,character in enumerate(value):
index = ord(character) - ord('a')
if not root.child[index]:
return False
root = root.child[index]
return root.endWord
def main():
# Input keys (use only 'a' through 'z' and lower case)
keys = ["the","anaswe"]
output = ["Not present in trie",
"Present in trie"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
print("{} ---- {}".format("the",output[t.search("the")]))
print("{} ---- {}".format("these",output[t.search("these")]))
print("{} ---- {}".format("their",output[t.search("their")]))
print("{} ---- {}".format("thaw",output[t.search("thaw")]))
if __name__ == '__main__':
main()
Let me know in case of doubts.
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
I devoloped this,
declare @x nvarchar(Max) = 'ali.veli.deli.';
declare @item nvarchar(Max);
declare @splitter char='.';
while CHARINDEX(@splitter,@x) != 0
begin
set @item = LEFT(@x,CHARINDEX(@splitter,@x))
set @x = RIGHT(@x,len(@x)-len(@item) )
select @item as item, @x as x;
end
the only attention you should is dot '.' that end of the @x is always should be there.
In Swift:
import AVFoundation
...
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
I know it's over a year old, but calling requestFeature()
never solved my problem. In fact I don't call it at all.
It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.
AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog()
to update that view.
Another alternative is to leverage AsyncTask for dialogs.
A final solution that I used is below:
public class CustomDialog extends AlertDialog {
private View content;
public CustomDialog(Context context) {
super(context);
LayoutInflater li = LayoutInflater.from(context);
content = li.inflate(R.layout.custom_view, null);
setUpAdditionalStuff(); // do more view cleanup
setView(content);
}
private void setUpAdditionalStuff() {
// ...
}
// Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method
public void prepare() {
setTitle(R.string.custom_title);
setIcon( getIcon() );
// ...
}
}
* Some Additional notes:
The above steps are foundation and basic. I followed them and still got error of "mysql failed to start".
For the new folder to store mysql data, you need to make sure that the folder has permissions and ownership mysql:mysql.
Beside this, it needs to check the permissions and ownership of parent directory of mysql if having, say, /data/mysql/. Here /data/ directory should be root:root. I fixed the error of "mysql failed to start" after changing ownership of parent directory of /mysql. The OS in my VM is RHEL 7.6.
The solution that worked for me is the following one given..
I selected the particular project> right click >Build path>configure Build path> Libraries> I noticed that JRE system Library was showing(Unbound) hence..
selected that Library>click on Remove>click on Apply>click on add Library>JRE system Library>next>workspace default JRE>click on Finish>Apply>ok.
now you will not see these exclamation icon in your project.
You can use LINQ:
String.Concat(str.OrderBy(c => c))
If you want to remove duplicates, add .Distinct()
.
And I like this way:
$cars = array
(
array("Volvo",22),
array("BMW",15),
array("Saab",5),
array("Land Rover",17)
);
You can use the gulp-filenames module to get the array of paths. You can even group them by namespaces:
var filenames = require("gulp-filenames");
gulp.src("./src/*.coffee")
.pipe(filenames("coffeescript"))
.pipe(gulp.dest("./dist"));
gulp.src("./src/*.js")
.pipe(filenames("javascript"))
.pipe(gulp.dest("./dist"));
filenames.get("coffeescript") // ["a.coffee","b.coffee"]
// Do Something With it
egrep -ir --include=*.{php,html,js} "(document.cookie|setcookie)" .
The r
flag means to search recursively (search subdirectories). The i
flag means case insensitive.
If you just want file names add the l
(lowercase L
) flag:
egrep -lir --include=*.{php,html,js} "(document.cookie|setcookie)" .
Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
Hint lies in Webapi2 auto generated account controller
Have this property with getter defined as
public string UserIdentity
{
get
{
var user = UserManager.FindByName(User.Identity.Name);
return user;//user.Email
}
}
and in order to get UserManager - In WebApi2 -do as Romans (read as AccountController) do
public ApplicationUserManager UserManager
{
get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
}
This should be compatible in IIS and self host mode
Get the flag parameter from the URL string http://cube.wisercapital.com/hf/create?flag=1
public function create(Request $request)
{
$flag = $request->input('flag');
return view('hf.create', compact('page_title', 'page_description', 'flag'));
}
Even simpler, use path/filepath
:
package main
import (
"fmt"
"log"
"path/filepath"
)
func main() {
files, err := filepath.Glob("*")
if err != nil {
log.Fatal(err)
}
fmt.Println(files) // contains a list of all files in the current directory
}
route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys
Ideally you shouldn't be splitting strings in T-SQL at all.
Barring that change, on older versions before SQL Server 2016, create a split function:
CREATE FUNCTION dbo.SplitStrings
(
@List nvarchar(max),
@Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN ( WITH x(x) AS
(
SELECT CONVERT(xml, N'<root><i>'
+ REPLACE(@List, @Delimiter, N'</i><i>')
+ N'</i></root>')
)
SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
);
GO
Now you can say:
DECLARE @Values varchar(1000);
SET @Values = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN dbo.SplitStrings(@Values, ',') AS s
ON s.Item = foo.myField;
On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM()
to take away any leading spaces:
DECLARE @Values varchar(1000) = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN STRING_SPLIT(@Values, ',') AS s
ON LTRIM(s.value) = foo.myField;
In your code you are missing Class.forName("com.mysql.jdbc.Driver");
This is what you are missing to have everything working.
By playing with parameters as -XX:PermSize
and -Xms
you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms
was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.
A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).
WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms
equal to -Xmx
or -XX:PermSize
equal to -XX:MaxPermSize
as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.
As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)
I managed to do something similar by using this URL:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
It downloads a complete list of stock symbols using the Yahoo YQL API, including the stock name, stock symbol, and industry ID. What it doesn't seem to have is any sort of stock symbol modifiers. E.g. for Rogers Communications Inc, it only downloads RCI, not RCI-A.TO, RCI-B.TO, etc. I haven't found a source for that information yet - if anyone knows of a way to automate downloading that, I'd like to hear it. Also, it'd be nice to find a way to download some sort of relation between the stock symbol and the exchange it's traded on, since some are traded on multiple exchanges, or maybe I only want to look at stuff on the TSX or something.
Are you sure you have a column DEPARTEMENT_CODE on your table PS_TBL_DEPARTMENT_DETAILS
More informations about your ERROR
ORA-00904: string: invalid identifier Cause: The column name entered is either missing or invalid. Action: Enter a valid column name. A valid column name must begin with a letter, be less than or equal to 30 characters, and consist of only alphanumeric characters and the special characters $, _, and #. If it contains other characters, then it must be enclosed in d double quotation marks. It may not be a reserved word.
Alternate way is to use a "container view". Just make alpha below 1 and embed with seque. XCode 5, target iOS7. Tested on iPhone.
Container view available from iOS6. Link to blog post about that.
$out.='<option value="'.$key.'">'.$value["name"];
me funciono con esta
"<a href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";
Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String
For Each fileName In fileEntries
If (System.IO.File.Exists(fileName)) Then
'Read File and Print Result if its true
ReadFile(fileName)
End If
TransfereFile(fileName, 1)
Next
On wildfly 8 and later, go to /bin/standalone.conf
and put your JAVA_OPTS there, with all you need.
Since this issue is kind of old a lot of things have changed.
You can now get this behavior by adding this to the footer div
data-position="fixed"
More info here: http://jquerymobile.com/test/docs/toolbars/bars-fixed.html
Also beware, if you use the previously mentioned CSS together with the new JQM solution you will NOT get the appropriate behavior!
I would just like to add--
In windows the commit message should be in double quotes (git commit -m "initial commit"
instead of git commit -m 'initial commit'
), as I spent about an hour, just to figure out that single quote is not working in windows.
Its in the standard float.h include file. You want DBL_MAX
In answer ,it creates circular dependency.This can be avoided by removing parent inside Child nodes. i.e,
public class MyTreeNode<T>{
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Using the same example specified above,the output will be like this:
{ "data": "Root", "children": [ { "data": "Child1", "children": [ { "data": "Grandchild1", "children": [] }, { "data": "Grandchild2", "children": [] } ] }, { "data": "Child2", "children": [ { "data": "Grandchild3", "children": [] } ] }, { "data": "Child3", "children": [] }, { "data": "Child4", "children": [] }, { "data": "Child5", "children": [] }, { "data": "Child6", "children": [] } ] }
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
These specific lines are the usual wrapper for jQuery plugins:
"...to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
I know this is an old post but since it comes up in a google search I thought I'd share some knowledge here. @erin-geyer pointed out that mixing migrations and seeders can create headaches and @justamartin countered that sometimes you want/need data to be populated as part of your deployment.
I'd go one step further and say that sometimes it is desirable to be able to roll out data changes consistently so that you can for example deploy to staging, see that all is well, and then deploy to production with confidence of the same results (and not have to remember to run some manual step).
However, there is still value in separating out the seed and the migration as those are two related but distinct concerns. Our team has compromised by creating migrations which call seeders. This looks like:
public function up()
{
Artisan::call( 'db:seed', [
'--class' => 'SomeSeeder',
'--force' => true ]
);
}
This allows you to execute a seed one time just like a migration. You can also implement logic that prevents or augments behavior. For example:
public function up()
{
if ( SomeModel::count() < 10 )
{
Artisan::call( 'db:seed', [
'--class' => 'SomeSeeder',
'--force' => true ]
);
}
}
This would obviously conditionally execute your seeder if there are less than 10 SomeModels. This is useful if you want to include the seeder as a standard seeder that executed when you call artisan db:seed
as well as when you migrate so that you don't "double up". You may also create a reverse seeder so that rollbacks works as expected, e.g.
public function down()
{
Artisan::call( 'db:seed', [
'--class' => 'ReverseSomeSeeder',
'--force' => true ]
);
}
The second parameter --force
is required to enable to seeder to run in a production environment.
I have found on an arm hardfloat system where glibc binutils and gcc were crosscompiled, using gcc gives the same error.
It is solved by exporting-mfloat-abi=hard
to flags, then gcc compiles without errors.
Try like this: select DATENAME(DW,GETDATE())
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
You can use the java.time
package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
@Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
Classic javascript mistake.
setTimeout(function(){this.setState({timePassed: true})}, 1000)
When setTimeout
runs this.setState
, this
is no longer CowtanApp
, but window
. If you define the function with the =>
notation, es6 will auto-bind this
.
setTimeout(() => {this.setState({timePassed: true})}, 1000)
Alternatively, you could use a let that = this;
at the top of your render
, then switch your references to use the local variable.
render() {
let that = this;
setTimeout(function(){that.setState({timePassed: true})}, 1000);
If not working, use bind
.
setTimeout(
function() {
this.setState({timePassed: true});
}
.bind(this),
1000
);
Use Brew is always good way to install ANT and other needs. To install type below command on terminal.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
after Brew installation , type
brew install ant
This will install Ant on your system. Also you will not need to worry about setting up the path.
Also i have documented on the same - How to Install ANT on Mac OS?
The scalar formatter supports collecting the exponents. The docs are as follows:
class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter
Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.
your technique would be:
from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3)) # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)
To get the exponent displayed in the format x10^5
, instantiate the ScalarFormatter with useMathText=True
.
You could also use:
xfmt.set_useOffset(10000)
To get a result like this:
It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined
when object.x is the real undefined. In my case I inadvertently set undefined to null.
The easiest way to see this happen is:
window.undefined = null;
alert(window.xyzw === undefined); // shows false
Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
Use FileMode.Truncate
everytime you create the file. Also place the File.Create
inside a try
catch
.
Run
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following command in the folder where you downloaded: get-pip.py
python get-pip.py
Many times we might want to perform Table pagination using jquery.Here i ll give you the answer and reference link
Jquery
$(document).ready(function(){
$('#data').after('<div id="nav"></div>');
var rowsShown = 4;
var rowsTotal = $('#data tbody tr').length;
var numPages = rowsTotal/rowsShown;
for(i = 0;i < numPages;i++) {
var pageNum = i + 1;
$('#nav').append('<a href="#" rel="'+i+'">'+pageNum+'</a> ');
}
$('#data tbody tr').hide();
$('#data tbody tr').slice(0, rowsShown).show();
$('#nav a:first').addClass('active');
$('#nav a').bind('click', function(){
$('#nav a').removeClass('active');
$(this).addClass('active');
var currPage = $(this).attr('rel');
var startItem = currPage * rowsShown;
var endItem = startItem + rowsShown;
$('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
css('display','table-row').animate({opacity:1}, 300);
});
});
JSfiddle: https://jsfiddle.net/u9d1ewsh/
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
Maybe specifying a width would work. When you position:absolute
an element, it's width will shrink to the contents I believe.
The simplest way to install setuptools when it isn't already there and you can't use a package manager is to download ez_setup.py and run it with the appropriate Python interpreter. This works even if you have multiple versions of Python around: just run ez_setup.py once with each Python.
Edit: note that recent versions of Python 3 include setuptools in the distribution so you no longer need to install separately. The script mentioned here is only relevant for old versions of Python.
For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.
Done.
This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
If you want to scroll the page vertically to perform some action, you can do it using the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);
Where ‘JavascriptExecutor’ is an interface, which helps executing JavaScript through Selenium WebDriver. You can use the following code to import.
import org.openqa.selenium.JavascriptExecutor;
2.If you want to scroll at a particular element, you need to use the following JavaScript.
WebElement element = driver.findElement(By.xpath(“//input [@id=’email’]”));((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, element);
Where ‘element’ is the locator where you want to scroll.
3.If you want to scroll at a particular coordinate, use the following JavaScript.
((JavascriptExecutor)driver).executeScript(“window.scrollBy(200,300)”);
Where ‘200,300’ are the coordinates.
4.If you want to scroll up in a vertical direction, you can use the following JavaScript. ((JavascriptExecutor) driver).executeScript(“window.scrollTo(document.body.scrollHeight,0)”);
If you want to scroll horizontally in the right direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(2000,0)”);
If you want to scroll horizontally in the left direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(-2000,0)”);
While editing the file, make marks where you want the start and end to be using
ma
- sets the a
mark
mb
- sets the b
mark
Then, to copy that into another file, just use the w
command:
:'a,'bw /name/of/output/file.txt
If you don't want to change the router, just go to the HomeController and change MyNewViewHere in the index like this:
public ActionResult Index()
{
return View("MyNewViewHere");
}
Or, you can install the GNU version of sed in your Mac, called gsed, and use it using the standard Linux syntax.
For that, install gsed
using ports (if you don't have it, get it at http://www.macports.org/) by running sudo port install gsed
. Then, you can run sed -i 's/old_link/new_link/g' *
Judging by the source code for URI
, the
public URL(URL context, String spec, URLStreamHandler handler)
constructor does more validation than the other constructors. You might try that one, but YMMV.
Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',
/**
* Or set header
* CURLOPT_HTTPHEADER => [
'Cookie: foo=bar;baz=foo',
]
*/
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo $response;
The following worked for me: Just save as custom_shape.xml.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- "shadow" -->
<item>
<shape android:shape="rectangle" >
<solid android:color="#000000"/>
<corners android:radius="12dp" />
</shape>
</item>
<item android:bottom="3px">
<shape android:shape="rectangle">
<solid android:color="#90ffffff"/>
<corners android:radius="12dp" />
</shape>
</item>
</layer-list>
Here I will explain how to do it without an external library. It will be a very long post, so brace yourself.
First of all, let me acknowledge @tim.paetz whose post inspired me to set off to a journey of implementing my own sticky headers using ItemDecoration
s. I borrowed some parts of his code in my implementation.
As you might have already experienced, if you attempted to do it yourself, it is very hard to find a good explanation of HOW to actually do it with the ItemDecoration
technique. I mean, what are the steps? What is the logic behind it? How do I make the header stick on top of the list? Not knowing answers to these questions is what makes others to use external libraries, while doing it yourself with the use of ItemDecoration
is pretty easy.
Initial conditions
list
of items of different type (not in a "Java types" sense, but in a "header/item" types sense).list
must be a header item.Here I provide full code for my RecyclerView.ItemDecoration
called HeaderItemDecoration
. Then I explain the steps taken in detail.
public class HeaderItemDecoration extends RecyclerView.ItemDecoration {
private StickyHeaderInterface mListener;
private int mStickyHeaderHeight;
public HeaderItemDecoration(RecyclerView recyclerView, @NonNull StickyHeaderInterface listener) {
mListener = listener;
// On Sticky Header Click
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
if (motionEvent.getY() <= mStickyHeaderHeight) {
// Handle the clicks on the header here ...
return true;
}
return false;
}
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDrawOver(c, parent, state);
View topChild = parent.getChildAt(0);
if (Util.isNull(topChild)) {
return;
}
int topChildPosition = parent.getChildAdapterPosition(topChild);
if (topChildPosition == RecyclerView.NO_POSITION) {
return;
}
View currentHeader = getHeaderViewForItem(topChildPosition, parent);
fixLayoutSize(parent, currentHeader);
int contactPoint = currentHeader.getBottom();
View childInContact = getChildInContact(parent, contactPoint);
if (Util.isNull(childInContact)) {
return;
}
if (mListener.isHeader(parent.getChildAdapterPosition(childInContact))) {
moveHeader(c, currentHeader, childInContact);
return;
}
drawHeader(c, currentHeader);
}
private View getHeaderViewForItem(int itemPosition, RecyclerView parent) {
int headerPosition = mListener.getHeaderPositionForItem(itemPosition);
int layoutResId = mListener.getHeaderLayout(headerPosition);
View header = LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false);
mListener.bindHeaderData(header, headerPosition);
return header;
}
private void drawHeader(Canvas c, View header) {
c.save();
c.translate(0, 0);
header.draw(c);
c.restore();
}
private void moveHeader(Canvas c, View currentHeader, View nextHeader) {
c.save();
c.translate(0, nextHeader.getTop() - currentHeader.getHeight());
currentHeader.draw(c);
c.restore();
}
private View getChildInContact(RecyclerView parent, int contactPoint) {
View childInContact = null;
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if (child.getBottom() > contactPoint) {
if (child.getTop() <= contactPoint) {
// This child overlaps the contactPoint
childInContact = child;
break;
}
}
}
return childInContact;
}
/**
* Properly measures and layouts the top sticky header.
* @param parent ViewGroup: RecyclerView in this case.
*/
private void fixLayoutSize(ViewGroup parent, View view) {
// Specs for parent (RecyclerView)
int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);
// Specs for children (headers)
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.getPaddingLeft() + parent.getPaddingRight(), view.getLayoutParams().width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.getPaddingTop() + parent.getPaddingBottom(), view.getLayoutParams().height);
view.measure(childWidthSpec, childHeightSpec);
view.layout(0, 0, view.getMeasuredWidth(), mStickyHeaderHeight = view.getMeasuredHeight());
}
public interface StickyHeaderInterface {
/**
* This method gets called by {@link HeaderItemDecoration} to fetch the position of the header item in the adapter
* that is used for (represents) item at specified position.
* @param itemPosition int. Adapter's position of the item for which to do the search of the position of the header item.
* @return int. Position of the header item in the adapter.
*/
int getHeaderPositionForItem(int itemPosition);
/**
* This method gets called by {@link HeaderItemDecoration} to get layout resource id for the header item at specified adapter's position.
* @param headerPosition int. Position of the header item in the adapter.
* @return int. Layout resource id.
*/
int getHeaderLayout(int headerPosition);
/**
* This method gets called by {@link HeaderItemDecoration} to setup the header View.
* @param header View. Header to set the data on.
* @param headerPosition int. Position of the header item in the adapter.
*/
void bindHeaderData(View header, int headerPosition);
/**
* This method gets called by {@link HeaderItemDecoration} to verify whether the item represents a header.
* @param itemPosition int.
* @return true, if item at the specified adapter's position represents a header.
*/
boolean isHeader(int itemPosition);
}
}
Business logic
So, how do I make it stick?
You don't. You can't make a RecyclerView
's item of your choice just stop and stick on top, unless you are a guru of custom layouts and you know 12,000+ lines of code for a RecyclerView
by heart. So, as it always goes with the UI design, if you can't make something, fake it. You just draw the header on top of everything using Canvas
. You also should know which items the user can see at the moment. It just happens, that ItemDecoration
can provide you with both the Canvas
and information about visible items. With this, here are basic steps:
In onDrawOver
method of RecyclerView.ItemDecoration
get the very first (top) item that is visible to the user.
View topChild = parent.getChildAt(0);
Determine which header represents it.
int topChildPosition = parent.getChildAdapterPosition(topChild);
View currentHeader = getHeaderViewForItem(topChildPosition, parent);
Draw the appropriate header on top of the RecyclerView by using drawHeader()
method.
I also want to implement the behavior when the new upcoming header meets the top one: it should seem as the upcoming header gently pushes the top current header out of the view and takes his place eventually.
Same technique of "drawing on top of everything" applies here.
Determine when the top "stuck" header meets the new upcoming one.
View childInContact = getChildInContact(parent, contactPoint);
Get this contact point (that is the bottom of the sticky header your drew and the top of the upcoming header).
int contactPoint = currentHeader.getBottom();
If the item in the list is trespassing this "contact point", redraw your sticky header so its bottom will be at the top of the trespassing item. You achieve this with translate()
method of the Canvas
. As the result, the starting point of the top header will be out of visible area, and it will seem as "being pushed out by the upcoming header". When it is completely gone, draw the new header on top.
if (childInContact != null) {
if (mListener.isHeader(parent.getChildAdapterPosition(childInContact))) {
moveHeader(c, currentHeader, childInContact);
} else {
drawHeader(c, currentHeader);
}
}
The rest is explained by comments and thorough annotations in piece of code I provided.
The usage is straight forward:
mRecyclerView.addItemDecoration(new HeaderItemDecoration((HeaderItemDecoration.StickyHeaderInterface) mAdapter));
Your mAdapter
must implement StickyHeaderInterface
for it to work. The implementation depends on the data you have.
Finally, here I provide a gif with a half-transparent headers, so you can grasp the idea and actually see what is going on under the hood.
Here is the illustration of "just draw on top of everything" concept. You can see that there are two items "header 1" - one that we draw and stays on top in a stuck position, and the other one that comes from the dataset and moves with all the rest items. The user won't see the inner-workings of it, because you'll won't have half-transparent headers.
And here what happens in the "pushing out" phase:
Hope it helped.
Edit
Here is my actual implementation of getHeaderPositionForItem()
method in the RecyclerView's adapter:
@Override
public int getHeaderPositionForItem(int itemPosition) {
int headerPosition = 0;
do {
if (this.isHeader(itemPosition)) {
headerPosition = itemPosition;
break;
}
itemPosition -= 1;
} while (itemPosition >= 0);
return headerPosition;
}
Continuous Integration with Jenkins, after code is pushed to repository from Git command/ GUI:
.git/hooks
folder.The hooks
folder contains the few files. Check for the "post-commit". If not present, create a file, "post-commit" without a file extension:
C:\work\test\\.git\hooks\post-commit
Edit the "post-commit" file with the below command. Make sure it is present in your local source code hooks folder.
curl -u userName:apiToken -X POST http://localhost:8080/jenkins/job/jobName/build?token=apiToken
Example:
curl -u admin:f1c55b3a07bb2b69b9dd549e96898384 -X POST http://localhost:8080/jenkins/job/Gitcommittest/build?token=f1c55b3a07bb2b69b9dd549e96898384
5.
userName
: Jenkins user name
jobName
: Job name of the build
apiToken
: To get your API token, go to your Jenkins user page (top right in the interface). It is available in the "Configure" menu on the left of the page: "Show API token"
Make changes in your source code and commit the code to repository.
Your job, http://localhost:8080/jenkins/job/Gitcommittest/
, should be building.
I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..
The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):
body{
$colorStart: rgba(0,0,0,0);
$colorEnd: rgba(0,0,0,0.8);
@include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml
Tomasz Tybulewicz answer is good way to go.
SELECT * FROM pg_table_def WHERE tablename = 'YOUR_TABLE_NAME' AND schemaname = 'YOUR_SCHEMA_NAME';
If schema name is not defined in search path , that query will show empty result. Please first check search path by below code.
SHOW SEARCH_PATH
If schema name is not defined in search path , you can reset search path.
SET SEARCH_PATH to '$user', public, YOUR_SCEHMA_NAME
My overly complicated piece of code:
import random
letter = (random.randint(1,26))
if letter == 1:
print ('a')
elif letter == 2:
print ('b')
elif letter == 3:
print ('c')
elif letter == 4:
print ('d')
elif letter == 5:
print ('e')
elif letter == 6:
print ('f')
elif letter == 7:
print ('g')
elif letter == 8:
print ('h')
elif letter == 9:
print ('i')
elif letter == 10:
print ('j')
elif letter == 11:
print ('k')
elif letter == 12:
print ('l')
elif letter == 13:
print ('m')
elif letter == 14:
print ('n')
elif letter == 15:
print ('o')
elif letter == 16:
print ('p')
elif letter == 17:
print ('q')
elif letter == 18:
print ('r')
elif letter == 19:
print ('s')
elif letter == 20:
print ('t')
elif letter == 21:
print ('u')
elif letter == 22:
print ('v')
elif letter == 23:
print ('w')
elif letter == 24:
print ('x')
elif letter == 25:
print ('y')
elif letter == 26:
print ('z')
It basically generates a random number out of 26 and then converts into its corresponding letter. This could defiantly be improved but I am only a beginner and I am proud of this piece of code.
Bitcode is a new feature of iOS 9
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Note: For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required
So you should disabled bitcode until all the frameworks of your app have bitcode enabled.
for example on debian
sudo gpasswd -a svn-admin www-data
sudo chgrp -R www-data svn/
sudo chmod -R g=rwsx svn/
After=
dependency is only effective when service including After=
and service included by After=
are both scheduled to start as part of your boot up.
Ex:
a.service
[Unit]
After=b.service
This way, if both a.service
and b.service
are enabled, then systemd will order b.service
after a.service
.
If I am not misunderstanding, what you are asking is how to start b.service
when a.service
starts even though b.service
is not enabled.
The directive for this is Wants=
or Requires=
under [Unit]
.
website.service
[Unit]
Wants=mongodb.service
After=mongodb.service
The difference between Wants=
and Requires=
is that with Requires=
, a failure to start b.service
will cause the startup of a.service
to fail, whereas with Wants=
, a.service
will start even if b.service
fails. This is explained in detail on the man page of .unit
.
#for python 3
A = [0,1,2,3,4,5]
l = len(A)/2
B = A[:int(l)]
C = A[int(l):]
Updated for c# 6:
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
Very simple and nice to look at!!
This is old question but still my answer may help someone
For checking Java version in android studio version , simply open Terminal of Android Studio and type
java -version
This will display java version installed in android studio
So here's how to do that:
In the bottom bar of VSCode, you'll see the label
UTF-8
. Click it. A popup opens. ClickSave with encoding
. You can now pick a new encoding for that file.
Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8"
. If using the graphical settings page in VSCode, simply search for encoding
. Do note however that this only applies to newly created files.
A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.
When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test
Use an interface to show it who's boss.
public interface SleskeEnum {
int id();
SleskeEnum[] getValues();
}
public enum BonusType implements SleskeEnum {
MONTHLY(1), YEARLY(2), ONE_OFF(3);
public final int id;
BonusType(int id) {
this.id = id;
}
public SleskeEnum[] getValues() {
return values();
}
public int id() { return id; }
}
public class Utils {
public static SleskeEnum getById(SleskeEnum type, int id) {
for(SleskeEnum t : type.getValues())
if(t.id() == id) return t;
throw new IllegalArgumentException("BonusType does not accept id " + id);
}
public static void main(String[] args) {
BonusType shouldBeMonthly = (BonusType)getById(BonusType.MONTHLY,1);
System.out.println(shouldBeMonthly == BonusType.MONTHLY);
BonusType shouldBeMonthly2 = (BonusType)getById(BonusType.MONTHLY,1);
System.out.println(shouldBeMonthly2 == BonusType.YEARLY);
BonusType shouldBeYearly = (BonusType)getById(BonusType.MONTHLY,2);
System.out.println(shouldBeYearly == BonusType.YEARLY);
BonusType shouldBeOneOff = (BonusType)getById(BonusType.MONTHLY,3);
System.out.println(shouldBeOneOff == BonusType.ONE_OFF);
BonusType shouldException = (BonusType)getById(BonusType.MONTHLY,4);
}
}
And the result:
C:\Documents and Settings\user\My Documents>java Utils
true
false
true
true
Exception in thread "main" java.lang.IllegalArgumentException: BonusType does not accept id 4
at Utils.getById(Utils.java:6)
at Utils.main(Utils.java:23)
C:\Documents and Settings\user\My Documents>
I was catching GuzzleHttp\Exception\BadResponseException
as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException
when DNS for domain wasn't available.
So my suggestion is - catch GuzzleHttp\Exception\ConnectException
to be safe about DNS errors as well.
This error occurs because the transaction log becomes full due to LOG_BACKUP. Therefore, you can’t perform any action on this database, and In this case, the SQL Server Database Engine will raise a 9002 error.
To solve this issue you should do the following
I wrote an article with all details regarding this error and how to solve it at The transaction log for database ‘SharePoint_Config’ is full due to LOG_BACKUP
You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n
.
string1 = "go"
string2 = "now"
string3 = "great"
multiline_string = (f"I will {string1} there\n"
f"I will go {string2}.\n"
f"{string3}.")
print(multiline_string)
I will go there
I will go now
great
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (f"I will {string1} there. "
f"I will go {string2}. "
f"{string3}.")
print(singleline_string)
I will go there. I will go now. great.
Alternatively, you can also create a multiline f-string with triple quotes.
multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
In one line of code as below :
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
onmouseout="this.type='password'" placeholder="password" />
_x000D_
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
--allow-empty-message -m ''
(and -m ""
) fail in Git 2.29.2 on PowerShell:
error: switch `m' requires a value
(oddly enough, with a backtick on one side and a single quote on the other)
The following works consistently in Linux, PowerShell, and Command Prompt:
git commit --allow-empty-message --no-edit
The --no-edit
bit does the trick, as it prevents the editor from launching.
I find this form more explicit and a bit less hacky than forcing an empty message with -m ''
.
As has been said before, the clone and attach elsewhere method does not guarantee the same results as styling may be different.
Below is my approach. It travels up the parents looking for the parent responsible for the hiding, then temporarily unhides it to calculate the required width, height, etc.
var width = parseInt($image.width(), 10);_x000D_
var height = parseInt($image.height(), 10);_x000D_
_x000D_
if (width === 0) {_x000D_
_x000D_
if ($image.css("display") === "none") {_x000D_
_x000D_
$image.css("display", "block");_x000D_
width = parseInt($image.width(), 10);_x000D_
height = parseInt($image.height(), 10);_x000D_
$image.css("display", "none");_x000D_
}_x000D_
else {_x000D_
_x000D_
$image.parents().each(function () {_x000D_
_x000D_
var $parent = $(this);_x000D_
if ($parent.css("display") === "none") {_x000D_
_x000D_
$parent.css("display", "block");_x000D_
width = parseInt($image.width(), 10);_x000D_
height = parseInt($image.height(), 10);_x000D_
$parent.css("display", "none");_x000D_
}_x000D_
});_x000D_
}_x000D_
}
_x000D_
So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:
Let's start with this HTML:
<body>
<div>
<select id="test">
<option>Bob</option>
<option>Sam</option>
<option>Sue</option>
<option>Jen</option>
</select>
</div>
<table id="theTable">
<tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
<tr><td>Sue</td><td>Jen</td></tr>
</table>
</body>
Some very basic CSS:
?#theTable td {
border:1px solid #555;
}
.activeCell {
background-color:#F00;
}
And set up a jQuery event:
function highlightCell(useVal){
$("#theTable td").removeClass("activeCell")
.filter(":contains('"+useVal+"')").addClass("activeCell");
}
$(document).ready(function(){
$("#test").change(function(e){highlightCell($(this).val())});
});
Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying
.filter("#"+useVal)
and make sure to add the ids appropriately. Hope this helps!
If you don't want to use the standard dictionary method (looping through the list incrementing the proper dict. key), you can try this:
>>> from itertools import groupby
>>> myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon']
>>> [(k, len(list(g))) for k, g in groupby(sorted(myList))]
[('apple', 2), ('banana', 2), ('lemon', 1), ('strawberry', 1)]
It runs in O(n log n) time.
Workaround using policies:
interface INumericPolicy<T>
{
T Zero();
T Add(T a, T b);
// add more functions here, such as multiplication etc.
}
struct NumericPolicies:
INumericPolicy<int>,
INumericPolicy<long>
// add more INumericPolicy<> for different numeric types.
{
int INumericPolicy<int>.Zero() { return 0; }
long INumericPolicy<long>.Zero() { return 0; }
int INumericPolicy<int>.Add(int a, int b) { return a + b; }
long INumericPolicy<long>.Add(long a, long b) { return a + b; }
// implement all functions from INumericPolicy<> interfaces.
public static NumericPolicies Instance = new NumericPolicies();
}
Algorithms:
static class Algorithms
{
public static T Sum<P, T>(this P p, params T[] a)
where P: INumericPolicy<T>
{
var r = p.Zero();
foreach(var i in a)
{
r = p.Add(r, i);
}
return r;
}
}
Usage:
int i = NumericPolicies.Instance.Sum(1, 2, 3, 4, 5);
long l = NumericPolicies.Instance.Sum(1L, 2, 3, 4, 5);
NumericPolicies.Instance.Sum("www", "") // compile-time error.
The solution is compile-time safe. CityLizard Framework provides compiled version for .NET 4.0. The file is lib/NETFramework4.0/CityLizard.Policy.dll.
It's also available in Nuget: https://www.nuget.org/packages/CityLizard/. See CityLizard.Policy.I structure.
Looks like the data has the same columns, so you can:
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
merged_df = pd.concat([df1, df2])
It worked for me
import subprocess
my_ip = subprocess.Popen(['ifconfig eth0 | awk "/inet /" | cut -d":" -f 2 | cut -d" " -f1'], stdout=subprocess.PIPE, shell=True)
(IP,errors) = my_ip.communicate()
my_ip.stdout.close()
print IP
You need to use proper nesting and then apply styles to it.
Right click on button and find the exact class nesting for it using (Inspect element using firebug for firefox), (inspect element for chrome).
Add style to whole bunch of class. Only then it would work
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
If you find the notation awkward, maybe the -R
-option does help. It outpouts the date in RFC 2822 format. So you won't need all those identifiers: date -d @1278999698 -R
. Another possibility is to output the date in seconds in your locale: date -d @1278999698 +%c
. Should be easy to remember. :-)
I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
complete and working sample from my machine...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
xmlns:tools="http://schemas.android.com/tools"_x000D_
android:layout_width="fill_parent"_x000D_
android:layout_height="fill_parent"_x000D_
android:paddingLeft="@dimen/activity_horizontal_margin"_x000D_
android:paddingRight="@dimen/activity_horizontal_margin"_x000D_
android:paddingTop="@dimen/activity_vertical_margin"_x000D_
android:paddingBottom="@dimen/activity_vertical_margin"_x000D_
android:orientation="vertical"_x000D_
tools:context=".MainActivity"_x000D_
android:gravity="center"_x000D_
android:textAlignment="center">_x000D_
_x000D_
_x000D_
<TextView_x000D_
android:layout_width="fill_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textAppearance="?android:attr/textAppearanceLarge"_x000D_
android:text="My Apps!"_x000D_
android:id="@+id/textView"_x000D_
android:gravity="center"_x000D_
android:layout_marginBottom="20dp"_x000D_
/>_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="SPOTIFY STREAMER"_x000D_
android:id="@+id/button_spotify"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="SCORES"_x000D_
android:id="@+id/button_scores"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_centerInParent="true"_x000D_
android:text="LIBRARY APP"_x000D_
android:id="@+id/button_library"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_centerInParent="true"_x000D_
android:text="BUILD IT BIGGER"_x000D_
android:id="@+id/button_buildit"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_centerInParent="true"_x000D_
android:text="BACON READER"_x000D_
android:id="@+id/button_bacon"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
<Button_x000D_
android:layout_width="220dp"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_centerInParent="true"_x000D_
android:text="CAPSTONE: MY OWN APP"_x000D_
android:id="@+id/button_capstone"_x000D_
android:gravity="center"_x000D_
android:layout_below="@+id/textView"_x000D_
android:padding="20dp"_x000D_
/>_x000D_
_x000D_
</LinearLayout>
_x000D_
If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.
BlockingQueue.java
public class BlockingQueue
{
int item;
boolean available = false;
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
} catch (InterruptedException e) {
}
}
item = value;
available = true;
notifyAll();
}
public synchronized int get()
{
while(available == false)
{
try
{
wait();
}
catch(InterruptedException e){
}
}
available = false;
notifyAll();
return item;
}
}
Consumer.java
package com.sukanya.producer_Consumer;
public class Consumer extends Thread
{
blockingQueue queue;
private int number;
Consumer(BlockingQueue queue,int number)
{
this.queue = queue;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = queue.get();
System.out.println("Consumer #" + this.number+ " got: " + value);
}
}
}
ProducerConsumer_Main.java
package com.sukanya.producer_Consumer;
public class ProducerConsumer_Main
{
public static void main(String args[])
{
BlockingQueue queue = new BlockingQueue();
Producer producer1 = new Producer(queue,1);
Consumer consumer1 = new Consumer(queue,1);
producer1.start();
consumer1.start();
}
}
Your $(magicSelector)
could be $('td', this)
. This will grab all td
that are children of this
, which in your case is each tr
. This is the same as doing $(this).find('td')
.
$('td', this).each(function() {
// Logic
});
printf "oldpassword/nnewpassword/nnewpassword" | passwd user
from r cookbook, where bp is your ggplot:
Remove legend for a particular aesthetic (fill):
bp + guides(fill=FALSE)
It can also be done when specifying the scale:
bp + scale_fill_discrete(guide=FALSE)
This removes all legends:
bp + theme(legend.position="none")
If you don't mind the try-except then...
def touch_dir(folder_path):
try:
os.mkdir(folder_path)
except FileExistsError:
pass
One thing to note though, if a file exists with the same name then it won't work and will fail silently.
The shortest way to write a selector that accesses that specific div is to simply use
[role=main] {
/* CSS goes here */
}
The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.
[role=main] {_x000D_
background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
<span role="main">Hello</span>_x000D_
</div>
_x000D_
Just imagine that the AutoResetEvent
executes WaitOne()
and Reset()
as a single atomic operation.
You could use limitTo
filter with -1
for find the last element
Example :
<div ng-repeat="friend in friends | limitTo: -1">
{{friend.name}}
</div>
You can check whether the connection was lost or not by using this function:-
var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});
Hope it will help you.
This is known as type assertion
in golang, and it is a common practice.
Here is the explanation from a tour of go:
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
NOTE: value i
should be interface type.
Even if i
is an interface type, []i
is not interface type. As a result, in order to convert []i
to its value type, we have to do it individually:
// var items []i
for _, item := range items {
value, ok := item.(T)
dosomethingWith(value)
}
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
The installation of these tools may vary on different OS.
Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.
So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Besides the removal of the github messaging service, usage was often not necessary due to many githubbers communicating with- and advocating twitter.
The advantage is that there is:
It is probably no coincidence that stackoverflow doesn't allow private messaging either, to ensure full transparency. The entire messaging issue is thoroughly discussed on meta-stackoverflow here.
I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log()
is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout
or stderr
with process.stdout.write()
instead of console.log()
, then you'll get the console output from the spawned process 'as is'.
I saw that solution here: Node.js: printing to console without a trailing newline?
Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).
Use:
MessageBoxResult m = MessageBox.Show("The file will be saved here.", "File Save", MessageBoxButton.OKCancel);
if(m == m.Yes)
{
// Do something
}
else if (m == m.No)
{
// Do something else
}
MessageBoxResult is used on Windows Phone instead of DialogResult...
Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)
If you are using python 3.6 or latest, f-string is the best and easy one
print(f"{your_varaible_name}")
Here is the simplest solution I can think of:
let rec distribute e = function
| [] -> [[e]]
| x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
let permute xs = Seq.fold (fun ps x -> List.collect (distribute x) ps) [[]] xs
The distribute
function takes a new element e
and an n
-element list and returns a list of n+1
lists each of which has e
inserted at a different place. For example, inserting 10
at each of the four possible places in the list [1;2;3]
:
> distribute 10 [1..3];;
val it : int list list =
[[10; 1; 2; 3]; [1; 10; 2; 3]; [1; 2; 10; 3]; [1; 2; 3; 10]]
The permute
function folds over each element in turn distributing over the permutations accumulated so far, culminating in all permutations. For example, the 6 permutations of the list [1;2;3]
:
> permute [1;2;3];;
val it : int list list =
[[3; 2; 1]; [2; 3; 1]; [2; 1; 3]; [3; 1; 2]; [1; 3; 2]; [1; 2; 3]]
Changing the fold
to a scan
in order to keep the intermediate accumulators sheds some light on how the permutations are generated an element at a time:
> Seq.scan (fun ps x -> List.collect (distribute x) ps) [[]] [1..3];;
val it : seq<int list list> =
seq
[[[]]; [[1]]; [[2; 1]; [1; 2]];
[[3; 2; 1]; [2; 3; 1]; [2; 1; 3]; [3; 1; 2]; [1; 3; 2]; [1; 2; 3]]]
window.frames['frameNameOrIndex'].location.reload();
If you need to handle error messages using jQuery.AJAX you will need to modify the xhr
function so the responseType
is not being modified when an error happens.
So you will have to modify the responseType
to "blob" only if it is a successful call:
$.ajax({
...
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
...
error: function(xhr, textStatus, errorThrown) {
// Here you are able now to access to the property "responseText"
// as you have the type set to "text" instead of "blob".
console.error(xhr.responseText);
},
success: function(data) {
console.log(data); // Here is "blob" type
}
});
If you debug and place a breakpoint at the point right after setting the xhr.responseType
to "blob" you can note that if you try to get the value for responseText
you will get the following message:
The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
By default structs do not have a ==
operator. You'll have to write your own implementation:
bool MyStruct1::operator==(const MyStruct1 &other) const {
... // Compare the values, and return a bool result.
}
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
onSaveInstanceState()
is a method used to store data before pausing the activity.Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.
onRestoreInstanceState()
is method used to retrieve that data back.Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).
Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause()
method of Activity as a bundle & in onResume()
method call the onRestoreInstanceState()
method .
Please see :
How to use onSavedInstanceState example please
http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/
The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but
for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;
or
What I did so that input didn't take up the whole line, and be able to place the input in a paragraph, I used a span tag and display to inline-block
html:
<span>cluster:
<input class="short-input" type="text" name="cluster">
</span>
css:
span{display: inline-block;}
This might work for you:
printf "%.5s" $TESTSTRINGONE
You should add user settings:
{
"editor.showFoldingControls": "always",
"editor.folding": true,
"editor.foldingStrategy": "indentation",
}
You might try turning off pooling, which is enabled by default. See this discussion for more information.
import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
del csr
Like the other posters have suggested, it sounds like you have a lock contention issue. We faced a similar issue a few weeks back; however, ours was much more intermittent, and often cleared up before we could get a DBA onto the server to run sp_who2 to trace down the issue.
What we ended up doing was implement an e-mail notification if a lock exceeded a certain threshold. Once we put this in place, we were able to identify the processes that were locking, and change the isolation level to read uncommitted where appropriate to fix the issue.
Here's an article that provides an overview of how to configure this type of notification.
If locking turns out to be the issue, and if you're not already doing so, I would suggest looking into configuring row versioning-based isolation levels.
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
If you are talking about AjaxTabControlExtender then set TabIndex of every tabs and set Visible property True/False according to your need.
myTab.Tabs[1].Visible=true/false;
I read through the answers and still felt the need to stress the key point which illuminates the essence of Prepared Statements. Consider two ways to query one's database where user input is involved:
Naive Approach
One concatenates user input with some partial SQL string to generate a SQL statement. In this case the user can embed malicious SQL commands, which will then be sent to the database for execution.
String SQLString = "SELECT * FROM CUSTOMERS WHERE NAME='"+userInput+"'"
For example, malicious user input can lead to SQLString
being equal to "SELECT * FROM CUSTOMERS WHERE NAME='James';DROP TABLE CUSTOMERS;'
Due to the malicious user, SQLString
contains 2 statements, where the 2nd one ("DROP TABLE CUSTOMERS"
) will cause harm.
Prepared Statements
In this case, due to the separation of the query & data, the user input is never treated as a SQL statement, and thus is never executed. It is for this reason, that any malicious SQL code injected would cause no harm. So the "DROP TABLE CUSTOMERS"
would never be executed in the case above.
In a nutshell, with prepared statements malicious code introduced via user input will not be executed!
Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.
A common convention is to put the result of a build into a build
, target
or bin
directory.
The Jenkins archiver can use globs (target/*.jar
) to easily pick up the right file even if you have a unique name per build.
here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.
You can import json files by using the node.js v14 experimental json modules flag. More details here
file.js
import data from './folder/file.json'
export default {
foo () {
console.log(data)
}
}
And you call it with node --experimental-json-modules file.js
These often comes from using pip to "update" system installed pip, and/or having multiple pip installs under user. My solution was to clean out the multiple installed pips under user, reinstall pip repo, then "pip install --user pip" as above.
See: https://github.com/pypa/pip/issues/5599 for an official complete discussion and fixes for the problem.
There are two types of string in python: the traditional str
type and the newer unicode
type. If you type a string literal without the u
in front you get the old str
type which stores 8-bit characters, and with the u
in front you get the newer unicode
type that can store any Unicode character.
The r
doesn't change the type at all, it just changes how the string literal is interpreted. Without the r
, backslashes are treated as escape characters. With the r
, backslashes are treated as literal. Either way, the type is the same.
ur
is of course a Unicode string where backslashes are literal backslashes, not part of escape codes.
You can try to convert a Unicode string to an old string using the str()
function, but if there are any unicode characters that cannot be represented in the old string, you will get an exception. You could replace them with question marks first if you wish, but of course this would cause those characters to be unreadable. It is not recommended to use the str
type if you want to correctly handle unicode characters.
For swift version
func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapDim: CGSize) -> Double {
var bounds = bounds
let WORLD_DIM = CGSize(width: 256, height: 256)
let ZOOM_MAX: Double = 21.0
func latRad(_ lat: Double) -> Double {
let sin2 = sin(lat * .pi / 180)
let radX2 = log10((1 + sin2) / (1 - sin2)) / 2
return max(min(radX2, .pi), -.pi) / 2
}
func zoom(_ mapPx: CGFloat,_ worldPx: CGFloat,_ fraction: Double) -> Double {
return floor(log10(Double(mapPx) / Double(worldPx) / fraction / log10(2.0)))
}
let ne = bounds.northEast
let sw = bounds.southWest
let latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / .pi
let lngDiff = ne.longitude - sw.longitude
let lngFraction = lngDiff < 0 ? (lngDiff + 360) : (lngDiff / 360)
let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
return min(latZoom, lngZoom, ZOOM_MAX)
}
Typically this would be handled by your Subversion server administrator. If that's you and you are using the built-in authentication, then edit your [repository]\conf\passwd
file on your Subversion server machine.
Follow these steps:
Next time you attempt an action that requires credentials you'll be asked for them.
If you're using the command-line svn.exe
use the --no-auth-cache
option so that you can specify alternate credentials without having them cached against your Windows user.
There are a few installs you may need to apply for ASP.NET MVC 5 support in Visual Studio 2012. Update 4 seems to include the Web Tools update now.
You don't have to install the full Windows 8.1 SDK if you are just looking for the option to build web applications, just the .NET Framework 4.5.1 option in the installer. The full install is about 1.1 GB, but just the .NET installer is only 72 MB.
I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;
Instead of;
... AND WPP.COMMENT NOT LIKE '%CORE%' ...
Try;
... AND NOT WPP.COMMENT LIKE '%CORE%' ...
Basically moving the "NOT" the other side of the field I was evaluating worked for me.
Adding on to @shruti's answer
To query grants for all tables in a schema for a given user
select a.tablename,
b.usename,
HAS_TABLE_PRIVILEGE(usename,tablename, 'select') as select,
HAS_TABLE_PRIVILEGE(usename,tablename, 'insert') as insert,
HAS_TABLE_PRIVILEGE(usename,tablename, 'update') as update,
HAS_TABLE_PRIVILEGE(usename,tablename, 'delete') as delete,
HAS_TABLE_PRIVILEGE(usename,tablename, 'references') as references
from pg_tables a,
pg_user b
where schemaname='your_schema_name'
and b.usename='your_user_name'
order by tablename;
Abstract classes are classes that contain one or more abstract methods. Along with abstract methods, Abstract classes can have static, class and instance methods. But in case of interface, it will only have abstract methods not other. Hence it is not compulsory to inherit abstract class but it is compulsory to inherit interface.
A Y-Combinator is another name for a flux capacitor.
I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.
ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.
function addValue(key, value)
if (value == nil) then
removeKey(key)
return
end
_primaryTable[key] = value
_secodaryTable[value] = key
end
function removeKey(key)
local value = _primaryTable[key]
if (value == nil) then
return
end
_primaryTable[key] = nil
_secondaryTable[value] = nil
end
function getValue(key)
return _primaryTable[key]
end
function containsValue(value)
return _secondaryTable[value] ~= nil
end
You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.
If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring
on it for example, and then use that as the key.
Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.
The wording of the question however strongly suggests that you have a large number of items to deal with.
The way of dknaack does not work for me, I found this solution as well:
@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { @onchange = "location = this.value;" })
where
@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
It doesn't work in IE5, but that's not a big issue.
However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
Try this working for Firefox:
driver.manage().window.maximize();
And if you are using python 3.X, you may apply the sorted
function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.
# using *sort method*
mylist.sort(lambda x: x[1])
# using *sorted function*
sorted(mylist, key = lambda x: x[1])
An enumeration is something of an inverse-array. What I believe you want is this:
const char * Week[] = { "", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; // The blank string at the beginning is so that Sunday is 1 instead of 0.
cout << "Today is " << Week[2] << ", enjoy!"; // Or whatever you'de like to do with it.
I've created a simple example tutorial. You can read this and use in your application.
http://ribinsandroidhelper.blogspot.in/2013/03/qr-code-reading-on-your-application.html
Through this link you can download the qrcode library project and import into your workspace and add library to your project
and copy this code to your activity
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(this, contents,Toast.LENGTH_LONG).show();
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
//Handle cancel
}
}
}
It seems to me the last line of your example code should simply be:
Task<Item> itsMe = o as Task<Item>;
Or am I missing something?
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
My preference is for something that:
Stitching together from other answers in this thread, I end up with
select
name, type
from
mysql.proc
where
db = database()
order by
type, name;
... which ends you up with results that look like this:
mysql> select name, type from mysql.proc where db = database() order by type, name;
+------------------------------+-----------+
| name | type |
+------------------------------+-----------+
| get_oldest_to_scan | FUNCTION |
| get_language_prevalence | PROCEDURE |
| get_top_repos_by_user | PROCEDURE |
| get_user_language_prevalence | PROCEDURE |
+------------------------------+-----------+
4 rows in set (0.30 sec)
You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.
Just for the info, this can be done with CSS only with just minor HTML and CSS changes
HTML:
<div class="left">
Hello
</div>
<div class="right">
Hello2
</div>
<div class="center">
<div class="left1">
Bye
</div>
<div class="right1">
Bye1
</div>
</div>
CSS:
.left, .right{
margin:10px;
float:left;
border:1px solid red;
height:60px;
width:60px
}
.left:hover, .right:hover{
border:1px solid blue;
}
.right{
float :right;
}
.center{
float:left;
height:60px;
width:160px
}
.center .left1, .center .right1{
margin:10px;
float:left;
border:1px solid green;
height:60px;
width:58px;
display:none;
}
.left:hover ~ .center .left1 {
display:block;
}
.right:hover ~ .center .right1 {
display:block;
}
and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
For me worked on Windows 10 npm config set prefix %AppData%\npm\node_modules
Change name
attribute in pubspec.yaml
(line 1)
For the name of apk, change android:label
in AndroidManifest.xml
In Docker container atleast one process must be run, then only the container will be running the docker image(ubuntu,httd..etc, whatever it is) at background without exiting
For example in ubuntu docker image ,
To create a new container with detach mode (running background atleast on process),
docker run -d -i -t f63181f19b2f /bin/bash
it will create a new contain for this image(ubuntu) id f63181f19b2f
. The container will run in the detached mode (running in background) at that time a small process tty
bash shell will be running at background. so, container will keep on running untill the bash shell process will killed.
To attach to the running background container,use
docker attach b1a0873a8647
if you want to detach from container without exiting(without killing the bash shell),
By default , you can use ctrl-p,q
. it will come out of container without exiting from the container(running background. that means without killing the bash shell).
You can pass the custom command during attach time to container,
docker attach --detach-keys="ctrl-s" b1a0873a8647
this time ctrl-p,q
escape sequence won't work. instead, ctrl-s
will work for exiting from container. you can pass any key eg, (ctrl-*)
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:
The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.
For example:
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
In this code, you should call stop()
on the thread when you want it to exit, and wait for the thread to exit properly using join()
. The thread should check the stop flag at regular intervals.
There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.
The following code allows (with some restrictions) to raise an Exception in a Python thread:
def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class ThreadWithExc(threading.Thread):
'''A thread class that supports raising an exception in the thread from
another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id
CAREFUL: this function is executed in the context of the caller
thread, to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")
# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id
# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid
# TODO: in python 2.6, there's a simpler way to do: self.ident
raise AssertionError("could not determine the thread's id")
def raiseExc(self, exctype):
"""Raises the given exception type in the context of this thread.
If the thread is busy in a system call (time.sleep(),
socket.accept(), ...), the exception is simply ignored.
If you are sure that your exception should terminate the thread,
one way to ensure that it works is:
t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )
If the exception is to be caught by the thread, you need a way to
check that your thread has caught it.
CAREFUL: this function is executed in the context of the
caller thread, to raise an exception in the context of the
thread represented by this instance.
"""
_async_raise( self._get_my_tid(), exctype )
(Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc
appears to be from an old version of Python.)
As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.
A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.
Yes, you very well can learn C using Visual Studio.
Visual Studio comes with its own C compiler, which is actually the C++ compiler. Just use the .c
file extension to save your source code.
You don't have to be using the IDE to compile C. You can write the source in Notepad, and compile it in command line using Developer Command Prompt which comes with Visual Studio.
Open the Developer Command Prompt, enter the directory you are working in, use the cl
command to compile your C code.
For example, cl helloworld.c
compiles a file named helloworld.c
.
Refer this for more information: Walkthrough: Compiling a C Program on the Command Line
Hope this helps
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character