I define multiple functions in one .m file with Octave and then use the command from within the .m file where I need to make use of the functions from that file:
source("mycode.m");
Not sure if this is available with Matlab.
octave:8> help source
'source' is a built-in function
-- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
public class lab {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a string:");
String s1;
s1 = input.nextLine();
int k = s1.length();
char s2;
s2=s1.charAt(k-1);
s1=s2+s1+s2;
System.out.println("The new string is\n" +s1);
}
}
Here's the output you'll get.
* Enter a string CAT The new string is TCATT *
It prints the the last character of the string to the first and last place. You can do it with any character of the String.
String::repeat
". ".repeat( 7 ) // Seven period-with-space pairs: . . . . . . .
New in Java 11 is the method String::repeat
that does exactly what you asked for:
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
Its Javadoc says:
/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/
Here is a code snippet taken from a blog article written by Anubhav Goyal:
// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
foreach (string s in Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || "asp.net_sessionid".Equals(s, StringComparison.InvariantCultureIgnoreCase))
{
Response.Cookies[s].Secure = true;
}
}
}
Adding this to the EndRequest event handler in the global.asax should make this happen for all page calls.
Note: An edit was proposed to add a break;
statement inside a successful "secure" assignment. I've rejected this edit based on the idea that it would only allow 1 of the cookies to be forced to secure and the second would be ignored. It is not inconceivable to add a counter or some other metric to determine that both have been secured and to break at that point.
Have a look at this excellent article Deep dive into the murky waters of script loading by the Google developer Jake Archibald written in 2013.
Quoting the relevant section from that article:
Defer
<script src="//other-domain.com/1.js" defer></script> <script src="2.js" defer></script>
Spec says: Download together, execute in order just before DOMContentLoaded. Ignore “defer” on scripts without “src”.
IE < 10 says: I might execute 2.js halfway through the execution of 1.js. Isn’t that fun??
The browsers in red say: I have no idea what this “defer” thing is, I’m going to load the scripts as if it weren’t there.
Other browsers say: Ok, but I might not ignore “defer” on scripts without “src”.
(I'll add that early versions of Firefox trigger DOMContentLoaded before the defer
scripts finish running, according to this comment.)
Modern browsers seem to support async
properly, but you need to be OK with scripts running out of order and possibly before DOMContentLoaded.
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
There are two different ways of generating a UUID.
If you just need a unique ID, you want a version 1 or version 4.
Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.
Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.
If you need to always generate the same UUID from a given name, you want a version 3 or version 5.
Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.
Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.
Similar situation. Did commit and realized it's not ok.
git commit -a -m "message"
git log -p
Based on the answers this helped me.
# revert to previous state, keeping the files changed
git reset HEAD~
#make sure it's ok
git diff
git status
#revert the file we don't want to be within the commit
git checkout specs/nagios/nagios.spec
#make sure it's ok
git status
git diff
#now go ahead with commit
git commit -a -m "same|new message"
#eventually push tu remote
git push
Process Hacker has numerous ways of killing a process.
(Right-click the process, then go to Miscellaneous->Terminator.)
If you're going to v-model
a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store
, considering that's what your getter pulls it from) you do in the setter.
If writing it back to the store happens via form submission, you don't want to v-model
, you just want to set :value
.
If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store
until form submission, you'll need to create such a data item.
InputStream in = new ByteArrayInputStream(yourstring.getBytes());
After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:
Follow this code:
Step-1: Call jquery library in html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Step-2: Write code to change text of input fields:
<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
});});
</script>
Step-3: Create HTML input fields with same id's you use in jquery code like:
<input type="text" id="edit-submitted-first-name" name="field name">
The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)
**Result: Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here. Result should like this: User Type: "thank you" it will change with "Thank You". **
Best of luck
I reckon the easiest way would be to use a built-in js functions decodeURI() / encodeURI().
function (usernameSent) {
var usernameEncoded = usernameSent; // Current value: utf8
var usernameDecoded = decodeURI(usernameReceived); // Decoded
// do stuff
}
I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.
.ts:
@Input() profile;
.html:
<span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>
.scss:
.avatar {
border-radius: 100%;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
width: 96px;
height: 96px;
}
Please note that if you write background
instead of 'background-image'
in [ngStyle]
, the styles you write (even in style
of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'
. The [ngStyle]
priority is higher than style
of element. In background
here, only url() property will work. Be sure to use 'background-image'
instead of 'background'
in case you want to write more properties to background image.
Extending Alex's answer slightly:
class User:
def __init__(self):
self.data = [1,2,3]
self.other_data = [4,5,6]
def doSomething(self, source):
dataSource = getattr(self,source)
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
will yield:
[1, 2, 3] [4, 5, 6]
However, personally I don't think that's great style - getattr
will let you access any attribute of the instance, including things like the doSomething
method itself, or even the __dict__
of the instance. I would suggest that instead you implement a dictionary of data sources, like so:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
again yielding:
[1, 2, 3] [4, 5, 6]
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
@Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.
Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using @tmpTable1. Depending on what you want to tell it to do.
A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.
Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.
You can't, as there are no variables in Python but only names.
For example:
> a = [1,2,3]
> b = a
> a is b
True
Which of those two is now the correct variable? There's no difference between a
and b
.
There's been a similar question before.
MSTest does not support that feature, but you can implement your own attribute to achieve that.
Have a look at Enabling parameterized tests in MSTest using PostSharp.
say you define the static getFactorial
function inside a CodeController
then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.
CodeController::getFactorial($index);
----------------UPDATE----------------
To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.
to do that
create a folder inside app
directory and name it as lib
(you can put a name you like).
this folder to needs to be autoload to do that add app/lib
to composer.json
as below. and run the composer dumpautoload
command.
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
............
"app/lib"
]
},
then files inside lib
will autoloaded.
then create a file inside lib
, i name it helperFunctions.php
inside that define the function.
if ( ! function_exists('getFactorial'))
{
/**
* return the factorial of a number
*
* @param $number
* @return string
*/
function getFactorial($date)
{
$fact = 1;
for($i = 1; $i <= $num ;$i++)
$fact = $fact * $i;
return $fact;
}
}
and call it anywhere within the app as
$fatorial_value = getFactorial(225);
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable
object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
After upgrading from Ubuntu 14.04 lts to Ubuntu 16.04 lts I found a yet another reason for this error that I haven't seen before.
During the upgrading process I had somehow lost my php5-fpm executable altogether. All the config files were intact and it took me a while to realize that service php5-fpm start
didn't really start a process, as it did not show any errors.
My moment of awakening was when I noticed that there were no socket file in /var/run/php5-fpm.sock
, as there should be, nor did netstat -an
show processes listening on the port that I tried as an alternative while trying to solve this problem. Since the file /usr/sbin/php5-fpm was also non-existing, I was finally on the right track.
In order to solve this problem I upgraded php from version 5.5 to 7.0. apt-get install php-fpm
did the trick as a side effect. After that and installing other necessary packages everything was back to normal.
This upgrading solution may have problems of its own, however. Since php has evolved quite a bit, it's possible that the software will break in unimaginable ways. So, even though I did go down that path, you may want to keep the version you're fond of just for a while longer.
Luckily, there seems to be a neat way for that, as described on The Customize Windows site:
add-apt-repository ppa:ondrej/php
apt-get purge php5-common
apt-get update
apt-get install php5.6
Neater solution as it might be, I didn't try that. I expect the next couple of days will tell me whether I should have.
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
You can convert list in string with elements seperated by space and split it based on number/char to be searched..
Will be clean and fast for large list..
>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3
This is really simple, the String
object has an endsWith
method.
From your question it seems like you want either /
, ,
or .
as the delimiter set.
So:
String str = "This.is.a.great.place.to.work.";
if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
// ...
You can also do this with the matches
method and a fairly simple regex:
if (str.matches(".*([.,/])work\\1$"))
Using the character class [.,/]
specifying either a period, a slash, or a comma, and a backreference, \1
that matches whichever of the alternates were found, if any.
This works for me:
try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
byte[] buffer = new byte[1024];
int bytesRead;
while((bytesRead = pdfin.read(buffer))!=-1){
pdfout.write(buffer,0,bytesRead);
}
}
But Jon's answer doesn't work for me if used in the following way:
try(InputStream pdfin = new FileInputStream("input.pdf");OutputStream pdfout = new FileOutputStream("output.pdf")){
int k = readFully(pdfin).length;
System.out.println(k);
}
Outputs zero as length. Why is that ?
One way to set the $_GET
variable is to parse the URL using parse_url()
and then parse the $query
string using parse_str()
, which sets the variables into the $_GET
global.
This approach is useful,
function setGetRequest($url)
{
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $_GET);
}
$url = 'http://www.example.com/test.php?a=10&b=plop';
setGetRequest($url);
var_dump($_GET);
Result: $_GET
contains
array (
'a' => string '10' (length=2)
'b' => string 'plop' (length=4)
)
Take these 2 examples:
var A = function() { this.hey = function() { alert('from A') } };
vs.
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Most people here (especially the top-rated answers) tried to explain how they are different without explaining WHY. I think this is wrong and if you understand the fundamentals first, the difference will become obvious. Let's try to explain the fundamentals first...
a) A function is an object in JavaScript. EVERY object in JavaScript gets an internal property (meaning, you can't access it like other properties, except maybe in browsers like Chrome), often referred to as __proto__
(you can actually type anyObject.__proto__
in Chrome to see what it references. This is just that, a property, nothing more. A property in JavaScript = a variable inside an object, nothing more. What do variables do? They point to things.
So what does this __proto__
property points to? Well, usually another object (we'll explain why later). The only way to force JavaScript for the __proto__
property to NOT point to another object is to use var newObj = Object.create(null)
. Even if you do this, the __proto__
property STILL exists as a property of the object, just it doesn't point to another object, it points to null
.
Here's where most people get confused:
When you create a new function in JavaScript (which is an object as well, remember?), the moment it is defined, JavaScript automatically creates a new property on that function called prototype
. Try it:
var A = [];
A.prototype // undefined
A = function() {}
A.prototype // {} // got created when function() {} was defined
A.prototype
is TOTALLY DIFFERENT from the __proto__
property. In our example, 'A' now has TWO properties called 'prototype' and __proto__
. This is a big confusion for people. prototype
and __proto__
properties are in no way related, they're separate things pointing to separate values.
You may wonder: Why does JavaScript has __proto__
property created on every single object? Well, one word: delegation. When you call a property on an object and the object doesn't have it, then JavaScript looks for the object referenced by __proto__
to see if it maybe has it. If it doesn't have it, then it looks at that object's __proto__
property and so on...until the chain ends. Thus the name prototype chain. Of course, if __proto__
doesn't point to an object and instead points to null
, well tough luck, JavaScript realizes that and will return you undefined
for the property.
You may also wonder, why does JavaScript creates a property called prototype
for a function when you define the function? Because it tries to fool you, yes fool you that it works like class-based languages.
Let's go on with our example and create an "object" out of A
:
var a1 = new A();
There's something happening in the background when this thing happened. a1
is an ordinary variable which was assigned a new, empty object.
The fact that you used the operator new
before a function invocation A()
did something ADDITIONAL in the background. The new
keyword created a new object which now references a1
and that object is empty. Here's what happening additionally:
We said that on each function definition there's a new property created called prototype
(which you can access it, unlike with the __proto__
property) created? Well, that property is being used now.
So we're now at the point where we have a freshly baked empty a1
object. We said that all objects in JavaScript have an internal __proto__
property which points to something (a1
also has it), whether it's null or another object. What the new
operator does is that it sets that __proto__
property to point to the function's prototype
property. Read that again. It's basically this:
a1.__proto__ = A.prototype;
We said that A.prototype
is nothing more than an empty object (unless we change it to something else before defining a1
). So now basically a1.__proto__
points to the same thing A.prototype
points to, which is that empty object. They both point to the same object which was created when this line happened:
A = function() {} // JS: cool. let's also create A.prototype pointing to empty {}
Now, there's another thing happening when var a1 = new A()
statement is processed. Basically A()
is executed and if A is something like this:
var A = function() { this.hey = function() { alert('from A') } };
All that stuff inside function() { }
is going to execute. When you reach the this.hey..
line, this
is changed to a1
and you get this:
a1.hey = function() { alert('from A') }
I won't cover why this
changes to a1
but this is a great answer to learn more.
So to summarize, when you do var a1 = new A()
there are 3 things happening in the background:
a1
. a1 = {}
a1.__proto__
property is assigned to point at the same thing as A.prototype
points to (another empty object {} )
The function A()
is being executed with this
set to the new, empty object created in step 1 (read the answer I referenced above as to why this
changes to a1
)
Now, let's try to create another object:
var a2 = new A();
Steps 1,2,3 will repeat. Do you notice something? The key word is repeat. Step 1: a2
will be a new empty object, step 2: its __proto__
property will point to the same thing A.prototype
points to and most importantly, step 3: function A()
is AGAIN executed, which means that a2
will get hey
property containing a function. a1
and a2
have two SEPARATE properties named hey
which point to 2 SEPARATE functions! We now have duplicate functions in same two different objects doing the same thing, oops...You can imagine the memory implications of this if we have 1000 objects created with new A
, after all functions declarations take more memory than something like the number 2. So how do we prevent this?
Remember why the __proto__
property exists on every object? So that if you retrieve the yoMan
property on a1
(which doesn't exist), its __proto__
property will be consulted, which if it's an object (and is most cases it is), it will check if it contains yoMan
, and if it doesn't, it will consult that object's __proto__
etc. If it does, it will take that property value and display it to you.
So someone decided to use this fact + the fact that when you create a1
, its __proto__
property points to the same (empty) object A.prototype
points to and do this:
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Cool! Now, when you create a1
, it again goes through all of the 3 steps above, and in step 3, it doesn't do anything, since function A()
has nothing to execute. And if we do:
a1.hey
It will see that a1
does not contain hey
and it will check its __proto__
property object to see if it has it, which is the case.
With this approach we eliminate the part from step 3 where functions are duplicated on each new object creation. Instead of a1
and a2
having a separate hey
property, now NONE of them has it. Which, I guess, you figured out yourself by now. That's the nice thing...if you understand __proto__
and Function.prototype
, questions like these will be pretty obvious.
NOTE: Some people tend to not call the internal Prototype property as __proto__
, I've used this name through the post to distinguish it clearly to the Functional.prototype
property as two different things.
Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):
use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go
360 degrees = 2*pi radians
That means deg2rad(x) = x*pi/180 and rad2deg(x) = 180x/pi;
You can do it this with two replace's
//let stw be "John Smith $100,000.00 M"
sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"
sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"
sw.WriteLine(sb_trim);
Here's how to look in the documentation.
First, you're dealing with IO, so look in the java.io
package.
There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles()
method in the File class. And the documentation for that method says:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
Scrolling up in the File
JavaDoc, I see the constructors. And that's really all I need to be able to create a File
instance and call listFiles()
on it. Scrolling still further, I can see some information about how files are named in different operating systems.
use this
body {
background: url(images/image-1.png), url(images/image-2.png),url(images/image-3.png);
background-repeat: no-repeat, repeat-x, repeat-y;
background-position:10px 20px , 20px 30px ,15px 25px;
}
a simple way to adjust you every image position with background-position: and set repeat property with background-repeat: for every image individually
I had a maven project giving me same thing. It showed that it couldnt find the jar with that version (dependency) and I knew its there and is correct -
So, for me the solution was to 1 delete the local repository. 2 Clean the project. 3 Disable the maven nature. 4 Generate eclipse artifacts and 5 re-configure as maven project.
(in order)
If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all
(or delete_all
) in the seed.db file to clean out a table before your MyModel.create!(...)
statements load the data. Then, you can redo the db:seed
operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)
There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...
To stop repeated alert of Nick's answer
ScrollActivate();
function ScrollActivate() {
$(window).on("scroll", function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).off("scroll");
alert("near bottom!");
}
});
}
As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.
However, especially if you are actively developing in both the parent repo and the submodule, detached HEAD
state can be confusing and potentially dangerous. If you make commits in the submodule while it's in detached HEAD
state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using git reflog
, but it's much better to avoid them in the first place.)
If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your gitconfig
file:
[alias]
submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z $branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"$branch\"; fi'; }; f"
Now, after doing git submodule update
you just need to call git submodule-checkout-branch
, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.
Furthermore, if you have set up git to automatically update submodules on checkout (using git config --global submodule.recurse true
, see this answer), you can make a post-checkout hook that calls this alias automatically:
$ cat .git/hooks/post-checkout
#!/bin/sh
git submodule-checkout-branch
Then you don't need to call either git submodule update
or git submodule-checkout-branch
, just doing git checkout
will update all submodules to their respective commits and check out the corresponding branches (if they exist).
Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";
// use the built in Json deserializer to convert the string to a list of Person objects
var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);
foreach (var person in people)
{
Console.WriteLine(person.Name + " is " + person.Age + " years old.");
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}
}
I had this error because I was using redirect_url
as a parameter instead of redirect_uri
.
The Server-Side Authentication doc page says to use redirect_url
:
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID
&redirect_url=YOUR_REDIRECT_URI
&scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
&state=SOME_ARBITRARY_BUT_UNIQUE_STRING
But this is incorrect. The OAuth Dialog doc says to use redirect_uri
instead, which works, so I'm assuming that you can only use one and not the other:
https://www.facebook.com/dialog/oauth/?
client_id=YOUR_APP_ID
&redirect_uri=YOUR_REDIRECT_URL
&state=YOUR_STATE_VALUE
&scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
Well it also can be :
SELECT t.col1, t.col2, ('test' + t.col3) as test_col3
FROM table t;
where for concatenation in oracle is used the operator ||
not +
.
In this case you get : ORA-01722: invalid number ...
Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:
EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!
Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
End Function
myOptions = {
center: myLatlng,
minZoom: 6,
maxZoom: 9,
styles: customStyles,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Try this out:
grep -i 'killed process' /var/log/messages
In the following httpd.conf
file, configure the ServerName
properly.
/etc/httpd/conf/httpd.conf
Like below:
ServerName 127.0.0.1:80
or
ServerName sitename
This resolved similar issue I was facing.
For +300k concurrent connection:
Set these variables in /etc/sysctl.conf
:
fs.file-max = 10000000
fs.nr_open = 10000000
Also, change these variables in /etc/security/limits.conf
:
* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000
And finally, increase TCP buffers in /etc/sysctl.conf
, too:
net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
for more information please refer to this.
#include + guard == #import
#include guard
Wiki - macro guard, header guard or file guard prevents to double include a header by a preprocessor
that can slow down a build time
The next step is
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
ctrl+fn+F11 on Mac to change the landscape to portrait and vice versa.
left-ctrl+F11on Windows 7.
ctrl+F11on Linux.
Description:
The MVC pattern is essentially this:
Important feature of MVC: We can modify Either the Model or View or Controller still not affecting the other ones
It looks like your $pdo
variable is not initialized.
I can't see in the code you've uploaded where you are initializing it.
Make sure you create a new PDO object in the global scope
before calling the class methods. (You should declare it in the global scope because of how you implemented the methods inside the Category class).
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
I believe DB Designer does something like that. And I think they even have a free version.
edit Never mind. Michael's link is much better.
The following is a simplification/one liner from the accepted answer:
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
for x in (x for x in xyz if x not in a):
print(x)
12
242
Notice that the generator
was kept inline. This was tested on python2.7
and python3.6
(notice the parens in the print
;) )
You're on the right track - the keyword you should be googling is Regular Expressions. R does support them in a more direct way than this using grep()
and a few other alternatives.
Here's a detailed discussion: http://www.regular-expressions.info/rlanguage.html
Unlike jQuery
in order to read raw JSON
you will need to decode it in PHP.
print_r(json_decode(file_get_contents("php://input"), true));
php://input
is a read-only stream that allows you to read raw data from the request body.
$_POST
is form variables, you will need to switch to form
radiobutton in postman
then use:
foo=bar&foo2=bar2
To post raw json
with jquery
:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If /home/smith/Desktop/Test/../
is what you want:
dirname 'path/to/child/dir'
as seen here.
Had this issue with spring-boot 2.4.1 when running the tests in bulk from [Intellij Idea] version 2020.3. The issue doesn't appear when running only one test at a time from IntelliJ or when running the tests from command line.
Maybe Intellij caching problem?
Follow up:
The problem appears when running tests using the maven-surefire-plugin reuseForks true. Using reuseForks false would provide a quick fix, but the tests running time will increase dramatically. Because we are reusing forks, the database context might become dirty due to other tests that are run - without cleaning the database context afterwards. The obvious solution would be to clean the database context before running a test, but the best one should be to clean up the database context after each test (solving the root cause of the original problem). Using the @Transactional annotation on your test methods will guarantee that your database changes are rolled back at the end of the test methods. See the Spring documentation on transactions: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testcontext-tx.
Add your style here:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Then in the page:
<asp:Table CssClass=NewStyleExampleClass runat="server" >
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
My solution was to put same value (path to JDK bin folder) in JAVA_HOME
and Path
Here is my batch script that I put together based on the good answers here & in other posts
You can set title timeout & even sleep to schedule it for latter & \n for new line
Name it popup.bat & put it in your windows path folder to work globally on your pc
For example popup Line 1\nLine 2
will produce a 2 line popup box
(type popup /?
for usage)
Here is the code
<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1] set pop.key=Ok
if %pop.key% == [2] set pop.key=Cancel
if %pop.key% == [3] set pop.key=Abort
if %pop.key% == [4] set pop.key=Retry
if %pop.key% == [5] set pop.key=Ignore
if %pop.key% == [6] set pop.key=Yes
if %pop.key% == [7] set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b
-- End CMD -->
<job><script language="VBScript">
'on error resume next
q =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup = 0
Title = "Popup"
Timeout = 0
Mode = 0
Message = ""
Sleep = 0
button = 0
If objArgs.Count = 0 Then
Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then
Usage()
End If
noWait = Not wait()
For Each arg in objArgs
If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch = True
Next
If not haveSwitch Then
Message=joinParam("woq")
Else
For i = 0 To objArgs.Count-1
If IsSwitch(objArgs(i)) Then
S=split(objArgs(i) , ":" , 2)
select case Lcase(S(0))
case "/m","/message"
Message=S(1)
case "/tt","/title"
Title=S(1)
case "/s","/sleep"
If IsNumeric(S(1)) Then Sleep=S(1)*1000
case "/t","/time"
If IsNumeric(S(1)) Then Timeout=S(1)
case "/b","/button"
select case S(1)
case "oc", "1"
button=1
case "ari","2"
button=2
case "ync","3"
button=3
case "yn", "4"
button=4
case "rc", "5"
button=5
case "ctc","6"
button=6
case Else
button=0
end select
case "/i","/icon"
select case S(1)
case "s","x","stop","16"
Mode=16
case "?","q","question","32"
Mode=32
case "!","w","warning","exclamation","48"
Mode=48
case "i","information","info","64"
Mode=64
case Else
Mode=0
end select
end select
End If
Next
End If
Message = Replace(Message,"/\n", "°" )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0
Wscript.Sleep(sleep)
Popup = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup
Function IsSwitch(Val)
IsSwitch = False
If Mid(Val,1,1) = "/" Then
For ii = 3 To 9
If Mid(Val,ii,1) = ":" Then IsSwitch = True
Next
End If
End Function
Function joinParam(quotes)
ReDim ArgArr(objArgs.Count-1)
For i = 0 To objArgs.Count-1
If quotes = "wq" Then
ArgArr(i) = q & objArgs(i) & q
Else
ArgArr(i) = objArgs(i)
End If
Next
joinParam = Join(ArgArr)
End Function
Function wait()
wait=True
If objArgs.Named.Exists("NewProcess") Then
wait=False
Exit Function
ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq")
WScript.Quit 99
End If
End Function
Function Usage()
Wscript.Echo _
vbCrLf&"Usage:" _
&vbCrLf&" popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
&vbCrLf&" To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
&vbCrLf&"" _
&vbCrLf&"Advanced user" _
&vbCrLf&" If any Switch is used then you must use the /m: switch for the message " _
&vbCrLf&" No space allowed between the switch & the value " _
&vbCrLf&" The switches are NOT case sensitive " _
&vbCrLf&"" _
&vbCrLf&" popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
&vbCrLf&"" _
&vbCrLf&" Switch | value |Description" _
&vbCrLf&" -----------------------------------------------------------------------" _
&vbCrLf&" /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
&vbCrLf&" | |" _
&vbCrLf&" /t: /time: | nn |Duration of the popup for n seconds " _
&vbCrLf&" | |<Default> untill key pressed" _
&vbCrLf&" | |" _
&vbCrLf&" /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
&vbCrLf&" | | <Default> Popup" _
&vbCrLf&" | |" _
&vbCrLf&" /s: /sleep: | nn |schedule the popup after n seconds " _
&vbCrLf&" | |" _
&vbCrLf&" /nw /NoWait | |Continue script without the user pressing ok - " _
&vbCrLf&" | | botton option will be defaulted to OK button " _
&vbCrLf&" | |" _
&vbCrLf&" /i: /icon: | ?/q |[question mark]" _
&vbCrLf&" | !/w |[exclamation (warning) mark]" _
&vbCrLf&" | i/info|[information mark]" _
&vbCrLf&" | x/stop|[stop\error mark]" _
&vbCrLf&" | n/none|<Default>" _
&vbCrLf&" | |" _
&vbCrLf&" /b: /button: | o |[OK button] <Default>" _
&vbCrLf&" | oc |[OK and Cancel buttons]" _
&vbCrLf&" | ari |[Abort, Retry, and Ignore buttons]" _
&vbCrLf&" | ync |[Yes, No, and Cancel buttons]" _
&vbCrLf&" | yn |[Yes and No buttons]" _
&vbCrLf&" | rc |[Retry and Cancel buttons]" _
&vbCrLf&" | ctc |[Cancel and Try Again and Continue buttons]" _
&vbCrLf&" ---> | ---> |The output will be saved in variable ""pop.key""" _
&vbCrLf&"" _
&vbCrLf&"Example:" _
&vbCrLf&" popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
&vbCrLf&"" _
&vbCrLf&" v1.9 By RDR @ 2020"
Wscript.Quit
End Function
</script></job>
You can use CSS white-space Property
to achieve this.
white-space: nowrap
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
I noticed that almost every solution posted involved ax.imshow(im, ...)
and did not normalize the colors displayed to the colorbar for the multiple subfigures. The im
mappable is taken from the last instance, but what if the values of the multiple im
-s are different? (I'm assuming these mappables are treated in the same way that the contour-sets and surface-sets are treated.) I have an example using a 3d surface plot below that creates two colorbars for a 2x2 subplot (one colorbar per one row). Although the question asks explicitly for a different arrangement, I think the example helps clarify some things. I haven't found a way to do this using plt.subplots(...)
yet because of the 3D axes unfortunately.
If only I could position the colorbars in a better way... (There is probably a much better way to do this, but at least it should be not too difficult to follow.)
import matplotlib
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
cmap = 'plasma'
ncontours = 5
def get_data(row, col):
""" get X, Y, Z, and plot number of subplot
Z > 0 for top row, Z < 0 for bottom row """
if row == 0:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 1
else:
pnum = 2
elif row == 1:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = -np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 3
else:
pnum = 4
print("\nPNUM: {}, Zmin = {}, Zmax = {}\n".format(pnum, np.min(Z), np.max(Z)))
return X, Y, Z, pnum
fig = plt.figure()
nrows, ncols = 2, 2
zz = []
axes = []
for row in range(nrows):
for col in range(ncols):
X, Y, Z, pnum = get_data(row, col)
ax = fig.add_subplot(nrows, ncols, pnum, projection='3d')
ax.set_title('row = {}, col = {}'.format(row, col))
fhandle = ax.plot_surface(X, Y, Z, cmap=cmap)
zz.append(Z)
axes.append(ax)
## get full range of Z data as flat list for top and bottom rows
zz_top = zz[0].reshape(-1).tolist() + zz[1].reshape(-1).tolist()
zz_btm = zz[2].reshape(-1).tolist() + zz[3].reshape(-1).tolist()
## get top and bottom axes
ax_top = [axes[0], axes[1]]
ax_btm = [axes[2], axes[3]]
## normalize colors to minimum and maximum values of dataset
norm_top = matplotlib.colors.Normalize(vmin=min(zz_top), vmax=max(zz_top))
norm_btm = matplotlib.colors.Normalize(vmin=min(zz_btm), vmax=max(zz_btm))
cmap = cm.get_cmap(cmap, ncontours) # number of colors on colorbar
mtop = cm.ScalarMappable(cmap=cmap, norm=norm_top)
mbtm = cm.ScalarMappable(cmap=cmap, norm=norm_btm)
for m in (mtop, mbtm):
m.set_array([])
# ## create cax to draw colorbar in
# cax_top = fig.add_axes([0.9, 0.55, 0.05, 0.4])
# cax_btm = fig.add_axes([0.9, 0.05, 0.05, 0.4])
cbar_top = fig.colorbar(mtop, ax=ax_top, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_top)
cbar_top.set_ticks(np.linspace(min(zz_top), max(zz_top), ncontours))
cbar_btm = fig.colorbar(mbtm, ax=ax_btm, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_btm)
cbar_btm.set_ticks(np.linspace(min(zz_btm), max(zz_btm), ncontours))
plt.show()
plt.close(fig)
## orientation of colorbar = 'horizontal' if done by column
I created a class wrapped in an ES6 module that solves exactly this.
It's 103 lines, no dependencies, and fairly nicely structured and documented, meant to be easy to modify/reuse.
Handles all 8 possible orientations, and is Promise-based.
Here you go, hope this still helps someone: https://gist.github.com/vdavid/3f9b66b60f52204317a4cc0e77097913
PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.
The following will produce an error:
function f(&$v){$v = true;}
f(&$v);
function f($v){$v = true;}
f(&$v);
None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.
If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.
The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.
This will do nothing:
function f($v){$v = true;}
$r = &$v;
f($r);
More specifically, it turns the reference back into a normal variable as you have not asked for a reference.
This will work:
function f(&$v){$v = true;}
f($v);
This sees that you are passing a non-reference but want a reference so turns it into a reference.
What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.
If you need more dynamic behaviour this will work:
function f(&$v){$v = true;}
$v = array(false,false,false);
$r = &$v[1];
f($r);
Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.
Ruby based watir-webdriver use something like this:
browser=Watir::Browser.new( :chrome, :switches => %w[ --disable-extensions ] )
You can use an emulator like genymotion which gives you the flexibility to emulate your present GPS location, etc.
Checkout Portfoliojs jQuery plugin: http://portfoliojs.com
This plugin supports Touch Devices, Desktops and Mobile Browsers. Also, It has pre-loading feature.
You are right, it is simple. Run (admin password required):
'/Library/Application Support/Jenkins/Uninstall.command'
It may be necessary to do this with admin privileges using sudo.
According to the ewerybody post: https://stackoverflow.com/a/29275361/7530957
Multiple problems can arise:
The 'ewerybody's' code will not work if the process name is long. So there is a problem with this line:
last_line.lower().startswith(process_name.lower())
Because last_line will be shorter than the process name.
So if you just want to know if a process/processes is/are active:
from subprocess import check_output
def process_exists(process_name):
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
if check_output(call).splitlines()[3:]:
return True
Instead for all the information of a process/processes
from subprocess import check_output
def process_exists(process_name):
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
processes = []
for process in check_output(call).splitlines()[3:]:
process = process.decode()
processes.append(process.split())
return processes
#define debug_print(FMT, ARGS...) do { \
if (DEBUG) \
fprintf(stderr, "%s:%d " FMT "\n", __FUNCTION__, __LINE__, ## ARGS); \
} while (0)
one line function:
function type(obj) {
return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase()
}
this give the same result as jQuery.type()
This will also work
let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));
Use the Activity Monitor. It's the last toolbar in the top bar. It will show you a list of "Recent Expensive Queries". You can double-click them to see the execution plan, etc.
Others have answered sufficiently. I would just like to add a few examples of frequent extensions:
The main
function returning void
. This is not defined by the standard, meaning it will only work on some compilers (including GCC), but not on others. By the way, int main()
and int main(int, char**)
are the two signatures that the standard does define.
Another popular extension is being able to declare and define functions inside other functions:
void f()
{
void g()
{
// ...
}
// ...
g();
// ...
}
This is nonstandard. If you want this kind of behavior, check out C++11 lambdas
std::string str(c_str, strnlen(c_str, max_length));
At Christian Rau's request:
strnlen
is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.
I ran into a similar error trying to run rails with postgresql. (I found this SO looking for a solution. Homebrew broke alot of things when it switched to open SSL 1.1.1) The above answers did not work for me (Mac 10.14.6). However, the answer found here did:
brew install --upgrade openssl
brew reinstall postgresql
For people that have tried above,try generating the key with the -keypass and -storepass options as I was only inputting one of the passwords when running it like the React Native docs have you. This caused it to error out when trying to build.
keytool -keypass PASSWORD1 -storepass PASSWORD2 -genkeypair -v -keystore release2.keystore -alias release2 -keyalg RSA -keysize 2048 -validity 10000
Simple ... use OSGi. In OSGi you can iterate over your Bundle's entries with findEntries and findPaths.
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
If you let dynamic SQL create a temp table, this table is owned by the Dynamic SQL connection, as opposed to the connection your stored procedure is called from.
DECLARE @COMMA_SEPARATED_KEYS varchar(MAX);
DROP TABLE IF EXISTS KV;
CREATE TABLE KV (id_person int, mykey varchar(30), myvalue int);
INSERT INTO KV VALUES
(1, 'age', 16),
(1, 'weight', 63),
(1, 'height', 175),
(2, 'age', 26),
(2, 'weight', 83),
(2, 'height', 185);
WITH cte(mykey) AS (
SELECT DISTINCT mykey FROM KV
)
SELECT @COMMA_SEPARATED_KEYS=STRING_AGG(mykey,',') FROM cte;
SELECT @COMMA_SEPARATED_KEYS AS keys;
DECLARE @ExecuteExpression varchar(MAX);
DROP TABLE IF EXISTS #Pivoted;
SET @ExecuteExpression = N'
SELECT *
INTO #Pivoted
FROM
(
SELECT
mykey,
myvalue,
id_person
FROM KV
) AS t
PIVOT(
MAX(t.myvalue)
FOR mykey IN (COMMA_SEPARATED_KEYS)
) AS pivot_table;
';
SET @ExecuteExpression = REPLACE(@ExecuteExpression, 'COMMA_SEPARATED_KEYS', @COMMA_SEPARATED_KEYS);
EXEC(@ExecuteExpression);
SELECT * FROM #Pivoted;
Msg 208, Level 16, State 0 Invalid object name '#Pivoted'. This is because #Pivoted is owned by the Dynamic SQL connection. So the last instruction
SELECT * FROM #Pivoted
fails.
One way to not face this issue is to make sure all references to #Pivoted are made from inside the dynamic query itself:
DECLARE @COMMA_SEPARATED_KEYS varchar(MAX);
DROP TABLE IF EXISTS KV;
CREATE TABLE KV (id_person int, mykey varchar(30), myvalue int);
INSERT INTO KV VALUES
(1, 'age', 16),
(1, 'weight', 63),
(1, 'height', 175),
(2, 'age', 26),
(2, 'weight', 83),
(2, 'height', 185);
WITH cte(mykey) AS (
SELECT DISTINCT mykey FROM KV
)
SELECT @COMMA_SEPARATED_KEYS=STRING_AGG(mykey,',') FROM cte;
SELECT @COMMA_SEPARATED_KEYS AS keys;
DECLARE @ExecuteExpression varchar(MAX);
DROP TABLE IF EXISTS #Pivoted;
SET @ExecuteExpression = N'
SELECT *
INTO #Pivoted
FROM
(
SELECT
mykey,
myvalue,
id_person
FROM KV
) AS t
PIVOT(
MAX(t.myvalue)
FOR mykey IN (COMMA_SEPARATED_KEYS)
) AS pivot_table;
SELECT * FROM #Pivoted;
';
SET @ExecuteExpression = REPLACE(@ExecuteExpression, 'COMMA_SEPARATED_KEYS', @COMMA_SEPARATED_KEYS);
EXEC(@ExecuteExpression);
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
Minimal runnable example
main.cpp
#include <cassert>
class C {
public:
int i;
C(int i) : i(i) {}
int m(int j) { return this->i + j; }
};
int main() {
// Get a method pointer.
int (C::*p)(int) = &C::m;
// Create a test object.
C c(1);
C *cp = &c;
// Operator .*
assert((c.*p)(2) == 3);
// Operator ->*
assert((cp->*p)(2) == 3);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Tested in Ubuntu 18.04.
You cannot change the order of the parenthesis or omit them. The following do not work:
c.*p(2)
c.*(p)(2)
GCC 9.2 would fail with:
main.cpp: In function ‘int main()’:
main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
19 | assert(c.*p(2) == 3);
|
C++11 standard
.*
and ->*
are a single operators introduced in C++ for this purpose, and not present in C.
.*
and ->*
.Methods in other answers throw OverflowException
if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_
int result = 0;
try {
result = Convert.ToInt32(value);
}
catch (OverflowException) {
if (value > 0) result = int.MaxValue;
else result = int.Minvalue;
}
Here is a solution without using regular expressions:
function onlyDigits(s) {
for (let i = s.length - 1; i >= 0; i--) {
const d = s.charCodeAt(i);
if (d < 48 || d > 57) return false
}
return true
}
where 48 and 57 are the char codes for "0" and "9", respectively.
"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.
The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.
Below can be the required mapping,
<class name="com.example.CompanyEntity" table="COMPANY">
<id name="id" column="COMPANY_ID"/>
<set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
<key column="COMPANY_ID" not-null="true"/>
<one-to-many entity-name="vendorName"/>
</set>
</class>
I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.
SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);
I had to use the Port 587, which is of course the default port over TSL and the did the authentication.
I've always heard them used in the opposite sense:
&
is the reference operator -- it gives you a reference (pointer) to some object
*
is the dereference operator -- it takes a reference (pointer) and gives you back the referred to object;
If you want to convert a character to its corresponding integer, you can do something like this:
int a = (int) 'a';
char b = (char) a;
System.out.println(b);
This happens because in ASCII there are some items that can not be printed normally.
For example, numbers 97 to 122 are integers corresponding to the lowercase letters a to z.
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
Let obj
be your object. Exec:
(_ => _[Object.keys(_).pop()])( obj )
Use for
, something along the lines of:
set content=
for /f "delims=" %%i in ('filename') do set content=%content% %%i
Maybe you’ll have to do setlocal enabledelayedexpansion
and/or use !content!
rather than %content%
. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).
The best batch-file-black-magic-reference I know of is at http://www.rsdn.ru/article/winshell/batanyca.xml. If you don’t know Russian, you still could make some use of the code snippets provided.
I had similar issue with the index.html being cached by the browser or more tricky by middle cdn/proxies (F5 will not help you).
I looked for a solution which verifies 100% that the client has the latest index.html version, luckily I found this solution by Henrik Peinar:
https://blog.nodeswat.com/automagic-reload-for-clients-after-deploy-with-angular-4-8440c9fdd96c
The solution solve also the case where the client stays with the browser open for days, the client checks for updates on intervals and reload if newer version deployd.
The solution is a bit tricky but works like a charm:
ng cli -- prod
produces hashed files with one of them called main.[hash].jsSince Henrik Peinar solution was for angular 4, there were minor changes, I place also the fixed scripts here:
VersionCheckService :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class VersionCheckService {
// this will be replaced by actual hash post-build.js
private currentHash = '{{POST_BUILD_ENTERS_HASH_HERE}}';
constructor(private http: HttpClient) {}
/**
* Checks in every set frequency the version of frontend application
* @param url
* @param {number} frequency - in milliseconds, defaults to 30 minutes
*/
public initVersionCheck(url, frequency = 1000 * 60 * 30) {
//check for first time
this.checkVersion(url);
setInterval(() => {
this.checkVersion(url);
}, frequency);
}
/**
* Will do the call and check if the hash has changed or not
* @param url
*/
private checkVersion(url) {
// timestamp these requests to invalidate caches
this.http.get(url + '?t=' + new Date().getTime())
.subscribe(
(response: any) => {
const hash = response.hash;
const hashChanged = this.hasHashChanged(this.currentHash, hash);
// If new version, do something
if (hashChanged) {
// ENTER YOUR CODE TO DO SOMETHING UPON VERSION CHANGE
// for an example: location.reload();
// or to ensure cdn miss: window.location.replace(window.location.href + '?rand=' + Math.random());
}
// store the new hash so we wouldn't trigger versionChange again
// only necessary in case you did not force refresh
this.currentHash = hash;
},
(err) => {
console.error(err, 'Could not get version');
}
);
}
/**
* Checks if hash has changed.
* This file has the JS hash, if it is a different one than in the version.json
* we are dealing with version change
* @param currentHash
* @param newHash
* @returns {boolean}
*/
private hasHashChanged(currentHash, newHash) {
if (!currentHash || currentHash === '{{POST_BUILD_ENTERS_HASH_HERE}}') {
return false;
}
return currentHash !== newHash;
}
}
change to main AppComponent:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private versionCheckService: VersionCheckService) {
}
ngOnInit() {
console.log('AppComponent.ngOnInit() environment.versionCheckUrl=' + environment.versionCheckUrl);
if (environment.versionCheckUrl) {
this.versionCheckService.initVersionCheck(environment.versionCheckUrl);
}
}
}
The post-build script that makes the magic, post-build.js:
const path = require('path');
const fs = require('fs');
const util = require('util');
// get application version from package.json
const appVersion = require('../package.json').version;
// promisify core API's
const readDir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
console.log('\nRunning post-build tasks');
// our version.json will be in the dist folder
const versionFilePath = path.join(__dirname + '/../dist/version.json');
let mainHash = '';
let mainBundleFile = '';
// RegExp to find main.bundle.js, even if it doesn't include a hash in it's name (dev build)
let mainBundleRegexp = /^main.?([a-z0-9]*)?.js$/;
// read the dist folder files and find the one we're looking for
readDir(path.join(__dirname, '../dist/'))
.then(files => {
mainBundleFile = files.find(f => mainBundleRegexp.test(f));
if (mainBundleFile) {
let matchHash = mainBundleFile.match(mainBundleRegexp);
// if it has a hash in it's name, mark it down
if (matchHash.length > 1 && !!matchHash[1]) {
mainHash = matchHash[1];
}
}
console.log(`Writing version and hash to ${versionFilePath}`);
// write current version and hash into the version.json file
const src = `{"version": "${appVersion}", "hash": "${mainHash}"}`;
return writeFile(versionFilePath, src);
}).then(() => {
// main bundle file not found, dev build?
if (!mainBundleFile) {
return;
}
console.log(`Replacing hash in the ${mainBundleFile}`);
// replace hash placeholder in our main.js file so the code knows it's current hash
const mainFilepath = path.join(__dirname, '../dist/', mainBundleFile);
return readFile(mainFilepath, 'utf8')
.then(mainFileData => {
const replacedFile = mainFileData.replace('{{POST_BUILD_ENTERS_HASH_HERE}}', mainHash);
return writeFile(mainFilepath, replacedFile);
});
}).catch(err => {
console.log('Error with post build:', err);
});
simply place the script in (new) build folder run the script using node ./build/post-build.js
after building dist folder using ng build --prod
I combined a couple of different answers in SO into the following snippet, which should work on all, if not most, modern browsers I believe. All you have to do is add the CSS class .disable-scrollbars
onto the element you wish to apply this to.
.disable-scrollbars::-webkit-scrollbar {
width: 0px;
background: transparent; /* Chrome/Safari/Webkit */
}
.disable-scrollbars {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
}
And if you want to use SCSS/SASS:
.disable-scrollbars {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
&::-webkit-scrollbar {
width: 0px;
background: transparent; /* Chrome/Safari/Webkit */
}
}
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
My favoured method for doing this looks something like:
<xsl:stylesheet>
<xsl:output method='text'/>
<xsl:variable name='newline'><xsl:text>
</xsl:text></xsl:variable>
<!-- note that the layout there is deliberate -->
...
</xsl:stylesheet>
Then, whenever you want to output a newline (perhaps in csv) you can output something like the following:
<xsl:value-of select="concat(elem1,elem2,elem3,$newline)" />
I've used this technique when outputting sql from xml input. In fact, I tend to create variables for commas, quotes and newlines.
list.append
returns None
, since it is an in-place operation and you are assigning it back to dates_dict[key]
. So, the next time when you do dates_dict.get(key, []).append
you are actually doing None.append
. That is why it is failing. Instead, you can simply do
dates_dict.setdefault(key, []).append(date)
But, we have collections.defaultdict
for this purpose only. You can do something like this
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
This will create a new list object, if the key
is not found in the dictionary.
Note: Since the defaultdict
will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.
The text inside $type is substituted directly into the insert string, therefore MySQL gets this:
... VALUES(testing, 'john', 'whatever')
Notice that there are no quotes around testing, you need to put these in like so:
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:
We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.
Our solution was to use the replacer
param of JSON.stringify()
, e.g.:
function jsonFriendlyErrorReplacer(key, value) {_x000D_
if (value instanceof Error) {_x000D_
return {_x000D_
// Pull all enumerable properties, supporting properties on custom Errors_x000D_
...value,_x000D_
// Explicitly pull Error's non-enumerable properties_x000D_
name: value.name,_x000D_
message: value.message,_x000D_
stack: value.stack,_x000D_
}_x000D_
}_x000D_
_x000D_
return value_x000D_
}_x000D_
_x000D_
let obj = {_x000D_
error: new Error('nested error message')_x000D_
}_x000D_
_x000D_
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))_x000D_
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))
_x000D_
I will do like....
(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))
Simply add file named as .keep in images folder.you can now stage and commit and also able to add folder to version control.
Create a empty file in images folder
$ touch .keep
$ git status
On branch master Your branch is up-to-date with 'origin/master'. Untracked files: (use "git add ..." to include in what will be committed) images/ nothing added to commit but untracked files present (use "git add" to track)
$ git add .
$ git commit -m "adding empty folder"
Since the OP question has already been answered above I just want to add some speed considerations:
It makes a lot of difference what priority class you assign to your async function in DispatchQueue.global.
I don't recommend running tasks with the .background thread priority especially on the iPhone X where the task seems to be allocated on the low power cores.
Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:
Device name / .background / .utility / .default / .userInitiated / .userInteractive
Note that the data set is not the same for all devices. It's the biggest on the iPhone X and the smallest on the iPhone 5s.
border-radius: 50%;
will turn all elements into a circle, regardless of size. At least, as long as the height
and width
of the target are the same, otherwise it will turn into an oval.
#target{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div id="target"></div>
_x000D_
Note: browser prefixes are not needed anymore for border-radius
Alternatively, you can use clip-path: circle();
to turn an element into a circle as well. Even if the element has a greater width
than height
(or the other way around), it will still become a circle, and not an oval.
#target{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
clip-path: circle();_x000D_
}
_x000D_
<div id="target"></div>
_x000D_
Note: clip-path is not (yet) supported by all browsers
You can place text inside of the circle, simply by writing the text inside of the tags of the target,
like so:
<div>text</div>
If you want to center text in the circle, you can do the following:
#target{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
border-radius: 50%;_x000D_
_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
#text{_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="target">_x000D_
<div id="text">text</div>_x000D_
</div>
_x000D_
I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].
new DecimalFormat("#0.##").format(bd)
<asp:RadioButtonList ID="rblRequestType">
<asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
<asp:ListItem Value="Value2">Value2</asp:ListItem>
</asp:RadioButtonList>
You can set checked like this.
var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");
radio0.checked = true;
radio1.checked = true;
Typescript implementation based on top rated answer
/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
private _start: Date;
private _remaining: number;
private _durationTimeoutId?: NodeJS.Timeout;
private _callback: (...args: any[]) => void;
private _done = false;
get done () {
return this._done;
}
constructor(callback: (...args: any[]) => void, ms = 0) {
this._callback = () => {
callback();
this._done = true;
};
this._remaining = ms;
this.resume();
}
/** pauses the timer */
pause(): Timer {
if (this._durationTimeoutId && !this._done) {
this._clearTimeoutRef();
this._remaining -= new Date().getTime() - this._start.getTime();
}
return this;
}
/** resumes the timer */
resume(): Timer {
if (!this._durationTimeoutId && !this._done) {
this._start = new Date;
this._durationTimeoutId = setTimeout(this._callback, this._remaining);
}
return this;
}
/**
* clears the timeout and marks it as done.
*
* After called, the timeout will not resume
*/
clearTimeout() {
this._clearTimeoutRef();
this._done = true;
}
private _clearTimeoutRef() {
if (this._durationTimeoutId) {
clearTimeout(this._durationTimeoutId);
this._durationTimeoutId = undefined;
}
}
}
As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019
if we had Kia enter
.native
and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the.native
modifier which I currently consider an anti-pattern will be removed in Vue 3 you'll be able to explicitly define that the parent might care about which element listeners are added to...
$listeners
:So, if you are using Vue 2 a better option to resolve this issue would be to use a fully transparent wrapper logic. For this Vue provides a $listeners
property containing an object of listeners being used on the component. For example:
{
focus: function (event) { /* ... */ }
input: function (value) { /* ... */ },
}
and then we just need to add v-on="$listeners"
to the test
component like:
Test.vue (child component)
<template>
<div v-on="$listeners">
click here
</div>
</template>
Now the <test>
component is a fully transparent wrapper, meaning it can be used exactly like a normal <div>
element: all the listeners will work, without the .native
modifier.
Demo:
Vue.component('test', {_x000D_
template: `_x000D_
<div class="child" v-on="$listeners">_x000D_
Click here_x000D_
</div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
el: "#myApp",_x000D_
data: {},_x000D_
methods: {_x000D_
testFunction: function(event) {_x000D_
console.log('test clicked')_x000D_
}_x000D_
}_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
<test @click="testFunction"></test>_x000D_
</div>
_x000D_
$emit
method:We can also use $emit
method for this purpose, which helps us to listen to child components events in parent component. For this, we first need to emit a custom event from child component like:
Test.vue (child component)
<test @click="$emit('my-event')"></test>
Important: Always use kebab-case for event names. For more information and demo regading this point please check out this answer: VueJS passing computed value from component to parent.
Now, we just need to listen to this emitted custom event in parent component like:
App.vue
<test @my-event="testFunction"></test>
So, basically instead of v-on:click
or the shorthand @click
we will simply use v-on:my-event
or just @my-event
.
Demo:
Vue.component('test', {_x000D_
template: `_x000D_
<div class="child" @click="$emit('my-event')">_x000D_
Click here_x000D_
</div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
el: "#myApp",_x000D_
data: {},_x000D_
methods: {_x000D_
testFunction: function(event) {_x000D_
console.log('test clicked')_x000D_
}_x000D_
}_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
<test @my-event="testFunction"></test>_x000D_
</div>
_x000D_
v-bind="$attrs"
:Vue 3 is going to make our life much easier in many ways. One of the examples for it is that it will help us to create a simpler transparent wrapper with very less config by just using v-bind="$attrs"
. By using this on child components not only our listener will work directly from the parent but also any other attribute will also work just like it a normal <div>
only.
So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine as <div>
is the root element here and it will automatically listen to all child events.
Demo #1:
const { createApp } = Vue;_x000D_
_x000D_
const Test = {_x000D_
template: `_x000D_
<div class="child">_x000D_
Click here_x000D_
</div>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
components: { Test },_x000D_
setup() {_x000D_
const testFunction = event => {_x000D_
console.log("test clicked");_x000D_
};_x000D_
return { testFunction };_x000D_
}_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
<test v-on:click="testFunction"></test>_x000D_
</div>
_x000D_
But for complex components with nested elements where we need to apply attributes and events to main <input />
instead of the parent label we can simply use v-bind="$attrs"
Demo #2:
const { createApp } = Vue;_x000D_
_x000D_
const BaseInput = {_x000D_
props: ['label', 'value'],_x000D_
template: `_x000D_
<label>_x000D_
{{ label }}_x000D_
<input v-bind="$attrs">_x000D_
</label>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
components: { BaseInput },_x000D_
setup() {_x000D_
const search = event => {_x000D_
console.clear();_x000D_
console.log("Searching...", event.target.value);_x000D_
};_x000D_
return { search };_x000D_
}_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
input{padding:8px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
<base-input _x000D_
label="Search: "_x000D_
placeholder="Search"_x000D_
@keyup="search">_x000D_
</base-input><br/>_x000D_
</div>
_x000D_
A compiler may place structure members on particular byte boundaries for reasons of performance on a particular architecture. This may leave unused padding between members. Structure packing forces members to be contiguous.
This may be important for example if you require a structure to conform to a particular file or communications format where the data you need the data to be at specific positions within a sequence. However such usage does not deal with endian-ness issues, so although used, it may not be portable.
It may also to exactly overlay the internal register structure of some I/O device such as a UART or USB controller for example, in order that register access be through a structure rather than direct addresses.
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
I would recommend %20
.
Are you hard-coding them?
This is not very consistent across languages, though.
If I'm not mistaken, in PHP urlencode()
treats spaces as +
whereas Python's urlencode()
treats them as %20
.
EDIT:
It seems I'm mistaken. Python's urlencode()
(at least in 2.7.2) uses quote_plus()
instead of quote()
and thus encodes spaces as "+".
It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.
EDIT #2:
I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:
import urllib
print(urllib.urlencode({' ' : '+ '})
>>> '+=%2B+'
If you are using 'docker-compose' as the method to spin up your container(s), there is actually a useful way to pass an environment variable defined on your server to the Docker container.
In your docker-compose.yml
file, let's say you are spinning up a basic hapi-js container and the code looks like:
hapi_server:
container_name: hapi_server
image: node_image
expose:
- "3000"
Let's say that the local server that your docker project is on has an environment variable named 'NODE_DB_CONNECT' that you want to pass to your hapi-js container, and you want its new name to be 'HAPI_DB_CONNECT'. Then in the docker-compose.yml
file, you would pass the local environment variable to the container and rename it like so:
hapi_server:
container_name: hapi_server
image: node_image
environment:
- HAPI_DB_CONNECT=${NODE_DB_CONNECT}
expose:
- "3000"
I hope this helps you to avoid hard-coding a database connect string in any file in your container!
xargs
is the most flexible solution for splitting output into command arguments.
It is also very human readable and easy to use due to its simple parameterisation.
Format is xargs -n $NUMLINES mycommand
.
For example, to echo
each individual line in a file /tmp/tmp.txt
you'd do:
cat /tmp/tmp.txt | xargs -n 1 echo
Or to diff
each successive pair of files listed as lines in a file of the above name you'd do:
cat /tmp/tmp.txt | xargs -n 2 diff
The -n 2
instructs xargs
to consume and pass as separate arguments two lines of what you've piped into it at a time.
You can tailor xargs
to split on delimiters besides carriage return/newline.
Use man xargs
and google to find out more about the power of this versatile utility.
SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2®ion=0&page=1', LEN(URL))
Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx
To fix your issue, i have made few changes in bla.js and it is working,
var foo= function (req, res, next) {
console.log('inside foo');
return ("foo");
}
var bar= function(req, res, next) {
this.foo();
}
module.exports = {bar,foo};
and no modification in app.js
var bla = require('./bla.js');
console.log(bla.bar());
Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:
https://support.google.com/accounts/answer/185833
Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.
I had a similar issue however found a different solution than what I have read. I came to my fix after reading P Walker's answer.
My issue happened when I named my resource file for Japanese language incorrectly. Long story short I was trying to create a Resource for Japanese but I accidentally named it localized.jp.resx. I then realized that the iso language code is ja not jp for Japanese. Once I changed the file name to localized.ja.resx and deleted everything that was in the designer file it fixed my problem.
This is what fixed my problem hopefully it helps someone else.
If you read JavaScript The Good Parts, you'll see that Crockford's replacement for i++ in a for loop is i+=1 (not i=i+1). That's pretty clean and readable, and is less likely to morph into something "tricky."
Crockford made disallowing autoincrement and autodecrement an option in jsLint. You choose whether to follow the advice or not.
My own personal rule is to not do anything combined with autoincrement or autodecrement.
I've learned from years of experience in C that I don't get buffer overruns (or array index out of bounds) if I keep use of it simple. But I've discovered that I do get buffer overruns if I fall into the "excessively tricky" practice of doing other things in the same statement.
So, for my own rules, the use of i++ as the increment in a for loop is fine.
From reading all the answers here, I have assembled a simplified solution that does not require any external libraries.
It also illustrates much better the general idea for the approach:
function processQ() {
// ... this will be called on each .push
}
var myEventsQ = [];
myEventsQ.push = function() { Array.prototype.push.apply(this, arguments); processQ();};
Just one note I could not find in the answers above. In this code:
context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)
What the third parameter context_instance
actually does? Being RequestContext it sets up some basic context which is then added to user_context
. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS
in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user
and variable perm
which are then accessible in the template.
You can try CustomScrollView
. Put your CustomScrollView inside Column Widget.
Just for example -
class App extends StatelessWidget {
App({Key key}): super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: new Container(
constraints: BoxConstraints.expand(),
decoration: new BoxDecoration(
image: new DecorationImage(
alignment: Alignment.topLeft,
image: new AssetImage('images/main-bg.png'),
fit: BoxFit.cover,
)
),
child: new Column(
children: <Widget>[
Expanded(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 0.0),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(context, index) => new YourRowWidget(),
childCount: 5,
),
),
),
],
),
),
],
)),
);
}
}
In above code I am displaying a list of items ( total 5) in CustomScrollView.
YourRowWidget
widget gets rendered 5 times as list item. Generally you should render each row based on some data.
You can remove decoration property of Container widget, it is just for providing background image.
On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeObject:self.question forKey:@"question"];
[encoder encodeObject:self.categoryName forKey:@"category"];
[encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
//decode properties, other class vars
self.question = [decoder decodeObjectForKey:@"question"];
self.categoryName = [decoder decodeObjectForKey:@"category"];
self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
}
return self;
}
Reading and writing from NSUserDefaults
:
- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodedObject forKey:key];
[defaults synchronize];
}
- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
Code shamelessly borrowed from: saving class in nsuserdefaults
There are two ways of retrieving the version:
package.json
and getting the version:const { version } = require('./package.json');
const version = process.env.npm_package_version;
Please don't use JSON.parse
, fs.readFile
, fs.readFileSync
and don't use another npm modules
it's not necessary for this question.
As mentioned before use apache commons codec. It's recommended by Spring guys as well (see DigestUtils in Spring doc). E.g.:
DigestUtils.sha1Hex(b);
Definitely wouldn't use the top rated answer here.
case statement some what similar to if in SQL server
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
You can use optimizer hints
select /*+ INDEX(table_name index_name) */ from table
etc...
More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm
I'm developing an UWP application which connects to a MQTT broker in the LAN. I go a similar error.
MQTTnet.Exceptions.MqttCommunicationException: 'An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883'
ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions [::ffff:xxx.xxx.xxx.xxx]:1883
Turned out that I forgot to give the app the correct capabilites ...
This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:
DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
Change color values in the array
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(Color.parseColor("#008000"),
Color.parseColor("#ADFF2F"))
);
gradientDrawable.cornerRadius = 0f;
//Set Gradient
linearLayout.setBackground(gradientDrawable);
Result
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
This is a good usecase for pythonpy:
curl 'http://twitter.com/users/username.json' | py 'json.load(sys.stdin)["name"]'
Updated mysqli version:
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
echo "Table exists";
}
}
else {
echo "Table does not exist";
}
Original mysql version:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
Referenced from the PHP docs.
By adding your own "Exception Handling Middleware", makes it hard to reuse some good built-in logic of Exception Handler like send an "RFC 7807-compliant payload to the client" when an error happens.
What I made was to extend built-in Exception handler outside of the Startup.cs
class to handle custom exceptions or override the behavior of existing ones. For example, an ArgumentException and convert into BadRequest without changing the default behavior of other exceptions:
on the Startup.cs
add:
app.UseExceptionHandler("/error");
and extend ErrorController.cs with something like this:
using System;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
namespace Api.Controllers
{
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[AllowAnonymous]
public class ErrorController : ControllerBase
{
[Route("/error")]
public IActionResult Error(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exceptionType = context.Error.GetType();
if (exceptionType == typeof(ArgumentException)
|| exceptionType == typeof(ArgumentNullException)
|| exceptionType == typeof(ArgumentOutOfRangeException))
{
if (webHostEnvironment.IsDevelopment())
{
return ValidationProblem(
context.Error.StackTrace,
title: context.Error.Message);
}
return ValidationProblem(context.Error.Message);
}
if (exceptionType == typeof(NotFoundException))
{
return NotFound(context.Error.Message);
}
if (webHostEnvironment.IsDevelopment())
{
return Problem(
context.Error.StackTrace,
title: context.Error.Message
);
}
return Problem();
}
}
}
Note that:
NotFoundException
is a custom exception and all you need to do is throw new NotFoundException(null);
or throw new ArgumentException("Invalid argument.");
USCOUNTER=$(grep -c "^US " "$FILE")
The difference is that the uint
and ulong
are unsigned data types, meaning the range is different: They do not accept negative values:
int range: -2,147,483,648 to 2,147,483,647
uint range: 0 to 4,294,967,295
long range: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong range: 0 to 18,446,744,073,709,551,615
If you are using Angular UI Router, you can listen for the $viewContentLoaded
event.
"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link
$scope.$on('$viewContentLoaded',
function(event){ ... });
You can use a lambda expression, e.g:
sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
You'd need to use return values.
DECLARE @SelectedValue int
CREATE PROCEDURE GetMyInt (@MyIntField int OUTPUT)
AS
SELECT @MyIntField = MyIntField FROM MyTable WHERE MyPrimaryKeyField = 1
Then you call it like this:
EXEC GetMyInt OUTPUT @SelectedValue
The documentation says
The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.
So this particular format can be controlled with postgres
date time output, eg:
t=# select now();
now
-------------------------------
2017-11-29 09:15:25.348342+00
(1 row)
t=# set datestyle to DMY, SQL;
SET
t=# select now();
now
-------------------------------
29/11/2017 09:15:31.28477 UTC
(1 row)
t=# select now()::date;
now
------------
29/11/2017
(1 row)
Mind that as @Craig mentioned in his answer, changing datestyle
will also (and in first turn) change the way postgres parses date.
Syntax:
transition: <property> || <duration> || <timing-function> || <delay> [, ...];
Note that the duration must come before the delay, if the latter is specified.
Individual transitions combined in shorthand declarations:
-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
Or just transition them all:
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
Here is a straightforward example. Here is another one with the delay property.
Edit: previously listed here were the compatibilities and known issues regarding transition
. Removed for readability.
Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.
If you still want to be sure, refer to http://caniuse.com/css-transitions
Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .
var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {
conn.db.collection(" collection ", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // data printed in console
})
});
});
Happy to Help. by RTTSS.
You're looking for:
.is(':visible')
Although you should probably change your selector to use jQuery considering you're using it in other places anyway:
if($('#testElement').is(':visible')) {
// Code
}
It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible')
on the child will return false
(which makes sense).
:visible
has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible
):
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle()
:
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}
If you are trying to call getClass()
from Static method or static block the you can do the following way.
You can call getClass()
on the Properties
object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml;
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}
mongo-db
is likely not a great choice for new developers.
On the other hand mongoose
as an ORM (Object Relational Mapping) can be a better choice for the new-bies.
Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:
class C(object):
def foo(self):
pass
Now let's have a look at that class in the shell:
>>> C.foo
<unbound method C.foo>
>>> C.__dict__['foo']
<function foo at 0x17d05b0>
As you can see if you access the foo
attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a __getattribute__
that resolves descriptors. Sounds complex, but is not. C.foo
is roughly equivalent to this code in that special case:
>>> C.__dict__['foo'].__get__(None, C)
<unbound method C.foo>
That's because functions have a __get__
method which makes them descriptors. If you have an instance of a class it's nearly the same, just that None
is the class instance:
>>> c = C()
>>> C.__dict__['foo'].__get__(c, C)
<bound method C.foo of <__main__.C object at 0x17bd4d0>>
Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where staticmethod
comes into play:
class C(object):
@staticmethod
def foo():
pass
The staticmethod
decorator wraps your class and implements a dummy __get__
that returns the wrapped function as function and not as a method:
>>> C.__dict__['foo'].__get__(None, C)
<function foo at 0x17d0c30>
Hope that explains it.
Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.
I don't need to set the country in parameter if my phone number begins with "+". Here is an example :
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
// phone must begin with '+'
PhoneNumber numberProto = phoneUtil.parse(phone, "");
int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
I did it in this way.
In tasks/main.yml
- name: template test
template:
src=myTemplateFile.j2
dest={{item}}
with_dict: some_dict
and in vars/main.yml
some_dict:
/path/to/dest1:
var1: 1
var2: 2
/path/to/dest2:
var1: 3
var2: 4
and in templates/myTemplateFile.j2
some_var = {{ item.value.var1 }}
some_other_var = {{ item.value.var2 }}
Hope this solves your problem.
Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.
If you're using org.json, JSONObject has a method toMap()
.
You can easily do:
Map<String, Object> myMap = myJsonObject.toMap();
To add an Activity
using Android Studio.
This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.
[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.
To add a Service
, or a BroadcastReceiver
, just do the same step.
I had the same problem, and found that the solution was to add the android:tools to the first node. In my case it is a LineraLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
You can do it manually. (I know, that that isn't great solution, but..)
use while
loop till the result
hasn't a value
kickOff().then(function(result) {
while(true){
if (result === undefined) continue;
else {
$("#output").append(result);
return;
}
}
});
You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with
basename $0
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
You have to add repositories
to your build file. For maven repositories you have to prefix repository name with maven{}
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
The mistake:
I git rebase -i --root
'ed my branch, ignorantly thinking I could reword the first commit differing from the master (the GitHub for Windows default view is the comparison to master, hiding it's entirety).
I grew a Silicon Valley beard while 900+ commits loaded themselves into Sublime. Exiting with no changes, I charged my battery then proceeded to shave, as all 900+ individual commits nonchalantly rebased - resetting their commit times to now.
Determined to beat Git and preserve the original times, I deleted this local repository and re-cloned from the remote.
Now it had re-added a most recent unneeded commit to master I wished to remove, so proceeded like so.
Exhausting the options:
I didn't wish to git revert
- it would create an additional commit, giving Git the upper hand.
git reset --hard HEAD
did nothing, after checking the reflog
, the last and only HEAD
was the clone - Git wins.
To get the most recent SHA, I checked the remote repository on github.com - minor win.
After thinking git reset --hard <SHA>
had worked, I updated another branch to master and 1... 2... poof! the commit was back - Git wins.
Checking back out to master, time to try git rebase -i <SHA>
, then remove the line... to no avail, sad to say. "If you remove a line here THAT COMMIT WILL BE LOST". Ah...glossed over new feature troll the n00b in the 2.8.3 release notes.
The solution:
git rebase -i <SHA>
then d, drop = remove commit
.
To verify, I checked out to another branch, and voila - no hiding commit to fetch/pull from the master.
https://twitter.com/holman/status/706006896273063936
Good day to you.
Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on
Start a site and the process will be launched for you.
Try this
Option Explicit
Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long
myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs
Set uniqueRng = GetUniqueValues(ws, myCol)
End Sub
Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long
With ws
.Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo
firstRow = 1
If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row
Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With
End Function
it should be quite fast and without the drawback NeepNeepNeep told about
You can use external library:
org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
It is in project Apache Commons Lang http://commons.apache.org/lang/
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
You can use operator.setitem
.
from operator import setitem
a = [5, 4, 3, 2, 1, 0]
ell = [0, 1, 3, 5]
m = [0, 0, 0, 0]
for b, c in zip(ell, m):
setitem(a, b, c)
>>> a
[0, 0, 3, 0, 1, 0]
Is it any more readable or efficient than your solution? I am not sure!
You can use some functional programming approach, transforming data:
['12','34','35','231'].map{|i| "'#{i}'"}.join(",")
This is iteration using block approach:
NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@->%@",key,obj);
// Set stop to YES when you wanted to break the iteration.
}];
With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.
This table might be helpful for you:
Going down the first column, you will see how the log works in each level. i.e for WARN, (FATAL, ERROR and WARN) will be visible. For OFF, nothing will be visible.
I have found a solution in Python that is working well !
from math import atan2,degrees
def GetAngleOfLineBetweenTwoPoints(p1, p2):
return degrees(atan2(p2 - p1, 1))
print GetAngleOfLineBetweenTwoPoints(1,3)
The one that worked for me is:
grep -e '->'
The -e means that the next argument is the pattern, and won't be interpreted as an argument.
From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
It sounds like you need to use recursion. Make a function to iterate through a list, and if it hits an item that is also a list, call itself to iterate on the member. Here's a link to something similar:
http://www.saltycrane.com/blog/2008/08/python-recursion-example-navigate-tree-data/
Here is all the information you need in order to format clickable hyperlinks in LaTeX:
http://en.wikibooks.org/wiki/LaTeX/Hyperlinks
Essentially, you use the hyperref
package and use the \url
or \href
tag depending on what you're trying to achieve.
For .NET Core, this is how I'll know the version of EntityFramework that I'm using. Let's assume that the name of my project is DemoApi, I have the following at my disposal:
dotnet list DemoApi.csproj package
Use
python python_script.py filename
and in your Python script
import sys
print sys.argv[1]
If you need just build the project or solution locally then removing the signing might be a dead simple solution as others suggest.
But if you have this error on your automation build server like TeamCity where you build your actual release pieces for deployment or distribution you might want to consider how you can get this cert properly installed to the cert store on the build machine, so that you get a signed packages at the end of the build.
Generally it is not recommenced to check-in/commit any PFX certificates into source control, so how you get this files on your build server during the build process is a bit another question, but sometimes people do have this file stored along with the solution code, so you can find it in the project folder.
All you need to do is just install this certificate under proper account on your build server.
Download PsExec from Windows Sysinternals.
Open a command prompt, and enter the following. It will spawn a new command prompt, running as Local System (assuming that your TeamCity is running under the default Local System account):
> psexec.exe -i -s cmd.exe
In this new command prompt, change to the directory containing the certificate and enter the filename to install (change the name of the file to yours):
> mykey.pfx
The Import Certificate wizard will start up. Click through and select all the suggested defaults.
Run the build.
All credits goes to Stuart Noble (and then further to Laurent Kempé I believe ?).
display:none
will hide the element and collapse the space is was taking up, whereas visibility:hidden
will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.
Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>>
or List<KeyValuePair<string, string>>
if you're not using .NET 4.
Here's my example in which I work
it's simple, use the "-B" option to add .h files' dir to search path.
E.g. g++ -B /header_file.h your.cpp -o bin/your_command
One trick I found was putting your setOnItemSelectedListeners in onWindowFocusChanged instead of onCreate. I haven't found any bad side-effects to doing it this way, yet. Basically, set up the listeners after the window gets drawn. I'm not sure how often onWindowFocusChanged runs, but it's easy enough to create yourself a lock variable if you are finding it running too often.
I think Android might be using a message-based processing system, and if you put it all in onCreate, you may run into situations where the spinner gets populated after it gets drawn. So, your listener will fire off after you set the item location. This is an educated guess, of course, but feel free to correct me on this.
I also got the following error when I run a command with PHP
, I did the solution like that:
C:\xampp\php
to your PATH Environment Variable.Very important note: restart command prompt
If you can't do
UPDATE table SET a=value WHERE x IN
(SELECT x FROM table WHERE condition);
because it is the same table, you can trick and do :
UPDATE table SET a=value WHERE x IN
(SELECT * FROM (SELECT x FROM table WHERE condition) as t)
[update or delete or whatever]
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
it appears that if you locate your jquery.js files under the same folder or in some subfolders where your html file is, the Firebug problem is solved. eg if your html is under C:/folder1/, then your js files should be somewhere under C:/folder1/ (or C:/folder1/folder2 etc) as well and addressed accordingly in the html doc. hope this helps.
The other answers assume that the array contains strings. My method is better, because it will work even if the array contains null, undefined, or other non-strings.
var notdefined;
var myarray = ['a', 'c', null, notdefined, 'nulk', 'BYE', 'nulm'];
myarray.sort(ignoreCase);
alert(JSON.stringify(myarray)); // show the result
function ignoreCase(a,b) {
return (''+a).toUpperCase() < (''+b).toUpperCase() ? -1 : 1;
}
The null
will be sorted between 'nulk' and 'nulm'. But the undefined
will be always sorted last.
Easiest way is to use System.Linq as previously described
using System.Linq;
public int GetHighestValue(List<MyTypes> list)
{
return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}
This is also possible with a Dictionary
using System.Linq;
public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}
Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.
For example, I have a DEV_DB tablespace with all my actual 'databases' within them:
SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;
Resulting in:
SYSTEM SYSAUX UNDOTBS1 TEMP USERS EXAMPLE DEV_DB
It is also possible to query the users in all tablespaces:
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;
Or within a specific tablespace (using my DEV_DB tablespace as an example):
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';
ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB
For Angular 7+ (Also Supports 8, 9, 10, 11):
1: Install moment by command npm install moment --save
2: Do not add anything in the app.module.ts
3: Just add import statement in top of your component
or any other file like this: import * as moment from 'moment';
4: Now you can use moment
anywhere in your code. Just like:
myDate = moment(someDate).format('MM/DD/YYYY HH:mm');
In C, unlike say C++, you would need a format specifier that states the datatype of the variable you want to print-in this case %d as the data type is an integer . Try printf("%d",addNumbers(a,b));
Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.
You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.
class MObject {
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };
OR by parameterized constructor
class MObject {
public MObject(int code, string org)
{
Code = code;
Org = org;
}
public int Code { get; set; }
public string Org { get; set; }
}
List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};
SQL Statement:
SELECT * FROM employee WHERE employeeName LIKE 'A%';
Result:
Number of Records: 4
employeeID employeeName employeeName Address City PostalCode Country
1 Alam Wipro Delhi Delhi 11005 India
2 Aditya Wipro Delhi Delhi 11005 India
3 Alok HCL Delhi Delhi 11005 India
4 Ashok IBM Delhi Delhi 11005 India