git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Honestly this is bad advice from npm
. An installation can run arbitrary scripts and running it with sudo
can be extremely dangerous! You could do sudo npm install -g less
to install it globally, but instead I would recommend updating your npm settings:
#~/.npmrc
prefix=~/.npm_modules
Then you can update your path:
#~/.bashrc or ~/.zshrc, etc.
export PATH=$PATH:$HOME/.npm_modules/bin
Then you don't require root permissions to perform the installation and you can still use the binary.
This would only apply to your user, however. If you want the entire system to be able to use the module you would have to tell everyone to add your path. More complicated and robust solutions would include adding a folder with node modules / binaries that a group could install to and adding that to everyone's path.
Use ToLower()
first, than CultureInfo.CurrentCulture.TextInfo.ToTitleCase
on the result to get the correct output.
//---------------------------------------------------------------
// Get title case of a string (every word with leading upper case,
// the rest is lower case)
// i.e: ABCD EFG -> Abcd Efg,
// john doe -> John Doe,
// miXEd CaSING - > Mixed Casing
//---------------------------------------------------------------
public static string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
>>> u"\u00b0"
u'\xb0'
>>> print _
°
BTW, all I did was search "unicode degree" on Google. This brings up two results: "Degree sign U+00B0" and "Degree Celsius U+2103", which are actually different:
>>> u"\u2103"
u'\u2103'
>>> print _
?
At this point method
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();
is deprecated.
You should use
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
and getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
I have also faced the same issue and solved it later. first of all execute the artisan command:
php artisan cache:clear
And after that restart the project. Hope it will help.
I did this differently than everyone else here did. I'm new to Java, so maybe my solution is poor.
Date now = new Date();
Date midnightToday = new Date(now.getYear(), now.getMonth(), now.getDate());
I'm not sure this works yet, but either way, I'd appreciate any feedback on this solution.
I'm confused by the statement above that you can calculate tomorrow by calling:
c.add(Calendar.DAY_OF_MONTH, 1);
If you add 1 to the day of the month and it's the 31st day, don't you get the 32nd day of the month?
Why are times/dates not all based on UTC in Java? I would think Timezones should only be needed when used with i/o, but internally should always be used in UTC. However, the classes seem to include Timezone info which seems not only wasteful, but prone to coding errors.
printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.
The following is an another example of print stack of the Exception in Java.
public class Demo {
public static void main(String[] args) {
try {
ExceptionFunc();
} catch(Throwable e) {
e.printStackTrace();
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception in Java...");
StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",5)
};
t.setStackTrace(trace);
throw t;
}
}
java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)
I written also a URL validation function base on rfc1738 and rfc3986 to check http and https urls. I try to hold this modular, so it can be better maintained and adapted to own requirements.
The RegExp in one line is show at end of this post.
The RegExp accept HTTP and HTTPS URLs with some international domain or IPv4 number. IPv6 is not supported yet.
window.isValidURL = (function() {// wrapped in self calling function to prevent global pollution
//URL pattern based on rfc1738 and rfc3986
var rg_pctEncoded = "%[0-9a-fA-F]{2}";
var rg_protocol = "(http|https):\\/\\/";
var rg_userinfo = "([a-zA-Z0-9$\\-_.+!*'(),;:&=]|" + rg_pctEncoded + ")+" + "@";
var rg_decOctet = "(25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|[1-9][0-9]|[0-9])"; // 0-255
var rg_ipv4address = "(" + rg_decOctet + "(\\." + rg_decOctet + "){3}" + ")";
var rg_hostname = "([a-zA-Z0-9\\-\\u00C0-\\u017F]+\\.)+([a-zA-Z]{2,})";
var rg_port = "[0-9]+";
var rg_hostport = "(" + rg_ipv4address + "|localhost|" + rg_hostname + ")(:" + rg_port + ")?";
// chars sets
// safe = "$" | "-" | "_" | "." | "+"
// extra = "!" | "*" | "'" | "(" | ")" | ","
// hsegment = *[ alpha | digit | safe | extra | ";" | ":" | "@" | "&" | "=" | escape ]
var rg_pchar = "a-zA-Z0-9$\\-_.+!*'(),;:@&=";
var rg_segment = "([" + rg_pchar + "]|" + rg_pctEncoded + ")*";
var rg_path = rg_segment + "(\\/" + rg_segment + ")*";
var rg_query = "\\?" + "([" + rg_pchar + "/?]|" + rg_pctEncoded + ")*";
var rg_fragment = "\\#" + "([" + rg_pchar + "/?]|" + rg_pctEncoded + ")*";
var rgHttpUrl = new RegExp(
"^"
+ rg_protocol
+ "(" + rg_userinfo + ")?"
+ rg_hostport
+ "(\\/"
+ "(" + rg_path + ")?"
+ "(" + rg_query + ")?"
+ "(" + rg_fragment + ")?"
+ ")?"
+ "$"
);
// export public function
return function (url) {
if (rgHttpUrl.test(url)) {
return true;
} else {
return false;
}
};
})();
RegExp in one line:
var rg = /^(http|https):\/\/(([a-zA-Z0-9$\-_.+!*'(),;:&=]|%[0-9a-fA-F]{2})+@)?(((25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|[1-9][0-9]|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9]|[1-9][0-9]|[0-9])){3})|localhost|([a-zA-Z0-9\-\u00C0-\u017F]+\.)+([a-zA-Z]{2,}))(:[0-9]+)?(\/(([a-zA-Z0-9$\-_.+!*'(),;:@&=]|%[0-9a-fA-F]{2})*(\/([a-zA-Z0-9$\-_.+!*'(),;:@&=]|%[0-9a-fA-F]{2})*)*)?(\?([a-zA-Z0-9$\-_.+!*'(),;:@&=\/?]|%[0-9a-fA-F]{2})*)?(\#([a-zA-Z0-9$\-_.+!*'(),;:@&=\/?]|%[0-9a-fA-F]{2})*)?)?$/;
After the latest automatic Java update, I could not run Java from the command prompt.
My path variable had 'C:\ProgramData\Oracle\Java\javapath;'
I could not cd into 'C:\ProgramData\Oracle\Java\javapath;' from the command prompt window, since it did not exist.
I removed C:\ProgramData\Oracle\Java\javapath;' from the path variable and replaced it with 'C:\Program Files\Java\jre1.8.0_141\bin;'
Alternative Swift solution:
static func topMostController() -> UIViewController {
var topController = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topController?.presentedViewController != nil) {
topController = topController?.presentedViewController
}
return topController!
}
Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:
$contents = (string) $response->getBody();
You can also do it with
$contents = $response->getBody()->getContents();
The difference between the two approaches is that getContents
returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind
or seek
.
$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.
$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses
The solution is pretty easy actually:
<button style="border:1px solid black; background-color: transparent;">Test</button>
This is doing an inline style. You're defining the border to be 1px, solid line, and black in color. The background color is then set to transparent.
UPDATE
Seems like your ACTUAL question is how do you prevent the border after clicking on it. That can be resolved with a CSS pseudo selector: :active
.
button {
border: none;
background-color: transparent;
outline: none;
}
button:focus {
border: none;
}
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
Add above code in API gateway under GET-Integration Request> mapping section.
Push object into your array. Try this:
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<{name: string, empoloyeeID: number}> = [];
constructor() {}
ngOnInit() {}
onEmpCreate(){
console.log(this.name,this.empoloyeeID);
this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
this.name = "";
this.empoloyeeID = 0;
}
}
You can tailor how your object is represented as a string by implementing a __toString()
method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;
, or automatic echo $myObject
) you can control what is included and the string format.
If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.
Some code to demonstrate the difference:
class MyObject {
protected $name = 'JJ';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
My name is: JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
http.get(options).on('response', function (response) {
var body = '';
var i = 0;
response.on('data', function (chunk) {
i++;
body += chunk;
console.log('BODY Part: ' + i);
});
response.on('end', function () {
console.log(body);
console.log('Finished');
});
});
Changes to this, which works. Any comments?
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Here are some of my suggestions:
dput
, so others can help you more easilyinstall.package()
unless it is really necessary, people will understand if you just use require
or library
Try to be concise,
All these are part of a reproducible example.
serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.
As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.
67.225.235.59 somerandomservice.com www.somerandomservice.com
Based on @Fletcher Johns answer I came up with:
open class AddressView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {
protected lateinit var countryInputLayout: TextInputLayout
protected lateinit var countryAutoCompleteTextView: CountryAutoCompleteTextView
protected lateinit var cityInputLayout: TextInputLayout
protected lateinit var cityEditText: CityEditText
protected lateinit var postCodeInputLayout: TextInputLayout
protected lateinit var postCodeEditText: PostCodeEditText
protected lateinit var streetInputLayout: TextInputLayout
protected lateinit var streetEditText: StreetEditText
init {
initView()
}
private fun initView() {
val view = inflate(context, R.layout.view_address, this)
orientation = VERTICAL
countryInputLayout = view.findViewById(R.id.countryInputLayout)
countryAutoCompleteTextView = view.findViewById(R.id.countryAutoCompleteTextView)
streetInputLayout = view.findViewById(R.id.streetInputLayout)
streetEditText = view.findViewById(R.id.streetEditText)
cityInputLayout = view.findViewById(R.id.cityInputLayout)
cityEditText = view.findViewById(R.id.cityEditText)
postCodeInputLayout = view.findViewById(R.id.postCodeInputLayout)
postCodeEditText = view.findViewById(R.id.postCodeEditText)
}
// Declare your direct and indirect child views that need to be saved
private val childrenToSave get() = mapOf<String, View>(
"coutryIL" to countryInputLayout,
"countryACTV" to countryAutoCompleteTextView,
"streetIL" to streetInputLayout,
"streetET" to streetEditText,
"cityIL" to cityInputLayout,
"cityET" to cityEditText,
"postCodeIL" to postCodeInputLayout,
"postCodeET" to postCodeEditText,
)
private var viewIds: HashMap<String, Int>? = null
override fun onSaveInstanceState(): Parcelable? {
// Create a bundle to put super parcelable in
val bundle = Bundle()
bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState())
// Store viewIds in the bundle - initialize if necessary.
if (viewIds == null) {
childrenToSave.values.forEach { view -> view.id = generateViewId() }
viewIds = HashMap<String, Int>(childrenToSave.mapValues { (key, view) -> view.id })
}
bundle.putSerializable(STATE_VIEW_IDS, viewIds)
return bundle
}
override fun onRestoreInstanceState(state: Parcelable?) {
// We know state is a Bundle:
val bundle = state as Bundle
// Get mViewIds out of the bundle
viewIds = bundle.getSerializable(STATE_VIEW_IDS) as HashMap<String, Int>
// For each id, assign to the view of same index
if (viewIds != null) {
viewIds!!.forEach { (key, id) -> childrenToSave[key]!!.id = id }
}
super.onRestoreInstanceState(bundle.getParcelable(SUPER_INSTANCE_STATE))
}
companion object {
private const val SUPER_INSTANCE_STATE = "saved_instance_state_parcelable"
private const val STATE_VIEW_IDS = "state_view_ids"
}
}
If you dont have a id or seed, like its its for a values list in insert:
REPLACE(RAND(), '.', '')
You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:
p => ({ foo: 'bar' });
You don't need to wrap any other expression into parentheses:
p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;
and so on.
Reference: MDN - Returning object literals
Due to @zerkems comment:
i should convert my strings to JSON object and then call the equal method:
var x = eval("(" + remoteJSON + ')');
var y = eval("(" + localJSON + ')');
function jsonequals(x, y) {
// If both x and y are null or undefined and exactly the same
if ( x === y ) {
return true;
}
// If they are not strictly equal, they both need to be Objects
if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {
return false;
}
// They must have the exact same prototype chain, the closest we can do is
// test the constructor.
if ( x.constructor !== y.constructor ) {
return false;
}
for ( var p in x ) {
// Inherited properties were tested using x.constructor === y.constructor
if ( x.hasOwnProperty( p ) ) {
// Allows comparing x[ p ] and y[ p ] when set to undefined
if ( ! y.hasOwnProperty( p ) ) {
return false;
}
// If they have the same strict value or identity then they are equal
if ( x[ p ] === y[ p ] ) {
continue;
}
// Numbers, Strings, Functions, Booleans must be strictly equal
if ( typeof( x[ p ] ) !== "object" ) {
return false;
}
// Objects and Arrays must be tested recursively
if ( !equals( x[ p ], y[ p ] ) ) {
return false;
}
}
}
for ( p in y ) {
// allows x[ p ] to be set to undefined
if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {
return false;
}
}
return true;
}
See Davion's anwser in this post: https://stackoverflow.com/a/26429849/1804068
HTML:
<div class="parent">
<span id="mySpan">Something in English</span>
</div>
JQUERY
$('#mySpan').animate({'opacity': 0}, 400, function(){
$(this).html('Something in Spanish').animate({'opacity': 1}, 400);
});
The code below creates a set from an array and then, using the ...
operator.
var arr=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,];
var set=new Set(arr);
let setarr=[...set];
console.log(setarr);
This question is old, but with C++11 we got a new way to check for a functions existence (or existence of any non-type member, really), relying on SFINAE again:
template<class T>
auto serialize_imp(std::ostream& os, T const& obj, int)
-> decltype(os << obj, void())
{
os << obj;
}
template<class T>
auto serialize_imp(std::ostream& os, T const& obj, long)
-> decltype(obj.stream(os), void())
{
obj.stream(os);
}
template<class T>
auto serialize(std::ostream& os, T const& obj)
-> decltype(serialize_imp(os, obj, 0), void())
{
serialize_imp(os, obj, 0);
}
Now onto some explanations. First thing, I use expression SFINAE to exclude the serialize(_imp)
functions from overload resolution, if the first expression inside decltype
isn't valid (aka, the function doesn't exist).
The void()
is used to make the return type of all those functions void
.
The 0
argument is used to prefer the os << obj
overload if both are available (literal 0
is of type int
and as such the first overload is a better match).
Now, you probably want a trait to check if a function exists. Luckily, it's easy to write that. Note, though, that you need to write a trait yourself for every different function name you might want.
#include <type_traits>
template<class>
struct sfinae_true : std::true_type{};
namespace detail{
template<class T, class A0>
static auto test_stream(int)
-> sfinae_true<decltype(std::declval<T>().stream(std::declval<A0>()))>;
template<class, class A0>
static auto test_stream(long) -> std::false_type;
} // detail::
template<class T, class Arg>
struct has_stream : decltype(detail::test_stream<T, Arg>(0)){};
And on to explanations. First, sfinae_true
is a helper type, and it basically amounts to the same as writing decltype(void(std::declval<T>().stream(a0)), std::true_type{})
. The advantage is simply that it's shorter.
Next, the struct has_stream : decltype(...)
inherits from either std::true_type
or std::false_type
in the end, depending on whether the decltype
check in test_stream
fails or not.
Last, std::declval
gives you a "value" of whatever type you pass, without you needing to know how you can construct it. Note that this is only possible inside an unevaluated context, such as decltype
, sizeof
and others.
Note that decltype
is not necessarily needed, as sizeof
(and all unevaluated contexts) got that enhancement. It's just that decltype
already delivers a type and as such is just cleaner. Here's a sizeof
version of one of the overloads:
template<class T>
void serialize_imp(std::ostream& os, T const& obj, int,
int(*)[sizeof((os << obj),0)] = 0)
{
os << obj;
}
The int
and long
parameters are still there for the same reason. The array pointer is used to provide a context where sizeof
can be used.
If one want to make executable hello.py
first find the path where python is in your os with : which python
it usually resides under "/usr/bin/python" folder.
at the very first line of hello.py
one should add : #!/usr/bin/python
then through linux command chmod
one should just make it executable like : chmod +x hello.py
and execute with ./hello.py
I don't think it actually does much, it looks like it's just a cache for string literals. If you have multiple Strings who's values are the same, they'll all point to the same string literal in the string pool.
String s1 = "Arul"; //case 1
String s2 = "Arul"; //case 2
In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.
if(s1 == s2) System.out.println("equal"); //Prints equal.
String n1 = new String("Arul");
String n2 = new String("Arul");
if(n1 == n2) System.out.println("equal"); //No output.
Thought I'd add the Centos installs:
sudo yum -y install gcc gcc-c++
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel
Check python version:
python3 -V
Create virtualenv:
virtualenv -p python3 venv
Text wrapping is not part of SVG1.1, the currently implemented spec. You should rather use HTML via the <foreignObject/>
element.
<svg ...>
<switch>
<foreignObject x="20" y="90" width="150" height="200">
<p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
</foreignObject>
<text x="20" y="20">Your SVG viewer cannot display html.</text>
</switch>
</svg>
Get and set with default values.
public enum Status {
STATUS_A("Status A"), STATUS_B("Status B"),
private String status;
Status(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:
- Passing an object does not copy the object.
- An object passed to a function can have its members modified by the function.
- A primitive value passed to a function cannot be modified by the function. A copy is made.
In my book that's called passing by reference.
— Brian Bi - Which programming languages are pass by reference?
Here is a rebuttal to this:
1.
Find out where Git thinks 'origin/master' is usinggit-remote
git remote show origin
..which will return something like..
* remote origin
URL: [email protected]:~/something.git
Remote branch merged with 'git pull' while on branch master
master
Tracked remote branch
master
A remote is basically a link to a remote repository. When you do..
git remote add unfuddle [email protected]/myrepo.git
git push unfuddle
..git will push changes to that address you added. It's like a bookmark, for remote repositories.
When you run git status
, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to "origin", both will be in sync, so you wont get that message.
2.
If it's somewhere else, how do I turn my laptop into the 'origin/master'?
There is no point in doing this. Say "origin" is renamed to "laptop" - you never want to do git push laptop
from your laptop.
If you want to remove the origin remote, you do..
git remote rm origin
This wont delete anything (in terms of file-content/revisions-history). This will stop the "your branch is ahead by.." message, as it will no longer compare your repository with the remote (because it's gone!)
One thing to remember is that there is nothing special about origin
, it's just a default name git uses.
Git does use origin
by default when you do things like git push
or git pull
. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as "origin":
git remote rm origin
git remote add origin [email protected]:subdomain/abbreviation.git
or do the above in one command using set-url:
git remote set-url origin [email protected]:subdomain/abbreviation.git
Then you can simply do git push
or git pull
to update, instead of git push unfuddle master
I've searched far and wide for a solution to this problem for a long time. Ideally we want to have the child greater than the parent, but without knowing the constraints of the parent in advance.
And I finally found a brilliant generic answer here. Copying it verbatim:
The idea here is: push the container to the exact middle of the browser window with left: 50%;, then pull it back to the left edge with negative -50vw margin.
.child-div {
width: 100vw;
position: relative;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}
If you're OK with viewing it as XML:
DECLARE @xmltmp xml = (SELECT * FROM table FOR XML AUTO)
PRINT CONVERT(NVARCHAR(MAX), @xmltmp)
While the OP's question as asked doesn't necessarily require this, it's useful if you got here looking to print multiple rows/columns (within reason).
you shoud do like this form your code
DataGridView.DataSource = yourlist;
DataGridView.DataBind();
How about this?
def MultiColumnLabelEncode(choice, columns, X):
LabelEncoders = []
if choice == 'encode':
for i in enumerate(columns):
LabelEncoders.append(LabelEncoder())
i=0
for cols in columns:
X[:, cols] = LabelEncoders[i].fit_transform(X[:, cols])
i += 1
elif choice == 'decode':
for cols in columns:
X[:, cols] = LabelEncoders[i].inverse_transform(X[:, cols])
i += 1
else:
print('Please select correct parameter "choice". Available parameters: encode/decode')
It is not the most efficient, however it works and it is super simple.
An answer to your Question from 2019:
It depends on what version of ECMAScript you use.
Pre ES6:
Use any of the answers below, e.g.:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
For ES6 (ES 2015):
You should use a Map
object, which has the entries()
function:
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
For ES8 (ES 2017):
Object.entries()
was introduced:
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
Simply follow the instructions given here:
Example install:
sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs
It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the
add-apt-repository
command to work:sudo apt-get install software-properties-common
As of Node.js v0.10.0, the nodejs package from Chris Lea's repo includes both npm and nodejs-dev.
Don't give sudo apt-get install nodejs npm
. Just sudo apt-get install nodejs
.
I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,
android avd
Once the emulator is running, you can check with adb devices
if the emulator shows up.
Then you can simply use
react-native run-android
to run the app on the emulator.
Make sure you've platform tools installed to be able to use adb
. Or you can use
brew install android-platform-tools
It should be enough to do:
$this->validate($request, [
'password' => 'sometimes,min:6,confirmed,required_with:password_confirmed',
]);
Make password optional, but if present requires a password_confirmation that matches, also make password required only if password_confirmed is present
You can check the output of a TensorObject without running the graph in a session, by enabling eager execution.
Simply add the following two lines of code:
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()
right after you import tensorflow
.
The output of print product
in your example will now be:
tf.Tensor([[ 12.]], shape=(1, 1), dtype=float32)
Note that as of now (November 2017) you'll have to install a Tensorflow nightly build to enable eager execution. Pre-built wheels can be found here.
To avoid this warning, do not use:
async: false
in any of your $.ajax()
calls. This is the only feature of XMLHttpRequest
that's deprecated.
The default is async: true
, so if you never use this option at all, your code should be safe if the feature is ever really removed.
However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false
and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.
Notice that the Fetch
API that's replacing XMLHttpRequest
does not even offer a synchronous option.
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
TL-DR
docker ps --no-trunc
and docker inspect CONTAINER
provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR}
because container environment variables are not printed as resolved.
To overcome that, docker inspect CONTAINER
has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env
property.
docker ps
and docker inspect
provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh
) and not the "real" program started by the container. To get information on that, requesting process information with ps
or /proc/1/cmdline
help.
1) docker ps --no-trunc
It prints the entrypoint and the command executed for all running containers.
While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO
or ${FOO}
).
If our containers use env variables, it may be not enough.
For example, run an alpine container :
docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'
When use docker -ps such as :
docker ps -a --filter name=alpine-example --no-trunc
It prints :
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5b064a6de6d8417... alpine:latest "sh -c 'ls $MY_VAR'" 2 minutes ago Exited (0) 2 minutes ago alpine-example
We see the command passed to the entrypoint : sh -c 'ls $MY_VAR'
but $MY_VAR
is indeed not resolved.
2) docker inspect CONTAINER
When we inspect the alpine-example container :
docker inspect alpine-example | grep -4 Cmd
The command is also there but we don't still see the env variable value :
"Cmd": [
"sh",
"-c",
"ls $MY_VAR"
],
In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :
docker inspect alpine-example | grep -4 -E "Cmd|Env"
That prints :
"Env": [
"MY_VAR=/var",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"sh",
"-c",
"ls $MY_VAR"
]
A more docker way would be to use the --format
flag of docker inspect
that allows to specify JSON attributes to render :
docker inspect --format '{{.Name}} {{.Config.Cmd}} {{ (.Config.Env) }}' alpine-example
That outputs :
/alpine-example [sh -c ls $MY_VAR] [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]
3) Retrieve the started process from the container itself for running containers
The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh
) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh"
.
For PostgreSQL that is "docker-entrypoint.sh postgres"
.
To get more information, we could execute on a running container
docker exec CONTAINER ps aux
.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :
docker exec CONTAINER ps -1
I specify 1
because the process executed by the entrypoint is generally the one with the 1
id.
Without ps
, we could still find the information in /proc/1/cmdline
(in most of Linux distros but not all). For example :
docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo
If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is :
: execute ps -PID
where PID is the local process created by the Docker daemon to run the container such as :
ps -$(docker container inspect --format '{{.State.Pid}}' CONTAINER)
User-friendly formatting with docker ps
docker ps --no-trunc
is not always easy to read.
Specifying columns to print and in a tabular format may make it better :
docker ps --no-trunc --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"
Create an alias may help :
alias dps='docker ps --no-trunc --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'
If you want to use a link then: in the html have:
<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>
in the typescript file
public openLineItems() {
if (this.$stateParams.id == 0) {
this.Flash.create('warning', "Need to save order!", 3000);
return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);
}
I hope you see this example helpful as it was for me along with the other answers.
You may want to take your argument a step further and talk about design patterns - and you can find out why he'd want to bother trying to inherit from multiple classes in c# if he even could
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance = this;
}
public static MainActivity getInstance() {
return instance;
}
public void myMethod() {
// do something...
}
)
AnotherClass.java
public Class AnotherClass() {
// call this method
MainActivity.getInstance().myMethod();
}
Follow these steps if you're on openSuse or SUSE.
Install php7 if it's not already installed.
zypper in php7
If you have php7 installed, update it with:
zypper update php7
Install php7-sockets
zypper in php7-sockets
For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.
You may wanna look into Windows/System32 folder for the following files: - java.exe - javaw.exe - javaws.exe
Because, the path variable is including these files, you can get a headache trying to figure out why the java -version or javac -version keeps pointing to the old JAVA_HOME: rename those files, take out the extension with an underscore, for instance. And then, you only will have to create the JAVA_HOME variable, add it to the path variable (e.g., %JAVA_HOME%) and append the "\bin" particle. This way you need to only change the JAVA_HOME variable pointing to different JRE or JDK and have multiple installations of java just by setting JAVA_HOME.
This also means that it is better to install Java manually, without an installer, so you are able to toy with it.
Perhaps the sched module will meet your needs.
Alternatively, consider using a Timer object.
import operator
To sort the list of dictionaries by key='name':
list_of_dicts.sort(key=operator.itemgetter('name'))
To sort the list of dictionaries by key='age':
list_of_dicts.sort(key=operator.itemgetter('age'))
Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:
// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');
// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';
// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
// Parse the request URL. Relative URLs require an origin explicitly.
const url = new URL(request.url, serverOrigin);
// Parse the URL query. The leading '?' has to be removed before this.
const query = parseQuery(url.search.substr(1));
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(`Hello, ${query.name}!\n`);
});
// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);
// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);
If you run the script above, you can test the server response like this, for example:
curl -q http://localhost:8000/status?name=ryan
Hello, ryan!
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
What element is used for the part with a green background? Just type the name of the element without "<" and ">" characters. For example type P, not <P>
if the answer is the <P>
element.
When your React app is massive, it really takes time for it to get up and running after the page has been loaded. Say, you mount your React part of the app to #app
. Usually, this element in your index.html is simply an empty div:
<div id="app"></div>
What you can do instead is put some styling and a bunch of images there to make it look better between page load and initial React app rendering to DOM:
<div id="app">
<div class="logo">
<img src="/my/cool/examplelogo.svg" />
</div>
<div class="preload-title">
Hold on, it's loading!
</div>
</div>
After the page loads, user will immediately see the original content of index.html. Shortly after, when React is ready to mount the whole hierarchy of rendered components to this DOM node, user will see the actual app.
Note class
, not className
. It's because you need to put this into your html file.
If you use SSR, things are less complicated because the user will actually see the real app right after the page loads.
Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
public static void main(String[] args) {
int[] toyNumber = new int[] {5};
NewClass temp = new NewClass();
temp.play(toyNumber);
System.out.println("Toy number in main " + toyNumber[0]);
}
void play(int[] toyNumber){
System.out.println("Toy number in play " + toyNumber[0]);
toyNumber[0]++;
System.out.println("Toy number in play after increement " + toyNumber[0]);
}
The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:
public UserTest UserTest { get; set; }
public EmailTest EmailTest { get; set; }
I post the code I've tested if someone is interested. Regards
using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
#region example2
public class UserTest
{
public int UserTestID { get; set; }
public string UserTestname { get; set; }
public string Password { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
public static void DoSomeTest(ApplicationDbContext context)
{
for (int i = 0; i < 5; i++)
{
var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
var address = context.EmailTest.Add(new EmailTest() { Address = "address@" + i });
}
context.SaveChanges();
foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
{
foreach (var address in context.EmailTest)
{
user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
}
}
context.SaveChanges();
}
}
public class EmailTest
{
public int EmailTestID { get; set; }
public string Address { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}
public class UserTestEmailTest
{
public int UserTestID { get; set; }
public UserTest UserTest { get; set; }
public int EmailTestID { get; set; }
public EmailTest EmailTest { get; set; }
public int n1 { get; set; }
public int n2 { get; set; }
//Call this code from ApplicationDbContext.ConfigureMapping
//and add this lines as well:
//public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
//public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
{
// Primary keys
builder.Entity<UserTest>().HasKey(q => q.UserTestID);
builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);
builder.Entity<UserTestEmailTest>().HasKey(q =>
new
{
q.UserTestID,
q.EmailTestID
});
// Relationships
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.EmailTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.EmailTestID);
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.UserTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.UserTestID);
}
}
#endregion
Another alternative way using get method with requests:
import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')
To check is variable is set you need to use isset function.
$lorem = 'potato';
if(isset($lorem)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
if(isset($ipsum)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
this code will print:
isset true
isset false
read more in https://php.net/manual/en/function.isset.php
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
The idea I generally use when working with transactions looks like this (semi-pseudo-code):
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$db->query('first query');
$db->query('second query');
$db->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (\Throwable $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
throw $e; // but the error must be handled anyway
}
PDO::setAttribute
PDO::ATTR_ERRMODE
and PDO::ERRMODE_EXCEPTION
For example, quite often you'll have a couple of queries before the transaction (before the begin
) and another couple of queries after the transaction (after either commit
or rollback
) and you'll want those queries executed no matter what happened (or not) in the transaction.
To dismiss or cancel AlertDialog.Builder
dialog.setNegativeButton("?????", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
you call dismiss() on the dialog interface
For generating the publish output provide one more parameter. msbuild example.sln /p:publishprofile=profilename /p:deployonbuild=true /p:configuration=debug/or any
If these are elements naturally in the tab order like buttons and anchors, removing them from the tab order with tabindex="-1"
is kind of an accessibility smell. If they're providing duplicate functionality removing them from the tab order is ok, and consider adding aria-hidden="true"
to these elements so assistive technologies will ignore them.
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
well If you have 150 columns then I think that UNPIVOT is not an option. So you could use xml trick
;with CTE1 as (
select ID, EntityID, (select t.* for xml raw('row'), type) as Data
from temp1 as t
), CTE2 as (
select
C.id, C.EntityID,
F.C.value('local-name(.)', 'nvarchar(128)') as IndicatorName,
F.C.value('.', 'nvarchar(max)') as IndicatorValue
from CTE1 as c
outer apply c.Data.nodes('row/@*') as F(C)
)
select * from CTE2 where IndicatorName like 'Indicator%'
You could also write dynamic SQL, but I like xml more - for dynamic SQL you have to have permissions to select data directly from table and that's not always an option.
UPDATE
As there a big flame in comments, I think I'll add some pros and cons of xml/dynamic SQL. I'll try to be as objective as I could and not mention elegantness and uglyness. If you got any other pros and cons, edit the answer or write in comments
cons
pros
inserted
and deleted
tables inside your trigger (not possible with dynamic at all);Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.
I've done this plenty of times in VS 2005 without any problems.
Here is a simpler method!
First: write a shell script and save it a .sh here is an example
#!/bin/bash
Icoff='/home/akbar/keyboardONOFF/icon/Dt6hQ.png'
id=13
fconfig=".keyboard"
echo "disabled" > $fconfig
xinput float $id
notify-send -i $Icoff "Internal Keyboard disabled";
this script will disable the internal keyboard at startup.
Second: Open the application " Startup Application Preferences"
Third: click Add. fourth: in the NAME section give a name. fifth: In the command section browse to your .sh . sixth: edit your command section to:
bash <space> path/to/file/<filename>.sh <space> --start
seventh: click Add. Thats it! Finished!
Now confirm by rebooting your pc.
cheers!
setTimeout will execute some code after a delay of some period of time (measured in milliseconds). However, an important note: because of the nature of javascript, the rest of the code continues to run after the timer is setup:
$('#someid').addClass("load");
setTimeout(function(){
$('#someid').addClass("done");
}, 2000);
// Any code here will execute immediately after the 'load' class is added to the element.
Both std::string
and std::vector<T>
have constructors initializing the object to be empty. You could use std::vector<unsigned char>()
but I'd remove the initializer.
We should avoid using traditional for loop while working with Collections. The simple reason what I will give is that the complexity of for loop is of the order O(sqr(n)) and complexity of Iterator or even the enhanced for loop is just O(n). So it gives a performence difference.. Just take a list of some 1000 items and print it using both ways. and also print the time difference for the execution. You can sees the difference.
For QT 5.* if you face error at Kits, like No Valid Kits Found
, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.
Just go to your OS Terminal and write sudo apt-get install qt5-default
, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.
You say you don't necessarily know that 'key2' is in position [1]. Well, it's not. Position 1 would be occupied by myHash[1].
You're abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript's array methods work with the numbered properties only.
The first thing you should do is switch to objects rather than arrays. You don't have a good reason to use an array here rather than an object, so don't do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.
You can, of course, put a hash (object) into an array if you like.
myhash[1]={"key1","brightOrangeMonkey"};
I'll try summarize the great answer by Alex and the jlmendezbonini's point, adding a modification that will make everything ARC compatible (so far it's not since ARC will complain since you should return id
, which means "any object", but BOOL
is not an object type).
- (BOOL) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
// begin feeding the world's children...
// it's all going well until....
if (ohNoImOutOfMonies) {
// sad, we can't solve world hunger, but we can let people know what went wrong!
// init dictionary to be used to populate error object
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
if (error != NULL) {
// populate the error object with the details
*error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return NO;
}
// wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
return YES;
}
Now instead of checking for the return value of our method call, we check whether error
is still nil
. If it's not we have a problem.
// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
// inspect error
NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.
var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);
Use the below function
/**
* Format a time from a given format to given target format
*
* @param inputFormat
* @param inputTimeStamp
* @param outputFormat
* @return
* @throws ParseException
*/
private static String TimeStampConverter(final String inputFormat,
String inputTimeStamp, final String outputFormat)
throws ParseException {
return new SimpleDateFormat(outputFormat).format(new SimpleDateFormat(
inputFormat).parse(inputTimeStamp));
}
Sample Usage is as Following:
try {
String inputTimeStamp = "08/16/2011";
final String inputFormat = "MM/dd/yyyy";
final String outputFormat = "EEE MMM dd HH:mm:ss z yyyy";
System.out.println(TimeStampConverter(inputFormat, inputTimeStamp,
outputFormat));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
https://developer.mozilla.org/en-US/docs/Web/CSS/initial
use initial property in css3
<p style="color:red!important">
this text is red
<em style="color:initial">
this text is in the initial color (e.g. black)
</em>
this is red again
</p>
I don't think that you really want an iframe, do you?
Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?
For your white box / extra space issue, try
style="display: none;"
instead of
style="visibility: hidden;"
Add this to your gradle file.
implementation 'com.android.support:support-annotations:27.1.1'
This works really fine:
\+?\d[\d -]{8,12}\d
Matches:
03598245785
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
987-98723-9898
+91 98780 98802
06421223054
9934-05-4851
WAQU9876567892
ABCD9876541212
98723-98765
Does NOT match:
2343
234-8700
1 234 765
The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean()
function. Therefore, check your data using str(data.frame&column)
function to see what data type you have, and convert it to numeric format if necessary.
For example, if your data is Character convert it with as.numeric(data.frame$column)
, or as a factor with as.numeric(as.character(data.frame$column))
. The mean function does not work with types other than numeric.
There are excellent answers, but if you want to color your console logs you can use the pattern :
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
[%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
The full log4j2 file is:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="APP_LOG_ROOT">/opt/test/log</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%style{%date{DEFAULT}}{yellow}
[%t] %highlight{%-5level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green} %logger{36} - %message\n"/>
</Console>
<RollingFile name="XML_ROLLING_FILE_APPENDER"
fileName="${APP_LOG_ROOT}/appName.log"
filePattern="${APP_LOG_ROOT}/appName-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="%d{DEFAULT} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<SizeBasedTriggeringPolicy size="19500KB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Logger name="com.compName.projectName" level="debug">
<AppenderRef ref="XML_ROLLING_FILE_APPENDER"/>
</Logger>
</Loggers>
</Configuration>
use this filter:
(dns.flags.response == 0) and (ip.src == 159.25.78.7)
what this query does is it only gives dns queries
originated from your ip
Optimization of the accepted answer:
The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:
import requests
from pandas import json_normalize
url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
response = requests.get(url)
dictr = response.json()
recs = dictr['result']['records']
df = json_normalize(recs)
print(df)
Output:
_id HourUTC HourDK ... ElbasAveragePriceEUR ElbasMaxPriceEUR ElbasMinPriceEUR
0 264028 2019-01-01T00:00:00+00:00 2019-01-01T01:00:00 ... NaN NaN NaN
1 138428 2017-09-03T15:00:00+00:00 2017-09-03T17:00:00 ... 33.28 33.4 32.0
2 138429 2017-09-03T16:00:00+00:00 2017-09-03T18:00:00 ... 35.20 35.7 34.9
3 138430 2017-09-03T17:00:00+00:00 2017-09-03T19:00:00 ... 37.50 37.8 37.3
4 138431 2017-09-03T18:00:00+00:00 2017-09-03T20:00:00 ... 39.65 42.9 35.3
.. ... ... ... ... ... ... ...
995 139290 2017-10-09T13:00:00+00:00 2017-10-09T15:00:00 ... 38.40 38.4 38.4
996 139291 2017-10-09T14:00:00+00:00 2017-10-09T16:00:00 ... 41.90 44.3 33.9
997 139292 2017-10-09T15:00:00+00:00 2017-10-09T17:00:00 ... 46.26 49.5 41.4
998 139293 2017-10-09T16:00:00+00:00 2017-10-09T18:00:00 ... 56.22 58.5 49.1
999 139294 2017-10-09T17:00:00+00:00 2017-10-09T19:00:00 ... 56.71 65.4 42.2
PS: API is for Danish electricity prices
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.
This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.
using (WebClient client = new WebClient())
{
client.DownloadFile("http://csharpindepth.com/Reviews.aspx",
@"c:\Users\Jon\Test\foo.txt");
}
You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.
Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split
If using Angular CLI v7+, the webpack version is printed in the output of ng version
:
-> ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.10.6
@angular-devkit/build-angular 0.10.6
@angular-devkit/build-optimizer 0.10.6
@angular-devkit/build-webpack 0.10.6
@angular-devkit/core 7.0.6
@angular-devkit/schematics 7.0.6
@angular/cli 7.0.6
@ngtools/webpack 7.0.6
@schematics/angular 7.0.6
@schematics/update 0.10.6
rxjs 6.3.3
typescript 3.1.6
webpack 4.19.1
is null
can be used to check whether null
data is coming from a query as in following example:
declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
set @flag= 0;
end
else
begin
set @flag=1;
end
return @flag;
You would be better off using a DOM parser for this kind of HTML parsing. Consider this code:
$html = '<img id="12" border="0" src="/images/image.jpg"
alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//img"); // find your image
$node = $nodelist->item(0); // gets the 1st image
$value = $node->attributes->getNamedItem('src')->nodeValue;
echo "src=$value\n"; // prints src of image
OUTPUT:
src=/images/image.jpg
The Mandelbrot Set can be presented in a way that isn't terribly complex, for example in Java below:
public class MiniMandelbrot {
public static void main(String[] args) {
int[] rgbArray = new int[256 * 256];
for (int y=0; y<256; y++) {
for (int x=0; x<256; x++) {
double cReal=x/64.0-2.0, cImaginary=y/64.0-2.0;
double zReal=0.0, zImaginary=0.0, zRealSquared=0.0, zImaginarySquared=0.0;
int i;
for (i = 0; (i < 63) && (zRealSquared + zImaginarySquared < 4.0); i++) {
zImaginary = (zReal * zImaginary) + (zReal * zImaginary) + cImaginary;
zReal = zRealSquared - zImaginarySquared - cReal;
zImaginarySquared = zImaginary * zImaginary;
zRealSquared = zReal * zReal;
}
rgbArray[x+y*256] = i * 0x040404;
}
}
java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage(256, 256, 1);
bufferedImage.setRGB(0, 0, 256, 256, rgbArray, 0, 256);
javax.swing.JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon(bufferedImage), "The Mandelbrot Set", -1);
}
}
Editor's Note: All functions in JavaScript are closures as explained in this post. However we are only interested in identifying a subset of these functions which are interesting from a theoretical point of view. Henceforth any reference to the word closure will refer to this subset of functions unless otherwise stated.
A simple explanation for closures:
Now let's use this to figure out who uses closures and who doesn't (for the sake of explanation I have named the functions):
Case 1: Your Friend's Program
for (var i = 0; i < 10; i++) {
(function f() {
var i2 = i;
setTimeout(function g() {
console.log(i2);
}, 1000);
})();
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.i
is a free variable.setTimeout
is a free variable.g
is a local variable.console
is a free variable.i
is bound to the global scope.setTimeout
is bound to the global scope.console
is bound to the global scope.i
is not closed over by f
.setTimeout
is not closed over by f
.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Bad for you: Your friend is using a closure. The inner function is a closure.
Case 2: Your Program
for (var i = 0; i < 10; i++) {
setTimeout((function f(i2) {
return function g() {
console.log(i2);
};
})(i), 1000);
}
In the above program there are two functions: f
and g
. Let's see if they are closures:
For f
:
i2
is a local variable.g
is a local variable.console
is a free variable.console
is bound to the global scope.console
is not closed over by f
.Thus the function f
is not a closure.
For g
:
console
is a free variable.i2
is a free variable.console
is bound to the global scope.i2
is bound to the scope of f
.setTimeout
.
console
is not closed over by g
.i2
is closed over by g
.Thus the function g
is a closure for the free variable i2
(which is an upvalue for g
) when it's referenced from within setTimeout
.
Good for you: You are using a closure. The inner function is a closure.
So both you and your friend are using closures. Stop arguing. I hope I cleared the concept of closures and how to identify them for the both of you.
Edit: A simple explanation as to why are all functions closures (credits @Peter):
First let's consider the following program (it's the control):
lexicalScope();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the control. You should be able to see this message being alerted.";_x000D_
_x000D_
regularFunction();_x000D_
_x000D_
function regularFunction() {_x000D_
alert(eval("message"));_x000D_
}_x000D_
}
_x000D_
lexicalScope
and regularFunction
aren't closures from the above definition.message
to be alerted because regularFunction
is not a closure (i.e. it has access to all the variables in its parent scope - including message
).message
is indeed alerted.Next let's consider the following program (it's the alternative):
var closureFunction = lexicalScope();_x000D_
_x000D_
closureFunction();_x000D_
_x000D_
function lexicalScope() {_x000D_
var message = "This is the alternative. If you see this message being alerted then in means that every function in JavaScript is a closure.";_x000D_
_x000D_
return function closureFunction() {_x000D_
alert(eval("message"));_x000D_
};_x000D_
}
_x000D_
closureFunction
is a closure from the above definition.message
not to be alerted because closureFunction
is a closure (i.e. it only has access to all its non-local variables at the time the function is created (see this answer) - this does not include message
).message
is actually being alerted.What do we infer from this?
You can use E6 destructuring:
Object destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled({arg1: value1, arg2: value2});
})
promise.then(({arg1, arg2}) => {
// ....
});
Array destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled([value1, value2]);
})
promise.then(([arg1, arg2]) => {
// ....
});
struct timeval contains two components, the second and the microsecond. A timestamp with microsecond precision is represented as seconds since the epoch stored in the tv_sec field and the fractional microseconds in tv_usec. Thus you cannot just ignore tv_sec and expect sensible results.
If you use Linux or *BSD, you can use timersub() to subtract two struct timeval values, which might be what you want.
In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.
Sub Demo()
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim query As String
Dim Col, Row As Integer
Dim objWS As New clsws_GlobalWeather
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
query = objWS.wsm_GetCitiesByCountry("india")
If Not XDoc.LoadXML(query) Then 'strXML is the string with XML'
Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (query)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Worksheets("Sheet3").Cells(1, 1).Value = "Country"
Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
Worksheets("Sheet3").Cells(1, 2).Value = "City"
Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
For Each xChild In xParent.ChildNodes
Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
Col = Col + 1
Next xChild
Row = Row + 1
Col = 1
Next xParent
End Sub
Good solutions explained pretty well here. But Here is one more.
Create your own CustomContextWrapper
class extending ContextWrapper
and use it to change Locale setting for the complete application.
Here is a GIST with usage.
And then call the CustomContextWrapper
with saved locale identifier e.g. 'hi'
for Hindi language in activity lifecycle method attachBaseContext
. Usage here:
@Override
protected void attachBaseContext(Context newBase) {
// fetch from shared preference also save the same when applying. Default here is en = English
String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}
The Java-based Oracle SQL Developer has a plugin module that supports SQL Server. I use it regularly on my Mac. It's free, too.
Here's how to install the SQL Server plugin:
var redBox = $(".post");
var greenBox = $(".post1");
var offset = redBox.offset();
$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);
1.To begin using MongoDB, Open CMD with admin privilege and type : "C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
2.To create data directory(open another cmd terminal)
cd C:
md "\data\db"
3. To start your mongo DB database, type in cmd the following lines:
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --dbpath="c:\data\db"
(The --dbpath option points to your database directory.)
[you can also do step 2 and 3 first and then step 1]
ref:https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
From: hxxp://dbaspot.c om/postgresql/348627-pg_dump-t-give-where-condition.html (NOTE: the link is now broken)
# create temp table with the data
psql mydb
CREATE TABLE temp1 (LIKE mytable);
INSERT INTO temp1 SELECT * FROM mytable WHERE myconditions;
\q
# export the data to a sql file
pg_dump --data-only --column-inserts -t temp1 mtdb > out.sql
psql mydb
DROP TABLE temp1;
\q
# import temp1 rows in another database
cat out.sql | psql -d [other_db]
psql other_db
INSERT INTO mytable (SELECT * FROM temp1);
DROP TABLE temp1;
Another method useful in remotes
# export a table csv and import in another database
psql-remote> COPY elements TO '/tmp/elements.csv' DELIMITER ',' CSV HEADER;
$ scp host.com:/tmp/elements.csv /tmp/elements.csv
psql-local> COPY elements FROM '/tmp/elements.csv' DELIMITER ',' CSV;
// This will work prefectly in all :D
function basedInDocument(el) {
// This function is used for checking if this element in the real DOM
while (el.parentElement != null) {
if (el.parentElement == document.body) {
return true;
}
el = el.parentElement; // For checking the parent of.
} // If the loop breaks, it will return false, meaning
// the element is not in the real DOM.
return false;
}
Maybe this would be useful
-webkit-justify-content: space-around;
You can drop the new string[]
part:
List<string> values = new List<string> { "one", "two", "three" };
You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php
Then in your ajax call change the success function to this:
$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
Actually, I've been looking at the various ways to do this "infinite" pagination, and even though the human notion of time is that it is infinite (even though we have a notion of the beginning and end of time), computers deal in the discrete. There is a minimum and maximum time (that can be adjusted as time goes on, remember the basis of the Y2K scare?).
Anyways, the point of this discussion is that it is/should be sufficient to support a relatively infinite date range through an actually finite date range. A great example of this is the Android framework's CalendarView
implementation, and the WeeksAdapter
within it. The default minimum date is in 1900 and the default maximum date is in 2100, this should cover 99% of the calendar use of anyone within a 10 year radius around today easily.
What they do in their implementation (focused on weeks) is compute the number of weeks between the minimum and maximum date. This becomes the number of pages in the pager. Remember that the pager doesn't need to maintain all of these pages simultaneously (setOffscreenPageLimit(int)
), it just needs to be able to create the page based on the page number (or index/position). In this case the index is the number of weeks that the week is from the minimum date. With this approach you just have to maintain the minimum date and the number of pages (distance to the maximum date), then for any page you can easily compute the week associated with that page. No dancing around the fact that ViewPager
doesn't support looping (a.k.a infinite pagination), and trying to force it to behave like it can scroll infinitely.
new FragmentStatePagerAdapter(getFragmentManager()) {
@Override
public Fragment getItem(int index) {
final Bundle arguments = new Bundle(getArguments());
final Calendar temp_calendar = Calendar.getInstance();
temp_calendar.setTimeInMillis(_minimum_date.getTimeInMillis());
temp_calendar.setFirstDayOfWeek(_calendar.getStartOfWeek());
temp_calendar.add(Calendar.WEEK_OF_YEAR, index);
// Moves to the first day of this week
temp_calendar.add(Calendar.DAY_OF_YEAR,
-UiUtils.modulus(temp_calendar.get(Calendar.DAY_OF_WEEK) - temp_calendar.getFirstDayOfWeek(),
7));
arguments.putLong(KEY_DATE, temp_calendar.getTimeInMillis());
return Fragment.instantiate(getActivity(), WeekDaysFragment.class.getName(), arguments);
}
@Override
public int getCount() {
return _total_number_of_weeks;
}
};
Then WeekDaysFragment
can easily display the week starting at the date passed in its arguments.
Alternatively, it seems that some version of the Calendar app on Android uses a ViewSwitcher
(which means there's only 2 pages, the one you see and the hidden page). It then changes the transition animation based on which way the user swiped and renders the next/previous page accordingly. In this way you get infinite pagination because it just switching between two pages infinitely. This requires using a View
for the page though, which is way I went with the first approach.
In general, if you want "infinite pagination", it's probably because your pages are based off of dates or times somehow. If this is the case consider using a finite subset of time that is relatively infinite instead. This is how CalendarView
is implemented for example. Or you can use the ViewSwitcher
approach. The advantage of these two approaches is that neither does anything particularly unusual with the ViewSwitcher
or ViewPager
, and doesn't require any tricks or reimplementation to coerce them to behave infinitely (ViewSwitcher
is already designed to switch between views infinitely, but ViewPager
is designed to work on a finite, but not necessarily constant, set of pages).
AFAIK, the only way this could be done is by using the state=directory
option.
While template
module supports most of copy
options, which in turn supports most file
options, you can not use something like state=directory
with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf
is a directory ? or would it mean that {{project_root}}/conf/
should be created first.
So I don't think this is possible right now without adding a previous file
task.
- file:
path: "{{project_root}}/conf"
state: directory
recurse: yes
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "="
in the scope. Here's three solutions depending on your situation.
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use $observe
or $watch
:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// observe changes in attribute - could also be scope.$watch
attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
scope.variable = value;
}
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// observe changes in attribute - could also be scope.$watch
$attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
$scope.variable = value;
}
});
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Note that you should not set the variable to "="
in the scope, if you are using the $observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout
to wait until the $apply
has run. Also we need to use $emit
to send it to the parent scope app controller (due to the isolated scope in the directive):
app.directive('yourDirective', ['$timeout', function ($timeout) {
return {
restrict: 'A',
// NB: isolated scope!!
scope: {
yourDirective: '='
},
link: function (scope, element, attrs) {
// wait until after $apply
$timeout(function(){
console.log(scope.yourDirective);
// use scope.$emit to pass it to controller
scope.$emit('notification', scope.yourDirective);
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: [ '$scope', function ($scope) {
// wait until after $apply
$timeout(function(){
console.log($scope.yourDirective);
// use $scope.$emit to pass it to controller
$scope.$emit('notification', scope.yourDirective);
});
}]
};
}])
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$on('notification', function (evt, value) {
console.log(value);
$scope.variable = value;
});
}]);
And here's the html (no brackets!):
<div ng-controller="MyCtrl">
<div your-directive="someObject.someVariable"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
If your variable is not changing and you need to evaluate it in your directive, you can use the $eval
function:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval(attrs.yourDirective);
console.log(scope.variable);
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval($attrs.yourDirective);
console.log($scope.variable);
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
Yes, you can make a web method like..
[WebMethod]
public static String SetName(string name)
{
return "Your String"
}
And then call it in JavaScript like,
PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);
This is also required :
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
You can throw a HttpResponseException
HttpResponseMessage response =
this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "your message");
throw new HttpResponseException(response);
Each controller has it's own scope(s) so that's causing your issue.
Having two controllers that want access to the same data is a classic sign that you want a service. The angular team recommends thin controllers that are just glue between views and services. And specifically- "services should hold shared state across controllers".
Happily, there's a nice 15-minute video describing exactly this (controller communication via services): video
One of the original author's of Angular, Misko Hevery, discusses this recommendation (of using services in this situation) in his talk entitled Angular Best Practices (skip to 28:08 for this topic, although I very highly recommended watching the whole talk).
You can use events, but they are designed just for communication between two parties that want to be decoupled. In the above video, Misko notes how they can make your app more fragile. "Most of the time injecting services and doing direct communication is preferred and more robust". (Check out the above link starting at 53:37 to hear him talk about this)
With lambda its easy to run with AsyncTask
AsyncTask.execute(() -> //run your query here );
I hit this error calling:
dict(my_data)
I fixed this with:
import json
json.loads(my_data)
In general it's a pain to write a regular expression not containing a particular string. We had to do this for models of computation - you take an NFA, which is easy enough to define, and then reduce it to a regular expression. The expression for things not containing "cat" was about 80 characters long.
Edit: I just finished and yes, it's:
aa([^a] | a[^a])aa
Here is a very brief tutorial. I found some great ones before, but I can't see them anymore.
use the following file prefix, this will add to your perl script eTRUE and eFALSE, it will actually be REAL(!) true and false (just like java)
#!/usr/bin/perl
use strict;
use warnings;
use constant { #real true false, compatible with encode_json decode_json for later (we don't want field:false... will be field:0...)
eTRUE => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
eFALSE => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' )
};
There are, actually, few reasons why you should use that.
My reason is that working with JSON, I've got 0 and 1 as values to keys, but this hack will make sure correct values are kept along your script.
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.
Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.
Using these magic methods (__enter__
, __exit__
) allows you to implement objects which can be used easily with the with
statement.
The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally
block). Some more explanation here.
A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
As explained above, use this object with the with
statement (you may need to do from __future__ import with_statement
at the top of the file if you're on Python 2.5).
with DatabaseConnection() as mydbconn:
# do stuff
PEP343 -- The 'with' statement' has a nice writeup as well.
from PHP manual:
str_replace — Replace all occurrences of the search string with the replacement string
I would go down that route, and then convert from string to float - floatval
Just ot note: Pycharm's to spaces function only works on indent tabs at the beginning of a line, not interstitial tabs within a line of text. for example, when you are trying to format columns in monospaced text.
I definitely prefer the first solution :
int size;
if(getObjectSize(h, &size) != MYAPI_SUCCESS) {
// Error handling
}
i would slightly modify it, to:
int size;
MYAPIError rc;
rc = getObjectSize(h, &size)
if ( rc != MYAPI_SUCCESS) {
// Error handling
}
In additional i will never mix legitimate return value with error even if currently the scope of function allowing you to do so, you never know which way function implementation will go in the future.
And if we already talking about error handling i would suggest goto Error;
as error handling code, unless some undo
function can be called to handle error handling correctly.
This is a feature of ES6, which is used in React as well. Look at the below example:
function Sum(x,y,z) {
return x + y + z;
}
console.log(Sum(1,2,3)); //6
This way is fine if we have a maximum of 3 parameters. But, what if we need to add for example 110 parameters. Should we define them all and add them one by one?
Of course there is an easier way to do, which is called SPREAD. Instead of passing all those parameters you write :
function (...numbers){}
We have no idea how many parameters we have, but we know there are heaps of those. Based on ES6, we can rewrite the above function as below and use the spread and mapping between them to make it as easy as a piece of cake:
let Sum = (...numbers) => {
return numbers.reduce((prev, current) => prev + current );
}
console.log(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9));//45
When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.
This helped me:
Posted: 8/12/2011 4:54
Set tnsnames directory tools->Preferences->Database->advanced->Tnsnames Directory
https://forums.oracle.com/forums/thread.jspa?messageID=10020012�
For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.
Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).
loop over an Array:
var a = [];
for (var i=0; i<a.length; i++) {
i // is the index
a[i] // is the item
}
loop over an Object:
var o = {};
for (var prop in o) {
prop // is the property name
o[prop] // is the property value - the item
}
As noted in comments above, while still on some UA implementations, readAsBinaryString
method didn't made its way to the specs and should not be used in production.
Instead, use readAsArrayBuffer
and loop through it's buffer
to get back the binary string :
document.querySelector('input').addEventListener('change', function() {_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function() {_x000D_
_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
_x000D_
}, false);
_x000D_
<input type="file" />_x000D_
<div id="result"></div>
_x000D_
For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.
Yes, the file API does provide a way to convert your File, in the <input type="file"/>
to a binary string, thanks to the FileReader Object and its method readAsBinaryString
.
[But don't use it in production !]
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var binaryString = this.result;_x000D_
document.querySelector('#result').innerHTML = binaryString;_x000D_
}_x000D_
reader.readAsBinaryString(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
If you want an array buffer, then you can use the readAsArrayBuffer()
method :
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result;_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
Typically, no.
Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.
For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".
As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.
When creating a PWA, a service worker used on an non https server also generates this error.
Here is the complete process to create a local repo and push the changes to new remote branch
Creating local repository:-
Initially user may have created the local git repository.
$ git init
:- This will make the local folder as Git repository,
Link the remote branch:-
Now challenge is associate the local git repository with remote master branch.
$ git remote add RepoName RepoURL
usage: git remote add []
Test the Remote
$ git remote show
--->Display the remote name
$ git remote -v
--->Display the remote branches
Now Push to remote
$git add .
----> Add all the files and folder as git staged'
$git commit -m "Your Commit Message"
- - - >Commit the message
$git push
- - - - >Push the changes to the upstream
Use vertical-align:middle
in your CSS.
<table>
<tr>
<td style="vertical-align:middle">Description:</td>
<td><textarea></textarea></td>
</tr>
</table>
JQuery:
elemm.attr("onclick", "yourFunction(this)");
or:
elemm.attr("onclick", "alert('Hi!')");
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
to switch on,
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
to go back to normal.
Note that things like texture-mapping and lighting will still be applied to the wireframe lines if they're enabled, which can look weird.
Java arrays, like C++ arrays, have the fixed length that after initializing it, you cannot change it. But, like class template vector - vector <T>
- in C++ you can use Java class ArrayList
that has many more utilities than Java arrays have.
I'm having the same issue in Eclipse Luna in my Ubuntu VM, but I just tried to Ctrl+click on a method and it worked (even though my mouse cursor didn't change to a pointer).
This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).
Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.
The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:
a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns
OR
b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along
The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.
I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
For this particular case, if using re
module is overkill, how about using split
(or rsplit
) method as
se='</html>'
z.write(article.split(se)[0]+se)
For example,
#!/usr/bin/python
article='''<html>Larala
Ponta Monta
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')
se='</html>'
z.write(article.split(se)[0]+se)
outputs out.txt
as
<html>Larala
Ponta Monta
</html>
It is probably failing because 1.0.0
is an annotated tag. Perhaps you saw the following error message:
error: Trying to write non-commit object to branch refs/heads/master
Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.
git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master # shorthand
There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).
git push production +1.0.0^{}:master
These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.
You could use d3py a python module that generate xml pages embedding d3.js script. For example :
import d3py
import networkx as nx
import logging
logging.basicConfig(level=logging.DEBUG)
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(3,2)
G.add_edge(3,4)
G.add_edge(4,2)
# use 'with' if you are writing a script and want to serve this up forever
with d3py.NetworkXFigure(G, width=500, height=500) as p:
p += d3py.ForceLayout()
p.show()
In my case, this was a test target that I removed all the pods from inside my podfile (because I added pods that I later realized I did not need in that target). None of the other solutions here worked for me.
Go to the Build Phases tab in the project settings for the target that's causing trouble.
Delete the section named "Check Pods Manifest" and "Copy Pods Resources"
Inside "Link Binary With Libraries" remove libPods-YourTarget.a
In your project settings in the Info tab expand "Configurations" and set the configuration for the target to None for both debug and release. (This will fix a couple of missing file warnings)
Delete your project's derived data (Window > Projects > Delete [next to your project) and restart Xcode. Build / run target.
I think it's just for your convenience (and the readers of your code)
Your code, and your unit tests should be ideally self documenting which this API helps with,
Think abt what is more clear to read:
AssertTrue(!(a > 3));
or
AssertFalse(a > 3);
When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)
This BASH script will execute the python unittest test directory from ANYWHERE in the file system, no matter what working directory you are in: its working directory always be where that test
directory is located.
ALL TESTS, independent $PWD
unittest Python module is sensitive to your current directory, unless you tell it where (using discover -s
option).
This is useful when staying in the ./src
or ./example
working directory and you need a quick overall unit test:
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
python -m unittest discover -s "$readlink"/test -v
SELECTED TESTS, independent $PWD
I name this utility file: runone.py
and use it like this:
runone.py <test-python-filename-minus-dot-py-fileextension>
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
(cd "$dirname"/test; python -m unittest $1)
No need for a test/__init__.py
file to burden your package/memory-overhead during production.
Try the require_all gem:
It lets you simply:
require_all 'path/to/directory'
const list = [
{ qty: 10, size: 'XXL' },
{ qty: 2, size: 'XL' },
{ qty: 8, size: 'M' }
]
list.sort((a, b) => (a.qty > b.qty) ? 1 : -1)
console.log(list)
_x000D_
Out Put :
[
{
"qty": 2,
"size": "XL"
},
{
"qty": 8,
"size": "M"
},
{
"qty": 10,
"size": "XXL"
}
]
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
It depends on your situation.
I would say, if your bool has a good name, then:
if (control.IsEnabled) // Read "If control is enabled."
{
}
would be preferred.
If, however, the variable has a not-so-obvious name, checking against true
would be helpful in understanding the logic.
if (first == true) // Read "If first is true."
{
}
Give headercss position fixed.
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
top:0
}
Then give the content container a 320px padding-top, so it doesn't get behind the header.
With jquery library
<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">
The java.sql.Timestamp class has no format. Its toString method generates a String with a format.
Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.
First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.
Instant instant = mySqlDate.toInstant() ;
Lose the fraction of a second you don't want.
instant = instant.truncatedTo( ChronoUnit.Seconds );
Assign the time zone to adjust from UTC used by Instant.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generate a String close to your desired output. Replace its T
in the middle with a SPACE.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );
This seems to be already asked before:
This might help:
Twitter Bootstrap Use collapse.js on table cells [Almost Done]
UPDATE:
Your fiddle wasn't loading jQuery, so anything worked.
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<td>Some Stuff</td>
<td>Some more stuff</td>
<td>And some more</td>
</tr>
<tr>
<td colspan="3">
<div id="accordion" class="collapse">Hidden by default</div>
</td>
</tr>
</tbody>
</table>
Try this one: http://jsfiddle.net/Nb7wy/2/
I also added colspan='2'
to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)
The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.
what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:
"word1 word2 word2EOF"
Pure Virtual Function
try this code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()=0;
};
class anotherClass:aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"hellow World";
}
};
int main()
{
//aClassWithPureVirtualFunction virtualObject;
/*
This not possible to create object of a class that contain pure virtual function
*/
anotherClass object;
object.sayHellow();
}
In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.
Virtual function
try another code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()
{
cout<<"from base\n";
}
};
class anotherClass:public aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"from derived \n";
}
};
int main()
{
aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
baseObject->sayHellow();///call base one
baseObject=new anotherClass;
baseObject->sayHellow();////call the derived one!
}
Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks
Have you given the permission in the manifest file
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and inside your activity
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);
Let me know if you find any issue.
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Basing on this answer if you need history object only in order to navigate to other component:
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .
If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.
The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.
Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.
I’ve recently come to this issue again and wrote the following category on NSObject
:
@implementation NSObject (Testing)
- (void) performSelector: (SEL) selector
withBlockingCallback: (dispatch_block_t) block
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self performSelector:selector withObject:^{
if (block) block();
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
This way I can easily turn asynchronous call with a callback into a synchronous one in tests:
[testedObject performSelector:@selector(longAsyncOpWithCallback:)
withBlockingCallback:^{
STAssert…
}];
Tagging this answer which helped me, might not answer the actual question
If you are using password instead of private key, please refer to this answer for tested working solution on Ubuntu 16.04.5 and 20.04.1
I wrote a version detector based on Hermann Ingjaldsson's answer, but more robust and which returns an object with name/version data in it. It covers the major browsers but I don't bother with the plethora of mobile ones and minor ones:
function getBrowserData(nav) {
var data = {};
var ua = data.uaString = nav.userAgent;
var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
var operaMatch = browserMatch[1] === 'chrome';
if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }
if (/trident/i.test(browserMatch[1])) {
var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
data.name = 'msie';
data.version = msieMatch[1];
}
else if (operaMatch) {
data.name = 'opera';
data.version = operaMatch[1];
}
else if (browserMatch[1] === 'safari') {
var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
data.name = 'safari';
data.version = safariVersionMatch[1];
}
else {
data.name = browserMatch[1];
data.version = browserMatch[2];
}
var versionParts = [];
if (data.version) {
var versionPartsMatch = data.version.match(/(\d+)/g) || [];
for (var i=0; i < versionPartsMatch.length; i++) {
versionParts.push(versionPartsMatch[i]);
}
if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
}
data.name = data.name || '(unknown browser name)';
data.version = {
full: data.version || '(unknown full browser version)',
parts: versionParts,
major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
};
return data;
};
It can then be used like this:
var brData = getBrowserData(window.navigator || navigator);
console.log('name: ' + brData.name);
console.log('major version: ' + brData.version.major);
// etc.
if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json. as it's bad json with "quoted" text identifiers.
Add the below method to a class containing your extension methods.
public static string Remove(this string text, char character)
{
var sb = new StringBuilder();
foreach (char c in text)
{
if (c != character)
sb.Append(c);
}
return sb.ToString();
}
you can then use this extension method:
var text= myString.Remove('"');
This works for me:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
Returns true if the given string is null or is the empty string.
Consider normalizing your string references with nullToEmpty. If you do, you can use String.isEmpty() instead of this method, and you won't need special null-safe forms of methods like String.toUpperCase either. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.
There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.
And then you can copy for example the file "test.txt" from a remote host to the local host
scp [email protected]:test.txt /local/dir
@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.
In UNIX, absolute paths must start with '/'.
I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value')
for input elements and element.text
to return the text node of an element.
You could check the WebElement object with element.tag_name
to find out what kind of element it is and return the appropriate value.
This should help you figure out:
driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')
element_text = element.text
element_attribute_value = element.get_attribute('value')
print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()
pip list -v
can be used to list packages' install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31
Show install locations when list command ran with “-v” option. (#979)
>pip list -v
Package Version Location Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster 0.7.12 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg 1.5 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete 1.10.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid 2.3.3 c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...
This feature is introduced in pip
10.0.0b1. On Ubuntu 18.04 (Bionic Beaver), pip
or pip3
installed with sudo apt install python-pip
or sudo apt install python3-pip
is 9.0.1 which doesn't have this feature.
Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip
or pip3
.
This error is pretty verbose:
ValueError: could not convert string to float: id
Somewhere in your text file, a line has the word id
in it, which can't really be converted to a number.
Your test code works because the word id
isn't present in line 2
.
If you want to catch that line, try this code. I cleaned your code up a tad:
#!/usr/bin/python
import os, sys
from scipy import stats
import numpy as np
for index, line in enumerate(open('data2.txt', 'r').readlines()):
w = line.split(' ')
l1 = w[1:8]
l2 = w[8:15]
try:
list1 = map(float, l1)
list2 = map(float, l2)
except ValueError:
print 'Line {i} is corrupt!'.format(i = index)'
break
result = stats.ttest_ind(list1, list2)
print result[1]
After some experimentation I found that a fourth value in the line controls the spread (at least in FF 10). I opposed the vertical offsets and gave them a negative spread.
Here's the working pen: http://codepen.io/gillytech/pen/dlbsx
<html>
<head>
<style type="text/css">
#test {
width: 500px;
border: 1px #CCC solid;
height: 200px;
box-shadow:
inset 0px 11px 8px -10px #CCC,
inset 0px -11px 8px -10px #CCC;
}
</style>
</head>
<body>
<div id="test"></div>
</body>
</html>
This works perfectly for me!
I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.
Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.
In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.
Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.
For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :
20/2 = 10
10/2 = 5
Hence our answer is 5 + 1 + 1 = 7
. (The 1 + 1 because we divided the number 20 twice).
You can use float on that particular div, e.g.
<div style="float:right;">
Float the div you want more space to have to the left as well:
<div style="float:left;">
If all else fails give the div on the right position:absolute and then move it as right as you want it to be.
<div style="position:absolute; left:-500px; top:30px;">
etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.
Remember to import the MatTableModule module and remove the table element show below for reference.
wrong implementation
<table mat-table [dataSource]=”myDataArray”>
...
</table>
correct implementation:
<mat-table [dataSource]="myDataArray">
</mat-table>
the most simple and straight forward is to create a FTP login. Here is a little and easy to understand tutorial site on stackoverflow itself, how to set things up in 2min... Setting up FTP on Amazon Cloud Server
Are you using express?
Check your path(note the "/
" after /public/):
app.use(express.static(__dirname + "/public/"));
//note: you do not need the "/" before "css" because its already included above:
rel="stylesheet" href="css/style.css
Hope this helps
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
In VSCode 1.24 you can do that.
Right click on EXPLORER
on the side bar and checked Outline
.
Node.js is an open source command line tool built for the server side JavaScript code.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
The basic philosophy of node.js is:
Non-blocking I/O - every I/O call must take a callback, whether it is to retrieve information from disk, network or another process. Built-in support for the most important protocols (HTTP, DNS, TLS) Low-level. Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections. Stream everything; never force the buffering of data.
A little more elegant way of doing the same adding on to the above comment ..
<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
AutoGenerateColumns="false"
OnRowDeleting="deleteRow"
GridLines="Vertical">
<asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
<asp:BoundField DataField="EntityId" HeaderText="EntityId" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
And on the server side:
protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
string IdTemplate= e.Values["IdTemplate"].ToString();
string EntityId = e.Values["EntityId"].ToString();
// Do stuff..
}
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
If all you need is a tool for reading, then this thing will open the file instantly http://www.readfileonline.com/
Swift 4
extension NSAttributedString {
convenience init(htmlString html: String) throws {
try self.init(data: Data(html.utf8), options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
}
}
Usage
UILabel.attributedText = try? NSAttributedString(htmlString: "<strong>Hello</strong> World!")
Here's a simple one written in VB for an ASPX page:
If myVar > 1 Then
response.write("Greater than 1")
else
response.write("Not!")
End If
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState
everytime window popstate
event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
On windows python
3.5, I managed to install scipy
by using conda
not pip
:
conda install scipy
I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.
The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.
About this I think you can reference to http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html.
Here're my understandings about this, with the Identity Federation Use Case to give a details for those concepts:
IdP provides the Persistent identifiers, they are used for linking to the local accounts in SPs, but they identify as the user profile for the specific service each alone. For example, the persistent identifiers are kind of like : johnForAir, jonhForCar, johnForHotel, they all just for one specified service, since it need to link to its local identity in the service.
Transient identifiers are what IdP tell the SP that the users in the session have been granted to access the resource on SP, but the identities of users do not offer to SP actually. For example, The assertion just like “Anonymity(Idp doesn’t tell SP who he is) has the permission to access /resource on SP”. SP got it and let browser to access it, but still don’t know Anonymity' real name.
The explanation for it in the spec is "The interpretation of the content of the element is left to individual implementations". Which means IdP defines the real format for it, and it assumes that SP knows how to parse the format data respond from IdP. For example, IdP gives a format data "UserName=XXXXX Country=US", SP get the assertion, and can parse it and extract the UserName is "XXXXX".
It worked for me:
Template HTML:
I added (ngModelChange)="selectChange($event)"
to my select
.
<div>
<label for="myListOptions">My List Options</label>
<select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts
this function:
selectChange( $event) {
//In my case $event come with a id value
this.model.myListOptions = this.listOptions[$event];
}
Note:
I try with [select]="oneOption.id==model.myListOptions.id"
and not work.
============= Another ways can be: =========
Template HTML:
I added [compareWith]="compareByOptionId
to my select
.
<div>
<label for="myListOptions">My List Options</label>
<select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts
this function:
/* Return true or false if it is the selected */
compareByOptionId(idFist, idSecond) {
return idFist && idSecond && idFist.id == idSecond.id;
}
Add plugin to build.gradle
apply plugin: 'war'
Add provided dependency to tomcat
dependencies {
// other dependencies
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}