Python version >= 2.7, do the below:
d = {i: True for i in [1,2,3]}
Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:
d = dict((i,True) for i in [1,2,3])
"Wokbench.panel.defaultLocation": "right"
Open settings using CTRL+.
, search for terminal
and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.
In your main styles.css
file change height/auto to whatever settings you desire. For example, 500px
:
#myCarousel {
height: auto;
width: auto;
overflow: hidden;
}
You can use the --system-site-packages
and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.
Unpack them:
word = "Paralelepipedo"
print([*word])
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"":'',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as
json.property_name
This will work as long as the image you want to rotate is already in your Properties resources folder.
In Partial Class:
Bitmap bmp2;
OnLoad:
bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox6.Image = bmp2;
Button or Onclick
private void pictureBox6_Click(object sender, EventArgs e)
{
if (bmp2 != null)
{
bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox6.Image = bmp2;
}
}
Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.
Though V8 makes available the --max_old_space_size
option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.
It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.
I had a similar issue I was getting the entire object in this
but the value was displaying while doing #each
.
Solution: I re-structure my array of object like this:
let list = results.map((item)=>{
return { name:item.name, author:item.author }
});
and then in template file:
{{#each list}}
<tr>
<td>{{name }}</td>
<td>{{author}}</td>
</tr>
{{/each}}
I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:
public String loadResourceAsString(String fileName) throws IOException {
Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
String contents = scanner.useDelimiter("\\A").next();
scanner.close();
return contents;
}
"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()
RealVNC 5.0.x now offers a VNCViewer that will do dual displays on Windows without having to buy a license. (Licensing now covers the SERVER portion of their tools).
self:: keyword used for the current class and basically it is used to access static members, methods, and constants. But in case of $this you cannot call the static member, method and functions.
You can use the self:: keyword in another class and access the static members, method and constants. When it will be extends from parent class and same in case of $this keyword. You can access the non static members, method and function in another class when it will be extends from parent class.
The code given below is a example of self:: and $this keyword. Just copy and paste the code in your code file and see the output.
class cars{
var $doors=4;
static $car_wheel=4;
public function car_features(){
echo $this->doors." Doors <br>";
echo self::$car_wheel." Wheels <br>";
}
}
class spec extends cars{
function car_spec(){
print(self::$car_wheel." Doors <br>");
print($this->doors." Wheels <br>");
}
}
/********Parent class output*********/
$car = new cars;
print_r($car->car_features());
echo "------------------------<br>";
/********Extend class from another class output**********/
$car_spec_show=new spec;
print($car_spec_show->car_spec());
You can use:
width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;
EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/
I assume you want to link to a library called foo, its filename is usually something link foo.dll
or libfoo.so
.
1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB
use
find_library(FOO_LIB foo)
CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib
, /usr/lib64
and the paths in PATH
.
You already know the location of your library. Add it to the CMAKE_PREFIX_PATH
when you call CMake, then CMake will look for your library in the passed paths, too.
Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html
2. Link the library
From 1. you have the full library name in FOO_LIB
. You use this to link the library to your target GLBall
as in
target_link_libraries(GLBall PRIVATE "${FOO_LIB}")
You should add PRIVATE
, PUBLIC
, or INTERFACE
after the target, cf. the documentation:
https://cmake.org/cmake/help/latest/command/target_link_libraries.html
If you don't add one of these visibility specifiers, it will either behave like PRIVATE
or PUBLIC
, depending on the CMake version and the policies set.
3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path
similar to find_library
and search for a header file. Then add the include directory with target_include_directories
similar to target_link_libraries
.
Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html
If available for the external software, you can replace find_library
and find_path
by find_package
.
Here is a working version with your bugs removed.
$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
//$proxyauth = 'user:password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
echo $curl_scraped_page;
I have added CURLOPT_PROXYUSERPWD
in case any of your proxies require a user name and password.
I set CURLOPT_RETURNTRANSFER
to 1, so that the data will be returned to $curl_scraped_page
variable.
I removed a second extra curl_exec($ch);
which would stop the variable being returned.
I consolidated your proxy IP and port into one setting.
I also removed CURLOPT_HTTPPROXYTUNNEL
and CURLOPT_CUSTOMREQUEST
as it was the default.
If you don't want the headers returned, comment out CURLOPT_HEADER
.
To disable the proxy simply set it to null.
curl_setopt($ch, CURLOPT_PROXY, null);
Any questions feel free to ask, I work with cURL
every day.
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
bool
is an alias for System.Boolean
just as int
is an alias for System.Int32
. See a full list of aliases here: Built-In Types Table (C# Reference).
I have tried all solutions, they are very useful but this only works fine for me
public class LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
if (getOrientation() == HORIZONTAL) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
heightSpec,
mMeasuredDimension);
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
measureScrapChild(recycler, i,
widthSpec,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
if (height < heightSize || width < widthSize) {
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
recycler.bindViewToPosition(view, position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
use <strong>
or <b>
tag
also, you can try with css <span style="font-weight:bold">text</span>
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
You may want to use Vim global marks.
This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short:
'C
takes me to the code I'm working with,
'T
takes me to the unit test I'm working with.
When you change places, resetting the marks is quick too:
mC
marks the new code spot,
mT
marks the new test spot.
Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.
I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout
(when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.
99.9% likely that you have corrupted memory (over- or under-flowed a buffer, wrote to a pointer after it was freed, called free twice on the same pointer, etc.)
Run your code under Valgrind to see where your program did something incorrect.
I can highly recommend checking out the Visual Studio plugin ReSharper. It has a QuickFix feature that does the same (and a lot more).
But ReSharper doesn't require the cursor to be located on the actual code that requires a new namespace. Say, you copy/paste some code into the source file, and just a few clicks of Alt + Enter, and all the required usings are included.
Oh, and it also makes sure that the required assembly reference is added to your project. Say for example, you create a new project containing NUnit unit tests. The first class you write, you add the [TestFixture] attribute. If you already have one project in your solution that references the NUnit DLL file, then ReSharper is able to see that the TestFixtureAttribute comes from that DLL file, so it will automatically add that assembly reference to your new project.
And it also adds required namespaces for extension methods. At least the ReSharper version 5 beta does. I'm pretty sure that Visual Studio's built-in resolve function doesn't do that.
On the down side, it's a commercial product, so you have to pay for it. But if you work with software commercially, the gained productivity (the plug in does a lot of other cool stuff) outweighs the price tag.
Yes, I'm a fan ;)
I did this and it works great
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<?php } ?>
If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.
<label class="radio control-label">Some label</label>
OR for 'radio inline'
<label class="radio-inline control-label">Some label</label>
I used (num-0.05).toFixed(1)
to get the second decimal floored.
checking with isinstance()
would not be enough if you want to know in run time.
use:
if(someObject.getClass().equals(C.class){
// do something
}
As mentioned before, you cannot create free certificates for S3 buckets. However, you can create Cloud Front distribution and then assign the certificate for the Cloud Front instead. You request the certificate for your domain and then just assign it to the Cloud Front distribution in the Cloud Front settings. I've used this method to serve static websites via SSL as well as serve static files.
For static website creation Amazon is the go to place. It is really affordable to get a static website with SSL.
Simpler more performant version, with simple caching.
var TITLE_CASE_LOWER_MAP = {_x000D_
'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
};_x000D_
_x000D_
// LEAK/CACHE TODO: evaluate using LRU._x000D_
var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
toTitleCase: function (title) {_x000D_
if (!title) return null;_x000D_
_x000D_
var result = TITLE_CASE_CACHE[title];_x000D_
if (result) {_x000D_
return result;_x000D_
}_x000D_
_x000D_
result = "";_x000D_
var split = title.toLowerCase().split(" ");_x000D_
for (var i=0; i < split.length; i++) {_x000D_
_x000D_
if (i > 0) {_x000D_
result += " ";_x000D_
}_x000D_
_x000D_
var word = split[i];_x000D_
if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
}_x000D_
_x000D_
result += word;_x000D_
}_x000D_
_x000D_
TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
return result;_x000D_
},
_x000D_
The first error
java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);
means that your encrypt
method throws an exception that is not being handled or declared by the actionPerformed
method where you are calling it. Read all about it at the Java Exceptions Tutorial.
You have a couple of choices that you can pick from to get the code to compile.
throws Exception
from your encrypt
method and actually handle the exception inside encrypt
.encrypt
and add throws Exception
and the exception handling block to your actionPerformed
method.It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.
The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt
, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt
, as I mentioned before.
//This piece of code will handle the leap year addition as well.
function updateExpiryDate(controlID, value) {
if ( $("#ICMEffectiveDate").val() != '' &&
$("#ICMTermYears").val() != '') {
var effectiveDate = $("#ICMEffectiveDate").val();
var date = new Date(effectiveDate);
var termYears = $("#ICMTermYears").val();
date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
$('#ICMExpiryDate').val(expiryDate);
}
}
ViewBag vs ViewData in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
Similarities between ViewBag & ViewData :
Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
Calling in View
@ViewBag.Name
@ViewData["Name"]
I had the same error and I started the SQL Server Express service and it worked. Hope this helps.
I was looking solution for my Ionic Cordova app push notification.
Thanks to Syed Rafay's answer.
in app.component.ts
const options: PushOptions = {
android: {
topics: ['all']
},
in Server file
"to" => "/topics/all",
If you just want to change the color, change the variable (recommended):
@input-border-focus: red;
$input-border-focus: red;
If you wan't to remove it completely, you'll have to overwrite the Mixin that sets the outline.
.form-control-focus(@color: @input-border-focus) {}
If you are using css overwrite it via:
.form-control:focus{
border-color: #cccccc;
-webkit-box-shadow: none;
box-shadow: none;
}
Use a Temp Table or a Table variable, e.g.
select 'A' as [value]
into #tmp
union
select 'B'
union
select 'C'
and then
SELECT
blah
FROM foo
WHERE myField IN (select [value] from #tmp)
or
SELECT
f.blah
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]
__main__.py
file for?When creating a Python module, it is common to make the module execute some functionality (usually contained in a main
function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:
if __name__ == '__main__':
# execute only if run as the entry point into the program
main()
You can get the same semantics for a Python package with __main__.py
, which might have the following structure:
.
+-- demo
+-- __init__.py
+-- __main__.py
To see this, paste the below into a Python 3 shell:
from pathlib import Path
demo = Path.cwd() / 'demo'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')
from demo import main
main()
""")
We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py
(but not the main
function):
>>> import demo
demo/__init__.py executed
When we use the package as the entry point to the program, we perform the code in the __main__.py
, which imports the __init__.py
first:
$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed
You can derive this from the documentation. The documentation says:
__main__
— Top-level script environment
'__main__'
is the name of the scope in which top-level code executes. A module’s__name__
is set equal to'__main__'
when read from standard input, a script, or from an interactive prompt.A module can discover whether or not it is running in the main scope by checking its own
__name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m
but not when it is imported:if __name__ == '__main__': # execute only if run as a script main()
For a package, the same effect can be achieved by including a
__main__.py
module, the contents of which will be executed when the module is run with-m
.
You can also zip up this directory, including the __main__.py
, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:
from pathlib import Path
demo = Path.cwd() / 'demo2'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')
from __init__ import main
main()
""")
Note the subtle change - we are importing main
from __init__
instead of demo2
- this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m
flag.
Particularly relevant to the question - zipapp
causes the zipped directory to execute the __main__.py
by default - and it is executed first, before __init__.py
:
$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed
Note again, this zipped directory is not a package - you cannot import it either.
as System environment Variable:
Windows:
Start -> type "envi" select environment variables and add a new:
Name: spring_profiles_active
Value: dev
(or whatever yours is)
Linux: add following line to /etc/environment under PATH:
spring_profiles_active=prod
(or whatever profile is)
then also export spring_profiles_active=prod
so you have it in the runtime now.
myfunc
is an attribute of MyClass
. That's how it's found when you run:
myinstance = MyClass()
myinstance.myfunc()
It looks for an attribute on myinstance
named myfunc
, doesn't find one, sees that myinstance
is an instance of MyClass
and looks it up there.
So the complete list of attributes for MyClass
is:
>>> dir(MyClass)
['__doc__', '__module__', 'a', 'b', 'myfunc']
(Note that I'm using dir just as a quick and easy way to list the members of the class: it should only be used in an exploratory fashion, not in production code)
If you only want particular attributes, you'll need to filter this list using some criteria, because __doc__
, __module__
, and myfunc
aren't special in any way, they're attributes in exactly the same way that a
and b
are.
I've never used the inspect module referred to by Matt and Borealid, but from a brief link it looks like it has tests to help you do this, but you'll need to write your own predicate function, since it seems what you want is roughly the attributes that don't pass the isroutine
test and don't start and end with two underscores.
Also note: by using class MyClass():
in Python 2.7 you're using the wildly out of date old-style classes. Unless you're doing so deliberately for compatibility with extremely old libraries, you should be instead defining your class as class MyClass(object):
. In Python 3 there are no "old-style" classes, and this behaviour is the default. However, using newstyle classes will get you a lot more automatically defined attributes:
>>> class MyClass(object):
a = "12"
b = "34"
def myfunc(self):
return self.a
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'myfunc']
The only way I able to get this to work was by doing this on the presenting view controller:
func didTapButton() {
self.definesPresentationContext = true
self.modalTransitionStyle = .crossDissolve
let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
let navController = UINavigationController(rootViewController: yourVC)
navController.modalPresentationStyle = .overCurrentContext
navController.modalTransitionStyle = .crossDissolve
self.present(navController, animated: true, completion: nil)
}
You can use DAYS.between
from java.time.temporal.ChronoUnit
e.g.
import java.time.temporal.ChronoUnit;
public long getDaysCountBetweenDates(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
}
@Oriol has an excellent answer, sadly as of October 2017, neither display:contents
, neither page-break-after
is widely supported, better said it's about Firefox which supports this but not the other players, I have come up with the following "hack" which I consider better than hard coding in a break after every 3rd element, because that will make it very difficult to make the page mobile friendly.
As said it's a hack and the drawback is that you need to add quite a lot of extra elements for nothing, but it does the trick and works cross browser even on the dated IE11.
The "hack" is to simply add an additional element after each div, which is set to display:none
and then used the css nth-child
to decide which one of this should be actually made visible forcing a line brake like this:
.container {
background: tomato;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
.item {
width: 100px;
background: gold;
height: 100px;
border: 1px solid black;
font-size: 30px;
line-height: 100px;
text-align: center;
margin: 10px
}
.item:nth-child(3n-1) {
background: silver;
}
.breaker {
display: none;
}
.breaker:nth-child(3n) {
display: block;
width: 100%;
height: 0;
}
_x000D_
<div class="container">
<div class="item">1</div>
<p class="breaker"></p>
<div class="item">2</div>
<p class="breaker"></p>
<div class="item">3</div>
<p class="breaker"></p>
<div class="item">4</div>
<p class="breaker"></p>
<div class="item">5</div>
<p class="breaker"></p>
<div class="item">6</div>
<p class="breaker"></p>
<div class="item">7</div>
<p class="breaker"></p>
<div class="item">8</div>
<p class="breaker"></p>
<div class="item">9</div>
<p class="breaker"></p>
<div class="item">10</div>
<p class="breaker"></p>
</div>
_x000D_
All objects are instances of at least one class – Object
– in ECMAScript. You can only differentiate between instances of built-in classes and normal objects using Object#toString
. They all have the same level of complexity, for instance, whether they are created using {}
or the new
operator.
Object.prototype.toString.call(object)
is your best bet to differentiate between normal objects and instances of other built-in classes, as object === Object(object)
doesn't work here. However, I can't see a reason why you would need to do what you're doing, so perhaps if you share the use case I can offer a little more help.
To get all rows, don't specify the key. Try this:
$meta_values = get_post_meta( get_the_ID() );
var_dump( $meta_values );
Hope it helps!
Swift 4+:
textField.clearButtonMode = UITextField.ViewMode.whileEditing
or even shorter:
textField.clearButtonMode = .whileEditing
In new Xcode 7.0 use
//: Playground - noun: a place where people can play
import UIKit
var name = "How do you use String.substringWithRange?"
let range = name.startIndex.advancedBy(0)..<name.startIndex.advancedBy(10)
name.substringWithRange(range)
//OUT:
Generally speaking, in the presence of a garbage collector, it is never good practice to manually call the GC. A GC is organized around heuristic algorithms which work best when left to their own devices. Calling the GC manually often decreases performance.
Occasionally, in some relatively rare situations, one may find that a particular GC gets it wrong, and a manual call to the GC may then improves things, performance-wise. This is because it is not really possible to implement a "perfect" GC which will manage memory optimally in all cases. Such situations are hard to predict and depend on many subtle implementation details. The "good practice" is to let the GC run by itself; a manual call to the GC is the exception, which should be envisioned only after an actual performance issue has been duly witnessed.
I get the same error. the solution is to put your script code before the end of body, not in the head section.
You can just trace the IP address of your local machine using
ifconfig
Then just enter into your Docker container and type
scp user_name@ip_address:/path_to_the_file destination
In any case if you don't have an SSH client and server installed, just install it using:
sudo apt-get install openssh-server
Check you are calling same function or not.
<script>function greeting(){document.write("hi");}</script>
<input type="button" value="Click Here" onclick="greeting();"/>
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
Make sure it's not blocked at your settings
http://www.howtogeek.com/howto/16404/how-to-disable-the-new-geolocation-feature-in-google-chrome/
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
Another option that can work better if you have many variables is factor
and model.matrix
.
> year.f = factor(year)
> dummies = model.matrix(~year.f)
This will include an intercept column (all ones) and one column for each of the years in your data set except one, which will be the "default" or intercept value.
You can change how the "default" is chosen by messing with contrasts.arg
in model.matrix
.
Also, if you want to omit the intercept, you can just drop the first column or add +0
to the end of the formula.
Hope this is useful.
Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.
import os
cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
os.system(cmd)
I'm currently fighting with dropdowns and I'd like to share my experiences:
There are specific situations where <select>
can't be used and must be 'emulated' with dropdown.
For example if you want to create bootstrap input groups, like Buttons with dropdowns (see http://getbootstrap.com/components/#input-groups-buttons-dropdowns). Unfortunately <select>
is not supported in input groups, it will not be rendered properly.
Or does anybody solved this already? I would be very interested on the solution.
And to make it even more complicated, you can't use so simply $(this).text()
to catch what user selected in dropdown if you're using glypicons or font awesome icons as content for dropdown. For example:
<li id="someId"><a href="#0"><i class="fa fa-minus"></i></a></li>
Because in this case there is no text and if you will add some then it will be also displayed in dropdown element and this is unwanted.
I found two possible solutions:
1)
Use $(this).html()
to get content of the selected <li>
element and then to examine it, but you will get something like <a href="#0"><i class="fa fa-minus"></i></a>
so you need to play with this to extract what you need.
2)
Use $(this).text()
and hide the text in element in hidden span:
<li id="someId"><a href="#0"><i class="fa fa-minus"><span class="hidden">text</span></i></a></li>
.
For me this is simple and elegant solution, you can put any text you need, text will be hidden, and you don't need to do any transformations of $(this).html()
result like in option 1) to get what you need.
I hope it's clear and can help somebody :-)
Do you mean altering the table after it has been created? If so you need to use alter table, in particular:
ALTER TABLE tablename MODIFY COLUMN new-column-definition
e.g.
ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);
ETA 24 Apr 17
I wanted to simplify this a bit with some async
/await
magic, as it makes it a lot more succinct:
Using the same promisified-observable:
const startObservable = (domNode) => {
var targetNode = domNode;
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
return new Promise((resolve) => {
var observer = new MutationObserver(function (mutations) {
// For the sake of...observation...let's output the mutation to console to see how this all works
mutations.forEach(function (mutation) {
console.log(mutation.type);
});
resolve(mutations)
});
observer.observe(targetNode, observerConfig);
})
}
Your calling function can be as simple as:
const waitForMutation = async () => {
const button = document.querySelector('.some-button')
if (button !== null) button.click()
try {
const results = await startObservable(someDomNode)
return results
} catch (err) {
console.error(err)
}
}
If you wanted to add a timeout, you could use a simple Promise.race
pattern as demonstrated here:
const waitForMutation = async (timeout = 5000 /*in ms*/) => {
const button = document.querySelector('.some-button')
if (button !== null) button.click()
try {
const results = await Promise.race([
startObservable(someDomNode),
// this will throw after the timeout, skipping
// the return & going to the catch block
new Promise((resolve, reject) => setTimeout(
reject,
timeout,
new Error('timed out waiting for mutation')
)
])
return results
} catch (err) {
console.error(err)
}
}
Original
You can do this without libraries, but you'd have to use some ES6 stuff, so be cognizant of compatibility issues (i.e., if your audience is mostly Amish, luddite or, worse, IE8 users)
First, we'll use the MutationObserver API to construct an observer object. We'll wrap this object in a promise, and resolve()
when the callback is fired (h/t davidwalshblog)david walsh blog article on mutations:
const startObservable = (domNode) => {
var targetNode = domNode;
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
return new Promise((resolve) => {
var observer = new MutationObserver(function (mutations) {
// For the sake of...observation...let's output the mutation to console to see how this all works
mutations.forEach(function (mutation) {
console.log(mutation.type);
});
resolve(mutations)
});
observer.observe(targetNode, observerConfig);
})
}
Then, we'll create a generator function
. If you haven't used these yet, then you're missing out--but a brief synopsis is: it runs like a sync function, and when it finds a yield <Promise>
expression, it waits in a non-blocking fashion for the promise to be fulfilled (Generators do more than this, but this is what we're interested in here).
// we'll declare our DOM node here, too
let targ = document.querySelector('#domNodeToWatch')
function* getMutation() {
console.log("Starting")
var mutations = yield startObservable(targ)
console.log("done")
}
A tricky part about generators is they don't 'return' like a normal function. So, we'll use a helper function to be able to use the generator like a regular function. (again, h/t to dwb)
function runGenerator(g) {
var it = g(), ret;
// asynchronously iterate over generator
(function iterate(val){
ret = it.next( val );
if (!ret.done) {
// poor man's "is it a promise?" test
if ("then" in ret.value) {
// wait on the promise
ret.value.then( iterate );
}
// immediate value: just send right back in
else {
// avoid synchronous recursion
setTimeout( function(){
iterate( ret.value );
}, 0 );
}
}
})();
}
Then, at any point before the expected DOM mutation might happen, simply run runGenerator(getMutation)
.
Now you can integrate DOM mutations into a synchronous-style control flow. How bout that.
You can just add the padding to tour block element and add background-origin
style like so:
.block {
position: relative;
display: inline-block;
padding: 10px 12px;
border:1px solid #e5e5e5;
background-size: contain;
background-position: center;
background-repeat: no-repeat;
background-origin: content-box;
background-image: url(_your_image_);
height: 14rem;
width: 10rem;
}
You can check several https://www.w3schools.com/cssref/css3_pr_background-origin.asp
I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.
Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.
There may be reasons not to do this that I don't know about, but it worked for me.
You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
string customHeaderValue = requestProperty.Headers["Custom"];
I needed to set an additional option to allow SSO passthrough to our intranet site. I added some code to an example above.
pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
echo user_pref("network.automatic-ntlm-auth.trusted-uris","site.domain.com, sites.domain.com");>>prefs.js
popd
here is a solution when you do want to dismiss AlertDialog but do not want to keep a reference to it inside activity.
solution requires you to have androidx.lifecycle dependency in your project (i believe at the moment of the comment it's a common requirement)
this lets you to delegate dialog's dismiss to external object (observer), and you dont need to care about it anymore, because it's auto-unsubscribed when activity dies. (here is proof: https://github.com/googlecodelabs/android-lifecycles/issues/5).
so, the observer keeps the reference to dialog, and activity keeps reference to observer. when "onPause" happens - observer dismisses the dialog, and when "onDestroy" happens - activity removes observer, so no leak happens (well, at least i dont see error in logcat anymore)
// observer
class DialogDismissLifecycleObserver( private var dialog: AlertDialog? ) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
dialog?.dismiss()
dialog = null
}
}
// activity code
private fun showDialog() {
if( isDestroyed || isFinishing ) return
val dialog = AlertDialog
.Builder(this, R.style.DialogTheme)
// dialog setup skipped
.create()
lifecycle.addObserver( DialogDismissLifecycleObserver( dialog ) )
dialog.show()
}
Add these depencendy, and it should work:
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
you can use DateUtils class in org.apache.commons.lang3.time package
int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute
rsubmit;
options missing=0;
ods listing close;
ods csv file='\\FILE_PATH_and_Name_of_report.csv';
proc sql;
SELECT *
FROM `YOUR_FINAL_TABLE_NAME';
quit;
ods csv close;
endrsubmit;
I was struggling for hours on this until I figured out it can be done in one line of powershell:
invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials
I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.
Simple.
You can write a custom UICollectionView
layout to achieve this, here is demo image of my implementation:
Here's code repository: KSTCollectionViewPageHorizontalLayout
@iPhoneDev (this maybe help you too)
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
for fstr in strlist:
if line.find(fstr) != -1:
print('found')
res = True
if res:
print('res true')
else:
print('res false')
This would become a bit more clear if you add a line to both examples:
var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");
The second one:
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
console.log(result.length);
});
console.log("Hello World");
Try running these, and you’ll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line. In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.
That's because in the second example, the database.query
is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length)
is only executed when the database query has completed.
If you have HashMap<String, SomeObject> hashMap
then:
hashMap.values().toArray();
Will return an Object[]
. If instead you want an array of the type SomeObject
, you could use:
hashMap.values().toArray(new SomeObject[0]);
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
element.style
has a setProperty
method that can take the priority as a third parameter:
element.style.setProperty("display", "inline", "important")
It didn't work in old IEs but it should be fine in current browsers.
pass your js array to the function below and it will do the same as php print_r() function
alert(print_r(your array)); //call it like this
function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += print_r(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
Include required imports and you can make ur decision in handleError method Error status will give the error code
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model';
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
catchError(this.handleError)
);
}
Use this code to find the record between two dates using $gte
and $lt
:
db.CollectionName.find({"whenCreated": {
'$gte': ISODate("2018-03-06T13:10:40.294Z"),
'$lt': ISODate("2018-05-06T13:10:40.294Z")
}});
Clean solution. Restore nuget packages.
You can simply import by
mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv
Note: Csv File name and Table name should be same
Before pull you need to clean your local changes. following command help me to solve.
git remote prune origin
and then after
git pull origin develop
Hopes this helps!
I was having a similar problem with an Eclipse/PyDev project. In this project the root directory of the python code was a sub-directory of the project.
--> MyProject
+ --> src Root of python code
+ --> module1 A module
+ --> module2 Another module
+ --> docs
+ --> test
When the project was debugged or run everything was fine as the working directory was set to the correct place. However the PyDev code analysis was failing to find any imports from module1 or module2.
Solution was to edit the project properties -> PyDev - PYTHONPATH section and remove /MyProject from the source folders tab and add /MyProject/src to it instead.
For such a simple operation there shouldn't be any dependency on third-party modules. Go easy.
var fs = require('fs'),
readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('/path/to/file'),
output: process.stdout,
console: false
});
rd.on('line', function(line) {
console.log(line);
});
I know this is kind of an old question by this one works better.
if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
//Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
}
As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.
Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.
extension UIView {
func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
self.layer.cornerRadius = corner_radius
self.clipsToBounds = clipsToBounds
}
}
Call this like:
email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true)
.
In my case, I was using the 6.0.24 Tomcat version (with JDK 1.8) and resolved the problem by upgrading to the 6.0.37 version.
Also, if you install the new tomcat version in a different folder, do not forget to copy your previous version /conf folder to the new installation folder.
I had to use this after the flush to get the last insert id:
$em->persist($user);
$em->flush();
$user->getId();
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
The standard streams have a boolalpha
flag that determines what gets displayed -- when it's false, they'll display as 0
and 1
. When it's true, they'll display as false
and true
.
There's also an std::boolalpha
manipulator to set the flag, so this:
#include <iostream>
#include <iomanip>
int main() {
std::cout<<false<<"\n";
std::cout << std::boolalpha;
std::cout<<false<<"\n";
return 0;
}
...produces output like:
0
false
For what it's worth, the actual word produced when boolalpha
is set to true is localized--that is, <locale>
has a num_put
category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true
and false
as they're represented in that locale. For example,
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
std::cout.imbue(std::locale("fr"));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux
instead of false
. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false
for every language I've checked.
The names that get used are defined in a numpunct
facet though, so if you really want them to print out correctly for particular language, you can create a numpunct
facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:
#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return "\3"; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
And the result is (as you'd probably expect):
0
faux
You can use 'IF EXISTS' to check if the view exists and drop if it does.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'MyView') DROP VIEW MyView GO CREATE VIEW MyView AS .... GO
Use like this:
String myString = String(n);
You can find more examples here.
Maybe your forgot to run git fetch? it's required to fetch data from the remote repo! Try running git fetch remote/branch
I suppose it's reasonable to want this behavior in some cases, but I would argue that code not triggering a form submission should (always) be the default behavior. Suppose you want to catch a form's submission with
$("form").submit(function(e){
e.preventDefault();
});
and then do some validation on the input. If code could trigger submit handlers, you could never include
$("form").submit()
inside this handler because it would result in an infinite loop (the SAME handler would be called, prevent the submission, validate, and resubmit). You need to be able to manually submit a form inside a submit handler without triggering the same handler.
I realize this doesn't ANSWER the question directly, but there are lots of other answers on this page about how this functionality can be hacked, and I felt that this needed to be pointed out (and it's too long for a comment).
You can use string.match() and a regular expression for this too:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes
string.match()
will return an array of matching substrings if found, otherwise null.
Apache Commons Lang has a StringUtils.left
method for this.
String upToNCharacters = StringUtils.left(s, n);
Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
Here's a complete, self-contained example. First, use the following HTML:
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>
Then put some squares on the canvas with random background colors:
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);
And print each color on mouseover:
$('#example').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
$('#status').html(coord + "<br>" + hex);
});
The code above assumes the presence of jQuery and the following utility functions:
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
function randomInt(max) {
return Math.floor(Math.random() * max);
}
function randomColor() {
return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}
See it in action here:
// set up some sample squares with random colors
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);
$('#example').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
$('#status').html(coord + "<br>" + hex);
});
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
function randomInt(max) {
return Math.floor(Math.random() * max);
}
function randomColor() {
return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>
_x000D_
If you want to hide the cursor in the entire webpage, using body
will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:
document.documentElement.style.cursor = 'none';
To reenable it:
document.documentElement.style.cursor = 'auto';
The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none}
)
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
Documentation: Convert JSON to a Type
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
Guava has Files.toByteArray() to offer you. It has several advantages:
The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:
div{
margin: 2rem;
height: 100vh;
overflow: hidden;
display: inline-block;
border: 1px solid #00000000;
}
img {
-webkit-filter: blur(2rem);
filter: blur(2rem);
}
<div><img src='https://images.unsplash.com/photo-1557853197-aefb550b6fdc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=375&q=80' /></div>
Here's a codepen depicting the same: https://codepen.io/arnavozil/pen/ExPYKNZ
i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.
template.html:
<script type="text/ng-template" id=“foo”>
foo
</script>
<script type="text/ng-template" id=“bar”>
bar
</script>
directive:
myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {
var getTemplate = function(data) {
// use data to determine which template to use
var templateid = 'foo';
var template = $templateCache.get(templateid);
return template;
}
return {
templateUrl: 'views/partials/template.html',
scope: {data: '='},
restrict: 'E',
link: function(scope, element) {
var template = getTemplate(scope.data);
element.html(template);
$compile(element.contents())(scope);
}
};
}]);
Sometime only this helps:
View child = parent.findViewById(R.id.btnMoreText);
child.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View parent = (View) v.getParent();
parent.performClick();
}
});
Another variant, works not always:
child.setOnClickListener(null);
Faced to this issue after a long time since question asked here. when checking material-ui code I found it's now accessible through inputRef
property.
...
<CssTextField
inputRef={(c) => {this.myRefs.username = c}}
label="Username"
placeholder="xxxxxxx"
margin="normal"
className={classes.textField}
variant="outlined"
fullWidth
/>
...
Then Access value like this.
onSaveUser = () => {
console.log('Saving user');
console.log(this.myRefs.username.value);
}
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
From bash command line, run:
$ python -c "import nltk; nltk.download('punkt')"
Test the existence of variavle MyVariable. Returns boolean true or false.
Test-Path variable:\MyVariable
Use the set -e
builtin:
#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
Alternatively, you can pass -e
on the command line:
bash -e my_script.sh
You can also disable this behavior with set +e
.
You may also want to employ all or some of the the -e
-u
-x
and -o pipefail
options like so:
set -euxo pipefail
-e
exits on error, -u
errors on undefined variables, and -o (for option) pipefail
exits on command pipe failures. Some gotchas and workarounds are documented well here.
(*) Note:
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !
(from man bash
)
You can use clone() method to create a copy..
$('#foo1').html( $('#foo2 > div').clone())?;
Here's a nice semi cross-browser way to have gradient borders that fade out half way down. Simply by setting the color-stop to rgba(0, 0, 0, 0)
.fade-out-borders {
min-height: 200px; /* for example */
-webkit-border-image: -webkit-gradient(linear, 0 0, 0 50%, from(black), to(rgba(0, 0, 0, 0))) 1 100%;
-webkit-border-image: -webkit-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-moz-border-image: -moz-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-o-border-image: -o-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
border-image: linear-gradient(to bottom, black, rgba(0, 0, 0, 0) 50%) 1 100%;
}
<div class="fade-out-border"></div>
Usage explained:
Formal grammar: linear-gradient( [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )
\---------------------------------/ \----------------------------/
Definition of the gradient line List of color stops
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
you must check is user loggined ?
Auth::check() ? Auth::user()->id : null
Other answers are correct, basically you had the wrong number of "y" characters in your pattern.
One more problem though… You did not address time zones. If you intended UTC, then you should have said so. If not, the answers are not complete. If all you want is the date portion without the time, then no issue. But if you do further work that may involve time, then you should be specifying a time zone.
Here is the same kind of code but using the third-party open-source Joda-Time 2.3 library
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
String date_s = "2011-01-18 00:00:00.0";
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );
// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.
// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );
When run…
dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18
dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z
It is Widget.ProgressBar.Horizontal
on my phone, if I set android:indeterminate="true"
A better solution with ref to avoid findDOMNode that is discouraged.
...
onScroll() {
let offsetTop = this.instance.getBoundingClientRect().top;
}
...
render() {
...
<Component ref={(el) => this.instance = el } />
...
Just to add on to the other answers, before i knew my way around git, i was looking for some way to upload existing code to a new github (or other git) repo. Here's the brief that would save time for newbs:-
Assuming you have your NEW empty github or other git repo ready:-
cd "/your/repo/dir"
git clone https://github.com/user_AKA_you/repoName # (creates /your/repo/dir/repoName)
cp "/all/your/existing/code/*" "/your/repo/dir/repoName/"
git add -A
git commit -m "initial commit"
git push origin master
Alternatively if you have an existing local git repo
cd "/your/repo/dir/repoName"
#add your remote github or other git repo
git remote set-url origin https://github.com/user_AKA_you/your_repoName
git commit -m "new origin commit"
git push origin master
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
y = a + b * x
where:
b = ( sum(xi * yi) - n * xbar * ybar ) / sum((xi - xbar)^2)
a = ybar - b * xbar
# sample points
X = [0, 5, 10, 15, 20]
Y = [0, 7, 10, 13, 20]
# solve for a and b
def best_fit(X, Y):
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
b = numer / denum
a = ybar - b * xbar
print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))
return a, b
# solution
a, b = best_fit(X, Y)
#best fit line:
#y = 0.80 + 0.92x
# plot points and fit line
import matplotlib.pyplot as plt
plt.scatter(X, Y)
yfit = [a + b * xi for xi in X]
plt.plot(X, yfit)
Instead, just do a hook_form_alter
and make the button an image button and you are done!
You can use ->child
to get a child element named child.
This element will contain the text of the child element.
But if you try var_dump()
on that variable, you will see it is not actually a PHP string.
The easiest way around this is to perform a strval(xml->child);
That will convert it to an actual PHP string.
This is useful when debugging when looping your XML and using var_dump()
to check the result.
So $s = strval($xml->child);
.
Use the DO statement, a new option in version 9.0:
DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
(
EventId BIGSERIAL NOT NULL PRIMARY KEY,
PrimaryKeyId bigint NOT NULL,
EventDateTime date NOT NULL DEFAULT(now()),
Action varchar(12) NOT NULL,
UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
);
CREATE TABLE "Logs"."EventDetails"
(
EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
Resource varchar(64) NOT NULL,
OldVal varchar(4000) NOT NULL,
NewVal varchar(4000) NOT NULL
);
RAISE NOTICE 'Task completed sucessfully.';
END;
$$;
Certian kinds of math I think are indispensible. For instance, every software engineer should know and understand De Morgan's laws, and O notation.
Other kinds are just very useful. In simulation we often have to do a lot of physics modeling. If you are doing graphics work, you will often find yourself needing to write coordinate transformation algorithms. I've had many other situations in my 20 year career where I needed to write up and solve simultanious linear equations to figure out what constants to put into an algorithm.
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
return;
is used in a method of void return type to return the control of execution to its parent method.<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|left"
android:orientation="vertical">
Your views go here...
</LinearLayout>
</ScrollView>
The required
property is boolean
:
$('form#register').find('input').each(function(){
if(!$(this).prop('required')){
console.log("NR");
} else {
console.log("IR");
}
});
Reference: HTMLInputElement
Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!
You could define a macro containing the following code:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.ClearContents
end sub
Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.
To leave your formulas intact use the following instead:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.SpecialCells(xlCellTypeConstants, 23).Select
Selection.ClearContents
end sub
This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'
You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.
You can do the following:
=Datevalue(text)+timevalue(text)
.
Go into different types of date formats and choose:
dd-mm-yyyy mm:ss am/pm
.
There are more (many) ways to Rome:
//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null
cheers!
check for scipy.stats module:
scipy.stats.scoreatpercentile
Use ftplib
, you can write it like this:
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb') # file to send
session.storbinary('STOR kitten.jpg', file) # send the file
file.close() # close file and FTP
session.quit()
Use ftplib.FTP_TLS
instead if you FTP host requires TLS.
To retrieve it, you can use urllib.retrieve
:
import urllib
urllib.urlretrieve('ftp://server/path/to/file', 'file')
EDIT:
To find out the current directory, use FTP.pwd()
:
FTP.pwd(): Return the pathname of the current directory on the server.
To change the directory, use FTP.cwd(pathname)
:
FTP.cwd(pathname): Set the current directory on the server.
I would use the simple code snippet from CSS-Tricks.com:
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/
Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.
I know that this is a quite old thread, but here is an updated version for Integers and Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
Note that it is "o1 - o2" for the normal ascending order (or Comparator.comparingInt()).
This also works for any other kinds of Objects. Say:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
For me the issue was the following.
Make sure performSegueWithIdentifier:
is performed on the main thread:
dispatch_async (dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:@"ViewController" sender:nil];
});
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
Credit to @mehras for the code. I just created a snippet to demonstrate it because I thought that would be appreciated and I wanted an excuse to try that feature.
$(document).ready(function() {_x000D_
$('#container').addClass('hidden');_x000D_
$('#header').click(function() {_x000D_
if ($('#container').hasClass('hidden')) {_x000D_
$('#container').removeClass('hidden');_x000D_
} else {_x000D_
$('#container').addClass('hidden');_x000D_
}_x000D_
});_x000D_
$('#header input[type=checkbox]').click(function(event) {_x000D_
if (event.stopPropagation) { // standard_x000D_
event.stopPropagation();_x000D_
} else { // IE6-8_x000D_
event.cancelBubble = true;_x000D_
}_x000D_
});_x000D_
});
_x000D_
div {_x000D_
text-align: center;_x000D_
padding: 2em;_x000D_
font-size: 1.2em_x000D_
}_x000D_
_x000D_
.hidden {_x000D_
display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="header"><input type="checkbox" />Checkbox won't bubble the event, but this text will.</div>_x000D_
<div id="container">click() bubbled up!</div>
_x000D_
It's about margins and border. If you use width: auto
, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100%
and some border, the element's width will be 100% + border or margin. For more info see this.
shift+F6
you will get a popup window as shown below select
Rename package.That's it done.
declare @T table (ScripName varchar(50), ScripCode varchar(50), Price int)
insert into @T values ('20 MICRONS', '533022', 39)
select
'ScripName' as ColName,
ScripName as ColValue
from @T
union all
select
'ScripCode' as ColName,
ScripCode as ColValue
from @T
union all
select
'Price' as ColName,
cast(Price as varchar(50)) as ColValue
from @T
You might need to install the "Microsoft Web Platform Installer" from http://www.microsoft.com/web/downloads/platform.aspx
1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
The corrected code is
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
running the code above produces
{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}
You have copy this sample code from Here,right?
now, as you can see there property
file they have define, have you done same thing?
if not then add below code in your project with property file for log4j
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
make changes as per your requirement like log
path
Try this explanation on...
TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).
For non-typesafe behavior, consider this:
object x = 89;
int y;
if you attempt to do this:
y = x;
the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:
y = Convert.ToInt32( x );
The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other.
Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out.
For example:
Session[ "x" ] = 34;
works fine. But to assign the integer value back, you'll need to:
int i = Convert.ToInt32( Session[ "x" ] );
Read about generics for ways that facility helps you easily implement typesafe collections.
C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).
When a subscriber unsubscribes you are changing contents of the collection of Subscribers during enumeration.
There are several ways to fix this, one being changing the for loop to use an explicit .ToList()
:
public void NotifySubscribers(DataRecord sr)
{
foreach(Subscriber s in subscribers.Values.ToList())
{
^^^^^^^^^
...
This is fixable in the application code by setting the button's TransformationMethod, e.g.
mButton.setTransformationMethod(null);
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
if its to reverse each letter than this for loop works nicely:
for(int i = 0; i < input.length(); i++){
output = output + input.substring((input.length()-i)-1, input.length()-i);
}
Just found this, it works for me and I personally find it easier to read.
This will set the actual index just like gnarf's answer number 3 option.
// sets selected index of a select box the actual index of 0
$("select#elem").attr('selectedIndex', 0);
This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474
As recommended in the comments use :
$("select#elem").prop('selectedIndex', 0);
None of these points to without_callbacks
plugin that just does what you need ...
class MyModel < ActiveRecord::Base
before_save :do_something_before_save
def after_save
raise RuntimeError, "after_save called"
end
def do_something_before_save
raise RuntimeError, "do_something_before_save called"
end
end
o = MyModel.new
MyModel.without_callbacks(:before_save, :after_save) do
o.save # no exceptions raised
end
http://github.com/cjbottaro/without_callbacks works with Rails 2.x
For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.
import ctypes
OpenClipboard = ctypes.windll.user32.OpenClipboard
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
GetClipboardData = ctypes.windll.user32.GetClipboardData
SetClipboardData = ctypes.windll.user32.SetClipboardData
CloseClipboard = ctypes.windll.user32.CloseClipboard
CF_UNICODETEXT = 13
GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalSize = ctypes.windll.kernel32.GlobalSize
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040
unicode_type = type(u'')
def get():
text = None
OpenClipboard(None)
handle = GetClipboardData(CF_UNICODETEXT)
pcontents = GlobalLock(handle)
size = GlobalSize(handle)
if pcontents and size:
raw_data = ctypes.create_string_buffer(size)
ctypes.memmove(raw_data, pcontents, size)
text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
GlobalUnlock(handle)
CloseClipboard()
return text
def put(s):
if not isinstance(s, unicode_type):
s = s.decode('mbcs')
data = s.encode('utf-16le')
OpenClipboard(None)
EmptyClipboard()
handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
pcontents = GlobalLock(handle)
ctypes.memmove(pcontents, data, len(data))
GlobalUnlock(handle)
SetClipboardData(CF_UNICODETEXT, handle)
CloseClipboard()
paste = get
copy = put
The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 ()
.
Here's one way:
create table #work
(
something decimal(8,3) not null
)
insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )
select convert(varchar,convert(decimal(8,2),something))
from #work
if you want it right-aligned, something like this should do you:
select str(something,8,2) from #work
Go to magento/var/report
and open the file with the Error log record number name i.e 673618173351
in your case. In that file you can find the complete description of the error.
For log files like system.log
and exception.log
, go to magento/var/log/
.
I tried the codes from bootstrap's document as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>tab demo</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="span9">
<div class="tabbable"> <!-- Only required for left/right tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
<li><a href="#tab2" data-toggle="tab">Section 2</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<p>I'm in Section 1.</p>
</div>
<div class="tab-pane" id="tab2">
<p>Howdy, I'm in Section 2.</p>
</div>
</div>
</div>
</div>
<script src="jquery.min.js"></script>
<script src="bootstrap.js"></script>
</body>
</html>
and it works.
But when I switch these two <script src...>
's postion, it do not work. So please remember to load your jquery script before bootstrap.js.
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
As stated before I even saw this question placeholder
is the answer. HTML5 for the win! But for those poor unfortunate souls that cannot rely on that functionality take a look at the jquery plugin as an augmentation as well. HTML5 Placeholder jQuery Plugin
<input name="Name" placeholder="Enter Your Name">
I don't know if this was pointed out here. The settings for .container
width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container
size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:
Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop
to (1130px + @grid-gutter-width)
and @container-large-desktop
to (1530px + @grid-gutter-width)
. Now, the .container
changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
s1 = s1.replace(char, repl)
return s1
# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}
Just my 2 cents. The following command fails if called from batch file (Windows 7) placed on pendrive:
xcopy /s /e /i %cd%Ala C:\KS\Ala
But this does the job:
xcopy /s /e /i %~dp0Ala C:\KS\Ala
You can do that like this:
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
This will execute a function (eg. hello_world) in the next day at 1a.m.
EDIT:
As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:
from datetime import datetime, timedelta
from threading import Timer
x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x
secs=delta_t.total_seconds()
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.
We have two ways to define version.
First way:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Second way:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
For completeness’ sake, the following also works:
df %>% group_by(x) %>% filter (! duplicated(y))
However, I prefer the solution using distinct
, and I suspect it’s faster, too.
Another approach using Array.prototype.map() and Array.prototype.filter():
var indices = array.map((e, i) => e === value ? i : '').filter(String)
Kotlin Version
via Extension Function
To find a resource id by its name In Kotlin, add below snippet in a kotlin file:
ExtensionFunctions.kt
import android.content.Context
import android.content.res.Resources
fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
Usage
Now all resource ids are accessible wherever you have a context reference using resIdByName
method:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.
What you put inside the </dependencies>
tag of the root pom will be included by all child modules of the root pom. If all your modules use that dependency, this is the way to go.
However, if only 3 out of 10 of your child modules use some dependency, you do not want this dependency to be included in all your child modules. In that case, you can just put the dependency inside the </dependencyManagement>
. This will make sure that any child module that needs the dependency must declare it in their own pom file, but they will use the same version of that dependency as specified in your </dependencyManagement>
tag.
You can also use the </dependencyManagement>
to modify the version used in transitive dependencies, because the version declared in the upper most pom file is the one that will be used. This can be useful if your project A includes an external project B v1.0 that includes another external project C v1.0. Sometimes it happens that a security breach is found in project C v1.0 which is corrected in v1.1, but the developers of B are slow to update their project to use v1.1 of C. In that case, you can simply declare a dependency on C v1.1 in your project's root pom inside `, and everything will be good (assuming that B v1.0 will still be able to compile with C v1.1).
I found this here.
You can add "--errors-only" flag for Pylint to disable warnings.
To do this, go to settings. Edit the following line:
"python.linting.pylintArgs": []
As
"python.linting.pylintArgs": ["--errors-only"]
And you are good to go!
I know this is old but still: Count filtered lines
My file looks like:
Number of files sent
Company 1 file: foo.pdf OK
Company 1 file: foo.csv OK
Company 1 file: foo.msg OK
Company 2 file: foo.pdf OK
Company 2 file: foo.csv OK
Company 2 file: foo.msg Error
Company 3 file: foo.pdf OK
Company 3 file: foo.csv OK
Company 3 file: foo.msg Error
Company 4 file: foo.pdf OK
Company 4 file: foo.csv OK
Company 4 file: foo.msg Error
If I want to know how many files are sent OK:
grep "OK" <filename> | wc -l
OR
grep -c "OK" filename
Here you go! Ready for Xcode 8 and Swift 3.
import UIKit
let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"
mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true
Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg)
this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!
url("#{$assetPath}/site/background.jpg")
Just write data-interval
in the div
containing the carousel:
<div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="500">
Example taken from w3schools.
You can use tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
I am just student working on my master's thesis, but this is the way I solved it and it worked well for me. First you select your file from directory (only in csv format) and then you put the data into the lists.
List<float> t = new List<float>();
List<float> SensorI = new List<float>();
List<float> SensorII = new List<float>();
List<float> SensorIII = new List<float>();
using (OpenFileDialog dialog = new OpenFileDialog())
{
try
{
dialog.Filter = "csv files (*.csv)|*.csv";
dialog.Multiselect = false;
dialog.InitialDirectory = ".";
dialog.Title = "Select file (only in csv format)";
if (dialog.ShowDialog() == DialogResult.OK)
{
var fs = File.ReadAllLines(dialog.FileName).Select(a => a.Split(';'));
int counter = 0;
foreach (var line in fs)
{
counter++;
if (counter > 2) // Skip first two headder lines
{
this.t.Add(float.Parse(line[0]));
this.SensorI.Add(float.Parse(line[1]));
this.SensorII.Add(float.Parse(line[2]));
this.SensorIII.Add(float.Parse(line[3]));
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(
"Error while opening the file.\n" + exc.Message,
this.Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
}
The problem is with the way you are printing the Time data
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
System.out.println(sa); //this will print the milliseconds as the toString() has been written in that format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(timestamp)); //this will print without ms
Quick Easy Process in Visual Studio
Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..
/// <reference path="../../components/someclass.ts"/>
Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:
public class Album
{
// Note that we make the setter 'private'
public string Name { get; private set; }
public string Artist { get; private set; }
public int Year { get; private set; }
public Album(string name, string artist, int year)
{
this.Name = name;
this.Artist = artist;
this.Year = year;
}
}
If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:
new {
Name = "Some Name",
Artist = "Some Artist",
Year = 1994
};
the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const
(C++) or final
(Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.
That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:
public void Configure(ConfigurationSetup setup);
and I have a class that has a number of members such as:
class ConfigurationSetup {
public String Name { get; set; }
public String Location { get; set; }
public Int32 Size { get; set; }
public DateTime Time { get; set; }
// ... and some other configuration stuff...
}
Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name
and Location
, I can just do:
ConfigurationSetup setup = new ConfigurationSetup {
Name = "Some Name",
Location = "San Jose"
};
and this allows me to set up some combination without having to define a new constructor for every possibly permutation.
On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.
There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:
var jsonify = (function(div){
return function(json){
div.setAttribute('onclick', 'this.__json__ = ' + json);
div.click();
return div.__json__;
}
})(document.createElement('div'));
// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)
Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)
There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:
https://github.com/ctran/annotate_models
to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.
Your code as given (after the edit) compiles fine, so something else is wrong that isn't in what you posted.
Some things to check, is everything public? That includes both the class and the method.
Overload with different parameters?
Are you sure that Base
is the class you think it is? I.e. is there another class by the same name that it's actually referencing?
Edit:
To answer the question in your comment, you can't override a method with different parameters, nor is there a need to. You can create a new method (with the new parameter) without the override
keyword and it will work just fine.
If your intention is to prohibit calling of the base method without the parameter you can mark the method as protected
instead of public
. That way it can only be called from classes that inherit from Base
A quick and easy way to perform the migration is to use the schematic NPM package schematics-scss-migrate. this package rename all css to scss file :
ng add schematics-scss-migrate
It is possibly because the value of val
is actually the string "null"
rather than the value null
.
For those who want to have the accepted answer run in Ansible without further searches, I post the task here for convenience and future reference.
Accepted answer recommendation: https://stackoverflow.com/a/35165401/78935
Ansible task equivalent
tasks:
- name: Setting up the NodeJS yum repository
shell: curl --silent --location https://rpm.nodesource.com/setup_10.x | bash -
args:
warn: no
# ...
The problem is that the timer
variable is local, and its value is lost after each function call.
You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:
var endAndStartTimer = (function () {
var timer; // variable persisted here
return function () {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
};
})();
Insted of
drawer.setDrawerListener(toggle);
You can use
drawer.addDrawerListener(toggle);
Based on Merrill's answer here is how to do with a CursorAdapter
CursorAdapter myAdapter = (CursorAdapter) spinner_listino.getAdapter(); //cast
for(int i = 0; i < myAdapter.getCount(); i++)
{
if (myAdapter.getItemId(i) == ordine.getListino() )
{
this.spinner_listino.setSelection(i);
break;
}
}
Try:
SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date',
convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date',
FROM
(......)SA
WHERE......
Or:
SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date',
format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date',
FROM
(......)SA
WHERE......
A Simply Swift,
Step 1: Create One SubClass of UITableViewCell
Step 2: Add this method to SubClass of UITableViewCell
override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.frame = CGRectMake(0, 0, 10, 10)
}
Step 3: Create cell object using that SubClass in cellForRowAtIndexPath
,
Ex: let customCell:CustomCell = CustomCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
Step 4: Enjoy
I'm using the following
type Props = { children: React.ReactNode };
const MyComponent: React.FC<Props> = ({children}) => {
return (
<div>
{ children }
</div>
);
export default MyComponent;
Concurrent Package:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//=========== Task1 class prints odd =====
class TaskClass1 implements Runnable
{
private Condition condition;
private Lock lock;
boolean exit = false;
int i;
TaskClass1(Condition condition,Lock lock)
{
this.condition = condition;
this.lock = lock;
}
@Override
public void run() {
try
{
lock.lock();
for(i = 1;i<11;i++)
{
if(i%2 == 0)
{
condition.signal();
condition.await();
}
if(i%2 != 0)
{
System.out.println(Thread.currentThread().getName()+" == "+i);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
lock.unlock();
}
}
}
//==== Task2 : prints even =======
class TaskClass2 implements Runnable
{
private Condition condition;
private Lock lock;
boolean exit = false;
TaskClass2(Condition condition,Lock lock)
{
this.condition = condition;
this.lock = lock;
}
@Override
public void run() {
int i;
// TODO Auto-generated method stub
try
{
lock.lock();
for(i = 2;i<11;i++)
{
if(i%2 != 0)
{
condition.signal();
condition.await();
}
if(i%2 == 0)
{
System.out.println(Thread.currentThread().getName()+" == "+i);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
lock.unlock();
}
}
}
public class OddEven {
public static void main(String[] a)
{
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Future future1;
Future future2;
ExecutorService executorService = Executors.newFixedThreadPool(2);
future1 = executorService.submit(new TaskClass1(condition,lock));
future2 = executorService.submit(new TaskClass2(condition,lock));
executorService.shutdown();
}
}