fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
Better you can use the Webclient class to simplify your task:
using System.Net;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("http://somesite.com/default.html");
}
Here is what I find works
form name
Use a default select option
, for example...
<option value="-1" selected>Please Select</option>
So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.
This input
<input type="submit">
should be
<input name="Submit" type="submit" value="Submit">
whenever I use a form that fails, it is a failure due to the difference in calling the button name submit
and name as Submit
.
You should also set your enctype attribute for your form as forms fail on my web host if it's not set.
This tutorial is very useful. To give a quick summary:
Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors
In your WebApiConfig.cs
file, add config.EnableCors()
to the Register()
method.
Add an attribute to the controllers you need to handle cors:
[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]
The documentation for writelines()
states:
writelines()
does not add line separators
So you'll need to add them yourself. For example:
line_list.append(new_line + "\n")
whenever you append a new item to line_list
.
If you want to use an active connection you can also use http://httpbin.org/delay/#, where # is the time you want their server to wait before sending a response. As long as your timeout is shorter than the delay ... should simulate the effect. I've successfully used it with the python requests package.
You may want to modify your request if you're sending anything sensitive - no idea what happens to the data sent to them.
(1) No (unfortunately). Edit: The other answers are right, per-user configuration is usually stored in dot-files or dot-directories in the users home directory. Anything above user level often is a lot of guesswork.
(2) System-wide ini file -> user ini file -> environment -> command line options (going from lowest to highest precedence)
is null is the syntax I use for such things, when COALESCE is of no help.
Try:
if (@zipCode is null)
begin
([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)
end
else
begin
([Portal].[dbo].[Address].PostalCode=@zipCode )
end
You need to escape the backslash \
:
println yourString.replace("\\", "/")
Some ideas:
Maybe you could simply not inherit from the parent in that case (and declare a dependency on base
with the exclusion). Not handy if you have lot of stuff in the parent pom.
Another thing to test would be to declare the mail
artifact with the version required by ALL-DEPS
under the dependencyManagement
in the parent pom to force the convergence (although I'm not sure this will solve the scoping problem).
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>???</version><!-- put the "right" version here -->
</dependency>
</dependencies>
</dependencyManagement>
mail
dependency from log4j if you're not using the features relying on it (and this is what I would do):<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
Remove the z-index value.
I would also recommend this approach.
HTML:
<header class="main-header" role="banner">
<img src="mybannerimage.gif" alt="Banner Image"/>
</header>
CSS:
.main-header {
text-align: center;
}
This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.
The easiest way to determine the week number ISO 8601 style using c# and the DateTime class.
Ask this: the how-many-eth thursday of the year is the thursday of this week. The answer equals the wanted week number.
var dayOfWeek = (int)moment.DayOfWeek;
// Make monday the first day of the week
if (--dayOfWeek < 0)
dayOfWeek = 6;
// The whole nr of weeks before this thursday plus one is the week number
var weekNumber = (moment.AddDays(3 - dayOfWeek).DayOfYear - 1) / 7 + 1;
Your code is correct. I tested:
r = requests.get("http://www.google.com")
print(r.content)
And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!
To display dataframes contained in a list:
display(*dfs)
If the GRANT ALL
doesn't work, try:
mysqld
and restart it with the --skip-grant-tables
option. mysqld
server with just: mysql
(i.e. no -p
option, and username may not be required).Issue the following commands in the mysql client:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
After that, you should be able to run GRANT ALL ON *.* TO 'root'@'localhost';
and have it work.
Clean solution while staying with the nio API:
Files.isDirectory(path)
Files.isRegularFile(path)
When you use a decorator, you're replacing one function with another. In other words, if you have a decorator
def logged(func):
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
then when you say
@logged
def f(x):
"""does some math"""
return x + x * x
it's exactly the same as saying
def f(x):
"""does some math"""
return x + x * x
f = logged(f)
and your function f
is replaced with the function with_logging
. Unfortunately, this means that if you then say
print(f.__name__)
it will print with_logging
because that's the name of your new function. In fact, if you look at the docstring for f
, it will be blank because with_logging
has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x
; instead it'll be listed as taking *args
and **kwargs
because that's what with_logging takes.
If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps
. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps
is itself a decorator, the following code does the correct thing:
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print(f.__name__) # prints 'f'
print(f.__doc__) # prints 'does some math'
It seems i came late to the party, but you should better check this out too.
So in system.web
for caching up exceptions within the application such as return HttpNotFound()
<system.web>
<customErrors mode="RemoteOnly">
<error statusCode="404" redirect="/page-not-found" />
<error statusCode="500" redirect="/internal-server-error" />
</customErrors>
</system.web>
and in system.webServer
for catching up errors that were caught by IIS and did not made their way to the asp.net framework
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404"/>
<error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
<remove statusCode="500"/>
<error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
</system.webServer>
In the last one if you worry about the client response then change the responseMode="Redirect"
to responseMode="File"
and serve a static html file, since this one will display a friendly page with an 200 response code.
Here is unicode-safe ucwords() function, which additionally respects double-lastnames like Russian ????-?????? and some noble names like Honoré de Balzac, d'Artagnan, Vincent van Gogh, Otto von Bismarck, Sulayman ibn Dawud, etc:
String.prototype.ucwords = function() {
return this.toLowerCase()
.replace(/(^|\s|\-)[^\s$]/g, function(m) {
return m.toUpperCase();
})
// French, Arabic and some noble names...
.replace(/\s(Of|De|Van|Von|Ibn|??|???|???|???)\s/g, function(m) { // Honoré de Balzac, Vincent van Gogh, Otto von Bismarck, Sulayman ibn Dawud etc.
return m.toLowerCase();
})
.replace(/(^|\s)(D|?)(['’][^\s$])/g, function(m, p1, p2, p3) { // D'Artagnan or d'Artagnan / ?’???????? ??? ?’????????
return p1 + (p1 === "" ? p2/*.toUpperCase()*/ : p2.toLowerCase()) + p3.toUpperCase();
});
}
I have monitored sppsvc.exe using process monitor and found out that it was trying to write to the HKEY_LOCAL_MACHINE\SYSTEM\WPA key. After giving permissions to NETWORK SERVICE on this key, I was able to start the service and Windows suddenly recognized that it was activated again.
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
Yes, you can even change it by triggering an event
<input type='text' name='pass' onclick="(this.type='password')" />
<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">
#!/bin/bash
cd /opt/
sudo mkdir java
sudo tar -zxvf ~/Downloads/jdk-8u192-linux-x64.tar.gz
sudo ln -s jdk1.8.0_192 current
for file in /opt/java/current/bin/*
do
if [ -x $file ]
then
filename=`basename $file`
sudo update-alternatives --install /usr/bin/$filename $filename $file 20000
sudo update-alternatives --set $filename $file
#echo $file $filename
fi
done
If you are a windows user and try to start py-script in cmd - don't forget to type python before filename.
python script.py
I have "No module named google" error if forget to type it.
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
Here's a utility class I use to convert the newer java.time
classes to java.util.Date
objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
Edited based on @Oliv comment.
Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:
ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);
Detailed discussion here.
The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.
Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.
This is without jQuery
<a href="123.com" id="elementid">link</a>
window.onload = function () {
var el = document.getElementById('elementid');
el.onclick = function (e) {
var ev = e || window.event;
// here u can use this or el as the HTML node
}
}
You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:
// this is the window.onload startup of your JS as in my previous example. The difference is
// that you can add multiple onload functions
$(function () {
$('a#elementid').bind('click', function (e) {
// "this" points to the <a> element
// "e" points to the event object
});
});
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
Cygwin's setup accepts command-line arguments to install packages from the command-line.
e.g. setup-x86.exe -q -P packagename1,packagename2
to install packages without any GUI interaction ('unattended setup mode').
(Note that you need to use setup-x86.exe
or setup-x86_64.exe
as appropriate.)
See http://cygwin.com/packages/ for the package list.
The best way to do this is to use getLocaleString, like this:
Create a date object:
date = new Date(0)
If you are in Berlin, this should convert to this string:
Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
Get the hours in Athens:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Europe/Athens' })
'02'
Get the hours in Shanghai:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Asia/Shanghai' })
'08'
Just wanted to show that there is no performance difference between the 2 main ways of doing it:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))
def loc():
df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
def replace():
df2['A'].replace(
to_replace=2,
value=5,
inplace=True
)
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
public class StringFormat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++){
String s1=sc.next();
int x=sc.nextInt();
System.out.println(String.format("%-15s%03d",s1,x));
}
System.out.println("================================");
}
}
outpot "================================"
ved15space123 ved15space123 ved15space123 "================================
Java solution
The "-" is used to left indent
The "15" makes the String's minimum length it takes up be 15
For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec
package that can also be used for encoding and decoding of Base64.
Ex.
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
<input type="text" autocomplete="off"/>
Should work. Alternatively, use:
<form autocomplete="off" … >
for the entire form (see this related question).
while running:
for elem,next_elem in zip(li, li[1:]+[li[0]]):
...
Your question is a little confusing, but assuming you want to display the number of options in a panel:
<div id="preview"></div>
and
$(function() {
$("#preview").text($("#input1 option").length + " items");
});
Not sure I understand the rest of your question.
try this. There are in general three ways to use mysqldump—
in order to dump a set of one or more tables,
shell> mysqldump [options] db_name [tbl_name ...]
a set of one or more complete databases
shell> mysqldump [options] --databases db_name ...
or an entire MySQL server—as shown here:
shell> mysqldump [options] --all-databases
I realize this is a very old question, but hopefully this will help someone else out as I came upon this post looking for the same thing. I had a similar issue, just that my metadata was a Guid and int. The solution is the same though. You can just make the needed metadata part of the URL.
POST accepting method in your "Controller" class:
public Task<HttpResponseMessage> PostFile(string name, float latitude, float longitude)
{
//See http://stackoverflow.com/a/10327789/431906 for how to accept a file
return null;
}
Then in whatever you're registering routes, WebApiConfig.Register(HttpConfiguration config) for me in this case.
config.Routes.MapHttpRoute(
name: "FooController",
routeTemplate: "api/{controller}/{name}/{latitude}/{longitude}",
defaults: new { }
);
if num in range(min, max):
"""do stuff..."""
else:
"""do other stuff..."""
The easiest way to do it is to make the display an inline block
<div id='page' style='width: 600px'>
<h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>
if you do this it should work
This Solution utilizes part of what @Newred and @Radu Di?a said. But will work in less standard cases.
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');
The issue both of them have is that neither check for a space between background-color: and the color.
All of these will match with the above code.
background-color: #ffffff
background-color: #fffff;
background-color:#fffff;
This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all
in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.
There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.
UPDATE: 2016-11-11As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.
UPDATES: 2016-05-16PATH
and Registry. After extraction, create a symlink to conda
in your bin
or install conda from PyPI. Then create another symlink called conda-activate
to activate
in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root
to enable Anaconda/Miniconda.conda update --all
to keep each conda environment updated,$ ln /c/Python33/python.exe python3
).If OP has 2.7.x and wants to install newer version of 2.7.x, then
It is recommended to uninstall any other Python distribution before installing Python(x,y)
Program Files\Enthought
or home\AppData\Local\Enthought\Canopy\App
for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.
sage -upgrade
command.Anaconda can be updated by using the conda
command:
conda update --all
Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.
Anaconda will likely disrupt any other Python installations. Installation uses MSI installer.
[UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe
installers and provide options to disable Windows PATH
and Registry alterations.
Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe
installer is used and the options to alter Windows PATH
and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore
keys.
Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\
with the following keys: Help
, InstallPath
, Modules
and PythonPath
- official Python registers these keys too, but under Python\PythonCore
. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore
, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.
App\lib\site-packages
and App\Scripts
could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list
to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip
to install pip if it wasn't installed.If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py
files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is
If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.
I hope this clears up any confusion.
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - resolves to 'true' when navigation succeeds,
* - resolves to 'false' when navigation fails,
* - is rejected when an error happens.
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'user', 11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
* URL.
*/
The Router Guide has more details on programmatic navigation.
You should write textcolor in xml as
android:textColor="@color/text_color"
or
android:textColor="#FFFFFF"
SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
and owner = 'Schema_name' order by object_name
here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be
SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
and owner = 'PMIS' order by object_name
Ref: https://www.plsql.co/list-all-procedures-from-a-schema-of-oracle-database.html
If you're looking for a JS version (using a combination of feature detection and UA sniffing) of what html5 boilerplate used to do:
var IE = (!! window.ActiveXObject && +(/msie\s(\d+)/i.exec(navigator.userAgent)[1])) || NaN;
if (IE < 9) {
document.documentElement.className += ' lt-ie9' + ' ie' + IE;
}
Since ant 1.9.1 you can use a if:set condition : https://ant.apache.org/manual/ifunless.html
My take borrowing from other answers. Attempt to simplify and minimize queries.
import platform, os
def ping(host):
result = os.popen(' '.join(("ping", ping.param, host))).read()
return 'TTL=' in result
ping.param = "-n 1" if platform.system().lower() == "windows" else "-c 1"
Using Spark 2.0+, we can load multiple CSV files from different directories using
df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True)
. For more information, refer the documentation
here
SELECT table1.id
FROM table1
LEFT JOIN table2 ON table1.id = table2.user_one
WHERE table2.user_one is NULL
Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.
<span id="timer"></span>
<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);
var counter = setInterval(timer, 1000);
function timer() {
now = new Date();
count = Math.round((timeup - now)/1000);
if (now > timeup) {
window.location = "/logout"; //or somethin'
clearInterval(counter);
return;
}
var seconds = Math.floor((count%60));
var minutes = Math.floor((count/60) % 60);
document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>
We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:
var querystring = Arg.url({name: "Mat", state: "CO"});
And reading works:
var name = Arg("name");
or getting the whole lot:
var params = Arg.all();
and if you care about the difference between ?query=true
and #hash=true
then you can use the Arg.query()
and Arg.hash()
methods.
just use scrollTo plugin
$("document").ready(function(){
$(window).scrollTo("#div")
})
One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.
Simple service example:
angular.module('myApp', [])
.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
Using the service in a controller:
function Ctrl2($scope, sharedProperties) {
$scope.prop2 = "Second";
$scope.both = sharedProperties.getProperty() + $scope.prop2;
}
This is described very nicely in this blog (Lesson 2 and on in particular).
I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.
Example: var property = { Property1: 'First' };
instead of var property = 'First';
.
UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:
In HTML it seems attributes are specific to the DOM tree while properties are used to describe the characteristics of DOM elements
When I uninstalled Java 8 it worked fine.
If you want HTML, with images and a list, this isn't support by UILabel. However, I've found YYText does the trick.
Try this:
Write mongodb
instead of mongod
sudo service mongodb status
If your compiler supports it, you could use a range based for to access the vector elements:
vector<float> vertices{ 1.0, 2.0, 3.0 };
for(float vertex: vertices){
std::cout << vertex << " ";
}
Prints: 1 2 3 . Note, you can't use this technique for changing the elements of the vector.
This post is for Shef(the one who posted the correct answer). It's the only way I can think of showing him how much I appreciate his code and what I have done with it.
<!DOCTYPE html>
<head><title>Displays Folder Contents</title></head>
<?php
function frmtFolder($Entity){
echo '<li style="font-weight:bold;color:black;list-style-type:none">' . $Entity;
}
function frmtFile($dEntry, $fEntry){
echo '<li style="list-style-type:square">' . '<a href="' . $dEntry . '/' . $fEntry .
'"> ' . $fEntry . ' </a>';
}
function listFolderFiles($dir) {
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
unset($ffs[array_search('index.html', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1) {return;}
echo '<ul>';
foreach ($ffs as $ff) {
if (is_dir($dir . '/' . $ff)) {
frmtFolder($dir);
} else {
frmtFile($dir, $ff);
}
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff);
}
echo '</li>';
}
echo '</ul>';
}
listFolderFiles('Folder_To_List_Here');
I plan on expanding the frmtFile to use audio and videos tags in the future.
This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem
package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:
\newenvironment{myitemize}
{ \begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt} }
{ \end{itemize} }
Which should be used like this:
\begin{myitemize}
\item one
\item two
\item three
\end{myitemize}
What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.
The above code fixed problem for most of the ppl but I still could not login. Finally I found this (line#9 in the above code needs to be changed)
$cfg['Servers'][$i]['AllowNoPassword'] = true; <--- change this
$cfg['Servers'][$i]['AllowNoPassword'] = false; <--- to this fixed the problem.
Note: there are other areas in localhost where you have to change the password manually. For example in "CD Collection" example. The password is hard coded there rather than picking it up from config.inc.php.
Stackoverflow uses such function to determine the age of a user.
The given answer is
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
So your helper method would look like
public static string Age(this HtmlHelper helper, DateTime birthday)
{
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (now < birthday.AddYears(age)) age--;
return age.ToString();
}
Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.
public static int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age;
}
NOTE: This should be considered a discussion rather than an actual answer.
An approximate approach is to operate __main__
in the module you want to create variables. For example there's a b.py
:
#!/usr/bin/env python
# coding: utf-8
def set_vars():
import __main__
print '__main__', __main__
__main__.B = 1
try:
print B
except NameError as e:
print e
set_vars()
print 'B: %s' % B
Running it would output
$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1
But this approach only works in a single module script, because the __main__
it import will always represent the module of the entry script being executed by python, this means that if b.py
is involved by other code, the B
variable will be created in the scope of the entry script instead of in b.py
itself. Assume there is a script a.py
:
#!/usr/bin/env python
# coding: utf-8
try:
import b
except NameError as e:
print e
print 'in a.py: B', B
Running it would output
$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1
Note that the __main__
is changed to 'a.py'
.
Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env.
This is what the build optimizer does under the hood:
The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed.
The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users.
Note : One update for Angular 5 and up, the ng build --prod
automatically take care of above process :)
Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.
php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >
If the legend is the same for both plots, there is a simple solution using grid.arrange
(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights
command to manually adjust and keep them the same size. You can even use grid.arrange
to make common axis titles. Note that this will require library(grid)
in addition to library(gridExtra)
. For vertical plots:
y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))
grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1),
arrangeGrob(p2, theme(legend.position="bottom"), ncol=1),
heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))
Here is the result for a similar graph for a project I was working on:
I would use a list:
string = []
for i in range(0, 9):
string.append("Hello")
This way, you would have 9 "Hello" and you could get them individually like this:
string[x]
Where x
would identify which "Hello" you want.
So, print(string[1])
would print Hello
.
@boernard 's answer solves this from the Android Studio IDE, but if you want to understand what's happening under the covers, it's a simple gradle build file update:
You can edit the build.gradle file from within the IDE (left pane: Gradle Scripts -> build.gradle (Module: app)
) or use the raw path (<proj_dir>/app/build.gradle
)
and add/update the following dependency section:
dependencies {
//
// IDE setting pulls in the specific version of v4 support you have installed:
//
//compile 'com.android.support:support-v4:21.0.3'
//
// generic directive pulls in any available version of v4 support:
//
compile 'com.android.support:support-v4:+'
}
Using the above generic compile directive, allows you to ship your code to anyone, provided they have some level of the Android Support Libraries v4
installed.
I changed a few lines of the source of stat_smooth
and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!
library(devtools)
source_gist("524eade46135f6348140")
df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
geom_smooth(method="lm",se=FALSE) +
geom_point() + facet_wrap(~class)
I used the code in @Ramnath's answer to format the equation. The stat_smooth_func
function isn't very robust, but it shouldn't be hard to play around with it.
https://gist.github.com/kdauria/524eade46135f6348140. Try updating ggplot2
if you get an error.
It's kind of ugly if the resizing code is almost as long as the code for building the graph in first place. So instead of resizing every element of the existing chart, why not simply reloading it? Here is how it worked for me:
function data_display(data){
e = document.getElementById('data-div');
var w = e.clientWidth;
// remove old svg if any -- otherwise resizing adds a second one
d3.select('svg').remove();
// create canvas
var svg = d3.select('#data-div').append('svg')
.attr('height', 100)
.attr('width', w);
// now add lots of beautiful elements to your graph
// ...
}
data_display(my_data); // call on page load
window.addEventListener('resize', function(event){
data_display(my_data); // just call it again...
}
The crucial line is d3.select('svg').remove();
. Otherwise each resizing will add another SVG element below the previous one.
This works for me:
var tP = $("img").css("padding").split(" ");
var Padding = {
Top: tP[0] != null ? parseInt(tP[0]) : 0,
Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
};
Result example:
Object {Top: 5, Right: 8, Bottom: 5, Left: 8}
To make a total:
var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:
session := &Session{}
if (Session{}) == *session {
fmt.Println("session is empty")
}
Check this playground.
Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...
My full answer is here, but here is an explanatory image to supplement the other answers on this page. For me, understanding where all the variables were going was the most confusing part in the beginning.
#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator> // std::begin, std::end
int main() {
std::vector<int> v = {5,14,2,4,6};
auto result = std::min_element(std::begin(v), std::end(v));
if (std::end(v)!=result)
std::cout << *result << '\n';
}
The program you show has a few problems, the primary culprit being the for
condition: i<v[n]
. You initialize the array, setting the first 5 elements to various values and the rest to zero. n
is set to the number of elements you explicitly initialized so v[n]
is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.
Some minor issues:
avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)
avoid magic numbers. int v[100]
is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.
avoid using namespace std;
It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.
Use Calendar.getInstance().get(Calendar.MONTH)+1
to get current month.
Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.
$a = 15; $b = 2; $a + $b --> 152
But if you divide it before:
$a/1 + $b/1 --> 17
Example:
['Thanks You',
'Its fine no problem',
'Are you sure']
code block:
import pandas as pd
df = pd.DataFrame(lst)
Output:
0
0 Thanks You
1 Its fine no problem
2 Are you sure
It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:
df = pd.DataFrame(lst)
df.columns = ['']
Output will be like this:
0 Thanks You
1 Its fine no problem
2 Are you sure
or
df = pd.DataFrame(lst).to_string(header=False)
But the output will be a list instead of a dataframe:
0 Thanks You
1 Its fine no problem
2 Are you sure
Hope this helps!!
[Offering a somewhat more descriptive answer than the answer provided by @Ajni.]
This can also be achieved using LINQ fluent syntax:
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Note that each method (Where
, OrderBy
, Take
) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take
begins with:
Returns a specified number of contiguous elements from the start of a sequence.
Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.
IF NOT EXISTS (SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'newSchemaName' )
BEGIN
EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
dateDate.Ticks
should give you what you're looking for.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.
But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.
You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.
This JS snippet should work fine:
document.TheFormHere.test.Value = true;
Objects inside an array:
var cars = [
{ "id": 1, brand: "Ferrari" }
, { "id": 2, brand: "Lotus" }
, { "id": 3, brand: "Lamborghini" }
];
If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case foo.id) and the on update and on delete actions.
I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.
EDIT: Make sure both of the tables have the InnoDB engine selected.
const int WIDTH = 1024;
const int HEIGHT = 800;
If you want to set backgroundColor of button programmatically then this code will surly help you
Swift 3 and Swift 4
self.yourButton.backgroundColor = UIColor.red
Swift 2.3 or lower
self.yourButton.backgroundColor = UIColor.redColor()
Using RGB
self.yourButton.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)
or you can use float values
button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)
Abstract:
The reason why you are getting this error
message is because you are trying to call a method on an int
type of a variable. This would work if would have called len()
function on a list
type of a variable. Let's examin the two cases:
Fail:
num = 10
print(len(num))
The above will produce an error similar to yours due to calling len()
function on an int
type of a variable;
Success:
data = [0, 4, 8, 9, 12]
print(len(data))
The above will work since you are calling a function on a list
type of a variable;
I believe python just has next() and according to the doc, it throws an exception is there are no more elements.
You can choose:
if [[ $? -ne 0 ]]; then # -ne: not equal
if ! [[ $? -eq 0 ]]; then # -eq: equal
if [[ ! $? -eq 0 ]]; then
!
inverts the return of the following expression, respectively.
It sounds like you haven't used this IDE before. Read Eclipse's "Before You Begin" page and follow the instructions to the T. This will make sure that Eclipse, which is only an IDE, is actually linked to a compiler.
When doing branch updates from master, I notice that I sometimes over-click, and cause the branch to merge into the master, too. Found a way to undo that.
If your last commit was a merge, a little more love is needed:
git revert -m 1 HEAD
This will take care of the empty td:
<td style="min-width: 20px;"></td>
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
String <variable> = sh.getCell("A2").getContents();
Turn off the JavaScript Validator in the "Builders" config for your project:
Then either restart your Eclipse or/and rename the .js to something like .js_ then back again.
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
and in onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
}
if(resultCode == RESULT_CANCELED){
//handle cancel
}
}
}
You need to wrap your input with component, and add containerElement property with value 'label' ...
<RaisedButton
containerElement='label' // <-- Just add me!
label='My Label'>
<input type="file" />
</RaisedButton>
You can read more about it in this GitHub issue.
EDIT: Update 2019.
Check at the bottom answer from @galki
TLDR;
<input
accept="image/*"
className={classes.input}
style={{ display: 'none' }}
id="raised-button-file"
multiple
type="file"
/>
<label htmlFor="raised-button-file">
<Button variant="raised" component="span" className={classes.button}>
Upload
</Button>
</label>
You can use any of the following:
\b #A word break and will work for both spaces and end of lines.
(^|\s) #the | means or. () is a capturing group.
/\b(stackoverflow)\b/
Also, if you don't want to include the space in your match, you can use lookbehind/aheads.
(?<=\s|^) #to look behind the match
(stackoverflow) #the string you want. () optional
(?=\s|$) #to look ahead.
What does const
mean
First, realize that the semantics of a "const" keyword means different things to different people:
final
semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiableconst
pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instanceWhy or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070
While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const
include:
const
mean above)Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const
keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.
I'm going to assume that your lack of quotes around the selector is just a transcription error, but you should check it anyway. Also, I don't see where you are actually giving the form an id. Usually you do this with the htmlAttributes parameter. I don't see you using the signature that has it. Again, though, if the form is submitting at all, this could be a transcription error.
If the selector and the id aren't the problem I'm suspicious that it might be because the click handler is added via markup when you use the Ajax BeginForm extension. You might try using $('form').trigger('submit') or in the worst case, have the click handler on the anchor create a hidden submit button in the form and click it. Or even create your own ajax submission using pure jQuery (which is probably what I would do).
Lastly, you should realize that by replacing the submit button, you're going to totally break this for people who don't have javascript enabled. The way around this is to also have a button hidden using a noscript tag and handle both AJAX and non-AJAX posts on the server.
BTW, it's consider standard practice, Microsoft not withstanding, to add the handlers via javascript not via markup. This keeps your javascript organized in one place so you can more easily see what's going on on the form. Here's an example of how I would use the trigger mechanism.
$(function() {
$('form#ajaxForm').find('a.submit-link').click( function() {
$('form#ajaxForm').trigger('submit');
}).show();
}
<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
new AjaxOptions
{
UpdateTargetId = "DescriptionDiv",
HttpMethod = "post"
}, new { id = "ajaxForm" } )) {%>
Description:
<%= Html.TextBox("Description", Model.Description) %><br />
<a href="#" class="submit-link" style="display: none;">Save</a>
<noscript>
<input type="submit" value="Save" />
</noscript>
<% } %>
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
Click here to learn how to implement log4net in .NET Core 2.2
The following steps are taken from the above link, and break down how to add log4net to a .NET Core 2.2 project.
First, run the following command in the Package-Manager console:
Install-Package Log4Net_Logging -Version 1.0.0
Then add a log4net.config with the following information (please edit it to match your set up):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logfile.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p - %m%n" />
</layout>
</appender>
<root>
<!--LogLevel: OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>
Then, add the following code into a controller (this is an example, please edit it before adding it to your controller):
public ValuesController()
{
LogFourNet.SetUp(Assembly.GetEntryAssembly(), "log4net.config");
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
LogFourNet.Info(this, "This is Info logging");
LogFourNet.Debug(this, "This is Debug logging");
LogFourNet.Error(this, "This is Error logging");
return new string[] { "value1", "value2" };
}
Then call the relevant controller action (using the above example, call /Values/Get
with an HTTP GET), and you will receive the output matching the following:
2019-06-05 19:58:45,103 [9] INFO-[Log4NetLogging_Project.Controllers.ValuesController.Get:23] - This is Info logging
First of all, you can't pass to alert
second argument, use concatenation instead
alert("Input is " + inputValue);
However in order to get values from input better to use states like this
var MyComponent = React.createClass({_x000D_
getInitialState: function () {_x000D_
return { input: '' };_x000D_
},_x000D_
_x000D_
handleChange: function(e) {_x000D_
this.setState({ input: e.target.value });_x000D_
},_x000D_
_x000D_
handleClick: function() {_x000D_
console.log(this.state.input);_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" onChange={ this.handleChange } />_x000D_
<input_x000D_
type="button"_x000D_
value="Alert the text input"_x000D_
onClick={this.handleClick}_x000D_
/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<MyComponent />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
Base @Dan J this version don't care max/min, more like sql :)
public static bool IsBetween(this decimal me, decimal a, decimal b, bool include = true)
{
var left = Math.Min(a, b);
var righ = Math.Max(a, b);
return include
? (me >= left && me <= righ)
: (me > left && me < righ)
;
}
Use the command
npm config set strict-ssl false
If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.
CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;
MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html
INSERT INTO table
SELECT 'jonny', NULL
FROM dual -- Not Oracle? No need for dual, drop that line
WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
-- anything as EXISTS only checks existence
FROM table
WHERE name = 'jonny'
)
I use this method:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TEST {
static Scanner scn;
public static void main(String[] args) {
String text = "";
try{
scn = new Scanner(new File("test.txt"));
}catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
while(scn.hasNext()){
text += scn.next();
}
String[] arry = text.split(",");
//if need converting to float do this:
Float[] arrdy = new Float[arry.length];
for(int i = 0; i < arry.length; i++){
arrdy[i] = Float.parseFloat(arry[i]);
}
System.out.println(Arrays.toString(arrdy));
}
}
Other Alternatives from just renaming the file to .doc.....
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx
Here is a good place to start. You can also try using this Office Open XML.
http://www.ecma-international.org/publications/standards/Ecma-376.htm
use git bundle, or clone
copying the git directory is not a good solution because it is not atomic. If you have a large repository that takes a long time to copy and someone pushes to your repository, it will affect your back up. Cloning or making a bundle will not have this problem.
I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:
public static void DumbDebug(string message)
{
File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}
Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.
I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.
Implement the following class:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}
return false;
}
}
$ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
I was having same issue.
String[] arr= new String[] { "A", "B", "C" };
Object obj = arr;
And then passed the obj as varargs argument. It worked.
You didn't create your project as "Dynamic Web Project", so Eclipse doesn't recognize it like a web project. Create a new "Dynamic Web Project" or go to Properties ? Projects Facets and check Dynamic Web Module.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
Just set the last value of the enum to a value large enough to make it the size you would like the enum to be, it should then be that size:
enum value{a=0,b,c,d,e,f,g,h,i,j,l,m,n,last=0xFFFFFFFFFFFFFFFF};
Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.
This was my case
I had a entity Student which was having many-to-one relation with another entity Classes (the classes which he studied).
I wanted to save the data into another table, which was having foreign keys of both Student and Classes. At some instance of execution, I was bringing a List of Students under some conditions, and each Student will have a reference of Classes class.
Sample code :-
Iterator<Student> itr = studentId.iterator();
while (itr.hasNext())
{
Student student = (Student) itr.next();
MarksCardSiNoGen bo = new MarksCardSiNoGen();
bo.setStudentId(student);
Classes classBo = student.getClasses();
bo.setClassId(classBo);
}
Here you can see that, I'm setting both Student and Classes reference to the BO I want to save. But while debugging when I inspected student.getClasses()
it was showing this exception(com.sun.jdi.InvocationException
).
The problem I found was that, after fetching the Student list using HQL query, I was flushing and closing the session. When I removed that session.close();
statement the problem was solved.
The session was closed when I finally saved all the data into table(MarksCardSiNoGen).
Hope this helps.
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
I think you have to draw the listitems yourself to achieve this.
Here's a post with the same kind of question.
I think this should work .. :)
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
You can put this in your .h file for your class and define it as property, in XCode 7:
@property int (*stuffILike) [10];
always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');
create DateTime instance, holding the current datetime
$datetime = new DateTime();
create one day interval
$interval = new DateInterval('P1D');
modify the DateTime instance
$datetime->sub($interval);
display the result, or print_r($datetime);
for more insight
echo $datetime->format('Y-m-d');
TIP:
If you don't want to change the default timezone, use the DateTimeZone
class instead.
$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone);
or just include it inside the constructor in this form new DateTime("now", $myTimezone);
As a general rule, you can’t just set the color of a horizontal line with CSS like you would anything else. First of all, Internet Explorer needs the color in your CSS to read like this:
“color: #123455”
But Opera and Mozilla needs the color in your CSS to read like this:
“background-color: #123455”
So, you will need to add both options to your CSS.
Next, you will need to give the horizontal line some dimensions or it will default to the standard height, width and color set by your browser. Here is a sample code of what your CSS should look like to get the blue horizontal line.
hr {
border: 0;
width: 100%;
color: #123455;
background-color: #123455;
height: 5px;
}
Or you could just add the style to your HTML page directly when you insert a horizontal line, like this:
<hr style="background:#123455" />
Hope this helps.
There is no shortcut for converting from int[]
to List<Integer>
as Arrays.asList
does not deal with boxing and will just create a List<int[]>
which is not what you want. You have to make a utility method.
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
intList.add(i);
}
It's up to the user whether they want to use new tabs or new windows, it isn't the business of the developer to modify this behaviour. I do not think you can do it.
Pet peeve of mine - I hate it when sites force me to open in a new window / tab - I am quite capable of making that decision for myself. Particularly when they do it in javascript - that is really unhelpful.
I just ran into an instance where...
int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];
...did not produce the results I was looking for. In 'myVal' above, the value stored in the array in position 21 was '0'. It should have been a '1'. I'm not sure why I received an inaccurate value for this and it baffled me until I found another way in C# to convert an INT to a bit array:
int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];
This produced the result 'true' as a boolean value for 'myVal'.
I realize this may not be the most efficient way to obtain this value, but it was very straight forward, simple, and readable.
Can this not be done with a user-defined function to replicate whatever your stored procedure is doing?
SELECT udfMyFunction(user_id), someOtherField, etc FROM MyTable WHERE WhateverCondition
where udfMyFunction is a function you make that takes in the user ID and does whatever you need to do with it.
See http://www.sqlteam.com/article/user-defined-functions for a bit more background
I agree that cursors really ought to be avoided where possible. And it usually is possible!
(of course, my answer presupposes that you're only interested in getting the output from the SP and that you're not changing the actual data. I find "alters user data in a certain way" a little ambiguous from the original question, so thought I'd offer this as a possible solution. Utterly depends on what you're doing!)
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
In my opinion, uniqueidentifier
/ GUID is neither a varchar
nor an nvarchar
but a char(36)
. Therefore I use:
CAST(xyz AS char(36))
A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)
If there is no vertical scrolling then you can use position:absolute
and height:100%
declared on html and body elements.
Another option is to use viewport height units, see Make div 100% height of browser window
Absolute position Example:
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
height:50%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
height:100vh;_x000D_
}_x000D_
.col-50vh {_x000D_
height:50vh;_x000D_
}_x000D_
#mmenu_screen--information{_x000D_
background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
<div class="row col-100vh">_x000D_
<div class="col-xs-6 col-100vh">_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
BOOKING BUTTON_x000D_
</div>_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
INFO BUTTON_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
DIRECT ACTION BUTTON_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can use the RedirectToAction()
method, then the action you redirect to can return a View. The easiest way to do this is:
return RedirectToAction("Index", model);
Then in your Index method, return the view you want.
you can do this :
private void setRowNumber(DataGridView dgv)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.HeaderCell.Value = row.Index + 1;
}
dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}
I think Mockito @InjectMocks
is the way to go.
Depending on your intention you can use:
More info in docs
Below is an example with field injection:
Classes:
public class Foo
{
private Bar bar = new Bar();
public void foo()
{
bar.someMethod();
}
}
public class Bar
{
public void someMethod()
{
//something
}
}
Test:
@RunWith(MockitoJUnitRunner.class)
public class FooTest
{
@Mock
Bar bar;
@InjectMocks
Foo foo;
@Test
public void FooTest()
{
doNothing().when( bar ).someMethod();
foo.foo();
verify(bar, times(1)).someMethod();
}
}
Use Glide library instead of directly loading into imageview
Glide : https://github.com/bumptech/glide
Glide.with(this).load(Uri.parse(filelocation))).into(img_selectPassportPic);
string utf8String = "Acción";
string propEncodeString = string.Empty;
byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
utf8_Bytes[i] = (byte)utf8String[i];
}
propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);
Output should look like
Acción
day’s displays day's
call DecodeFromUtf8();
private static void DecodeFromUtf8()
{
string utf8_String = "day’s";
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
utf8_String = Encoding.UTF8.GetString(bytes);
}
You can use the eq method or selector:
$('ul').find('li').eq(index).css({'background-color':'#343434'});
UPDATE: By version 41 of Google Chrome, initMouseEvent
seemed to have a changed behavior.
this can be done by simulating ctrl
+ click
(or any other key/event combinations that open a background tab) on a dynamically generated a
element with its href
attribute set to the desired url
In action: fiddle
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
tested only on chrome
A RESTful resource controller sets up some default routes for you and even names them.
Route::resource('users', 'UsersController');
Gives you these named routes:
Verb Path Action Route Name
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{user} show users.show
GET /users/{user}/edit edit users.edit
PUT|PATCH /users/{user} update users.update
DELETE /users/{user} destroy users.destroy
And you would set up your controller something like this (actions = methods)
class UsersController extends BaseController {
public function index() {}
public function show($id) {}
public function store() {}
}
You can also choose what actions are included or excluded like this:
Route::resource('users', 'UsersController', [
'only' => ['index', 'show']
]);
Route::resource('monkeys', 'MonkeysController', [
'except' => ['edit', 'create']
]);
Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create
and edit
routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create
nor edit
methods.
Route::apiResource('users', 'UsersController');
RESTful Resource Controller documentation
An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.
Route::controller('users', 'UserController');
Would lead you to set up the controller with a sort of RESTful naming scheme:
class UserController extends BaseController {
public function getIndex()
{
// GET request to index
}
public function getShow($id)
{
// get request to 'users/show/{id}'
}
public function postStore()
{
// POST request to 'users/store'
}
}
Implicit Controller documentation
It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes
. I typically use RESTful Resource controllers in combination with explicit routes.
The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.
There could be one of the reasons that You might have created your advertise from adMob console by clicking yes that your app is already in playstore and giving url of your live app.Now in that case you wont able to run your ads in any other projects which is having diff package id then the live one(not even test advertise).You have to implement the ads in live project containing same package id and in other case will be getting ad failed to load ad : 3.
Thanks! Happy coding!
Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps
https://nominatim.openstreetmap.org/search?q=Mumbai&format=json
Here is the API documentation for reference.
Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.
Other way of doing this: Assuming that you have a TextBox input type, Create a Form, and have the textbox value as a public property.
public partial class TextPrompt : Form
{
public string Value
{
get { return tbText.Text.Trim(); }
}
public TextPrompt(string promptInstructions)
{
InitializeComponent();
lblPromptText.Text = promptInstructions;
}
private void BtnSubmitText_Click(object sender, EventArgs e)
{
Close();
}
private void TextPrompt_Load(object sender, EventArgs e)
{
CenterToParent();
}
}
In the main form, this will be the code:
var t = new TextPrompt(this, "Type the name of the settings file:");
t.ShowDialog()
;
This way, the code looks cleaner:
I had a similar problem. I had a char*
buffer with the .so name in it.
I could not convert the char*
variable to LPCTSTR
. Here's how I got around it...
char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);
The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
Since virtualenvs contain pip by default, I almost never install pip globally. What I do ends up looking more like:
$ sudo apt-get install python-setuptools
$ curl -O http://python-distribute.org/distribute_setup.py
$ sudo python distribute_setup.py
$ sudo easy_install virtualenv
I then proceed to install and set up virtualenvwrapper to my liking and off I go. it might also be worthwhile to take a look at Jeremy Avnet's virtualenv-burrito:
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
@jeb
And after using this, the stderr seems to be inaccessible
No, try this:
@echo off 2>Nul 3>Nul 4>Nul
ben ali
mubarak 2>&1
gadeffi
..next ?
echo hello Tunisia
pause
But why it works?
sorry, i answer the question in frensh:
( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )
one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]
all(x in two for x in one)
Explanation: Generator creating booleans by looping through list one
checking if that item is in list two
. all()
returns True
if every item is truthy, else False
.
There is also an advantage that all
return False on the first instance of a missing element rather than having to process every item.
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
I removed the float from the second div to make it work.
RewriteCond %{HTTP:X-Forwarded-Proto} =https
The IDLE shell window is not the same as a terminal shell (e.g. running sh
or bash
). Rather, it is just like being in the Python interactive interpreter (python -i
). The easiest way to run a script in IDLE is to use the Open
command from the File
menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run
-> Run Module
command (shortcut F5).
JStack is quite inexpensive - one option would be to pipe the output through grep to find active threads and then pipe through wc -l.
More graphically is JConsole, which displays the thread count for a given process.
Wrapping it with div should work. I tested it in Firefox, Chrome on Fedora 13 (demo).
#content {
width: 95%;
height: 95%;
margin: auto;
}
#myCanvas {
width: 100%;
height: 100%;
border: 1px solid black;
}
And the canvas should be enclosed in tag
<div id="content">
<canvas id="myCanvas">Your browser doesn't support canvas tag</canvas>
</div>
Let me know if it works. Cheers.
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
Here is how you could do it with Java 11's java.net.http package:
var fileA = new File("a.pdf");
var fileB = new File("b.pdf");
var mimeMultipartData = MimeMultipartData.newBuilder()
.withCharset(StandardCharsets.UTF_8)
.addFile("file1", fileA.toPath(), Files.probeContentType(fileA.toPath()))
.addFile("file2", fileB.toPath(), Files.probeContentType(fileB.toPath()))
.build();
var request = HttpRequest.newBuilder()
.header("Content-Type", mimeMultipartData.getContentType())
.POST(mimeMultipartData.getBodyPublisher())
.uri(URI.create("http://somehost/upload"))
.build();
var httpClient = HttpClient.newBuilder().build();
var response = httpClient.send(request, BodyHandlers.ofString());
With the following MimeMultipartData:
public class MimeMultipartData {
public static class Builder {
private String boundary;
private Charset charset = StandardCharsets.UTF_8;
private List<MimedFile> files = new ArrayList<MimedFile>();
private Map<String, String> texts = new LinkedHashMap<>();
private Builder() {
this.boundary = new BigInteger(128, new Random()).toString();
}
public Builder withCharset(Charset charset) {
this.charset = charset;
return this;
}
public Builder withBoundary(String boundary) {
this.boundary = boundary;
return this;
}
public Builder addFile(String name, Path path, String mimeType) {
this.files.add(new MimedFile(name, path, mimeType));
return this;
}
public Builder addText(String name, String text) {
texts.put(name, text);
return this;
}
public MimeMultipartData build() throws IOException {
MimeMultipartData mimeMultipartData = new MimeMultipartData();
mimeMultipartData.boundary = boundary;
var newline = "\r\n".getBytes(charset);
var byteArrayOutputStream = new ByteArrayOutputStream();
for (var f : files) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + f.name + "\"; filename=\"" + f.path.getFileName() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Type: " + f.mimeType).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(Files.readAllBytes(f.path));
byteArrayOutputStream.write(newline);
}
for (var entry: texts.entrySet()) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(entry.getValue().getBytes(charset));
byteArrayOutputStream.write(newline);
}
byteArrayOutputStream.write(("--" + boundary + "--").getBytes(charset));
mimeMultipartData.bodyPublisher = BodyPublishers.ofByteArray(byteArrayOutputStream.toByteArray());
return mimeMultipartData;
}
public class MimedFile {
public final String name;
public final Path path;
public final String mimeType;
public MimedFile(String name, Path path, String mimeType) {
this.name = name;
this.path = path;
this.mimeType = mimeType;
}
}
}
private String boundary;
private BodyPublisher bodyPublisher;
private MimeMultipartData() {
}
public static Builder newBuilder() {
return new Builder();
}
public BodyPublisher getBodyPublisher() throws IOException {
return bodyPublisher;
}
public String getContentType() {
return "multipart/form-data; boundary=" + boundary;
}
}
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
In my case I had in one report many different datasets to DB and Analysis Services Cube. Looks like that datasets blocked each other and generated such error. For me helped option "Use single transaction when processing the queries" in the CUBE datasource properties
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
You can define a function type in interface in various ways,
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
Using is very straight forward,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}
There are multiple ways of doing things because there were never any protocols built into the standards. You use whatever ad-hoc "standard" your equipment implements.
Just based on the names, RTS/CTS would seem to be a natural fit. However, it's backwards from the needs that developed over time. These signals were created at a time when a terminal would batch-send a screen full of data, but the receiver might not be ready, thus the need for flow control. Later the problem would be reversed, as the terminal couldn't keep up with data coming from the host, but the RTS/CTS signals go the wrong direction - the interface isn't orthogonal, and there's no corresponding signals going the other way. Equipment makers adapted as best they could, including using the DTR and DSR signals.
EDIT
To add a bit more detail, its a two level hierarchy so "officially" both must happen for communication to take place. The behavior is defined in the original CCITT (now ITU-T) standard V.28.
The DCE is a modem connecting between the terminal and telephone network. In the telephone network was another piece of equipment which split off to the data network, eg. X.25.
The modem has three states: Powered off, Ready (Data Set Ready is true), and connected (Data Carrier Detect)
The terminal can't do anything until the modem is connected.
When the modem wants to send data, it raises RTS and the modem grants the request with CTS. The modem lowers CTS when its internal buffer is full.
So nostalgic!
Go to:
Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter
There you can see which external libraries you have installed for python2 and which for python3.
Select the required python version according to your requirements.
Same problem with the 'script' plugin in the Atom editor, which is an old version of node, not having btoa(), nor atob(), nor does it support the Buffer datatype. Following code does the trick:
var Base64 = new function() {_x000D_
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="_x000D_
this.encode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = Base64._utf8_encode(input);_x000D_
while (i < input.length) {_x000D_
chr1 = input.charCodeAt(i++);_x000D_
chr2 = input.charCodeAt(i++);_x000D_
chr3 = input.charCodeAt(i++);_x000D_
enc1 = chr1 >> 2;_x000D_
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);_x000D_
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);_x000D_
enc4 = chr3 & 63;_x000D_
if (isNaN(chr2)) {_x000D_
enc3 = enc4 = 64;_x000D_
} else if (isNaN(chr3)) {_x000D_
enc4 = 64;_x000D_
}_x000D_
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
this.decode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3;_x000D_
var enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");_x000D_
while (i < input.length) {_x000D_
enc1 = keyStr.indexOf(input.charAt(i++));_x000D_
enc2 = keyStr.indexOf(input.charAt(i++));_x000D_
enc3 = keyStr.indexOf(input.charAt(i++));_x000D_
enc4 = keyStr.indexOf(input.charAt(i++));_x000D_
chr1 = (enc1 << 2) | (enc2 >> 4);_x000D_
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);_x000D_
chr3 = ((enc3 & 3) << 6) | enc4;_x000D_
output = output + String.fromCharCode(chr1);_x000D_
if (enc3 != 64) {_x000D_
output = output + String.fromCharCode(chr2);_x000D_
}_x000D_
if (enc4 != 64) {_x000D_
output = output + String.fromCharCode(chr3);_x000D_
}_x000D_
}_x000D_
output = Base64._utf8_decode(output);_x000D_
return output;_x000D_
}_x000D_
_x000D_
this._utf8_encode = function(string) {_x000D_
string = string.replace(/\r\n/g, "\n");_x000D_
var utftext = "";_x000D_
for (var n = 0; n < string.length; n++) {_x000D_
var c = string.charCodeAt(n);_x000D_
if (c < 128) {_x000D_
utftext += String.fromCharCode(c);_x000D_
} else if ((c > 127) && (c < 2048)) {_x000D_
utftext += String.fromCharCode((c >> 6) | 192);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
} else {_x000D_
utftext += String.fromCharCode((c >> 12) | 224);_x000D_
utftext += String.fromCharCode(((c >> 6) & 63) | 128);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
}_x000D_
}_x000D_
return utftext;_x000D_
}_x000D_
_x000D_
this._utf8_decode = function(utftext) {_x000D_
var string = "";_x000D_
var i = 0;_x000D_
var c = 0,_x000D_
c1 = 0,_x000D_
c2 = 0,_x000D_
c3 = 0;_x000D_
while (i < utftext.length) {_x000D_
c = utftext.charCodeAt(i);_x000D_
if (c < 128) {_x000D_
string += String.fromCharCode(c);_x000D_
i++;_x000D_
} else if ((c > 191) && (c < 224)) {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));_x000D_
i += 2;_x000D_
} else {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
c3 = utftext.charCodeAt(i + 2);_x000D_
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));_x000D_
i += 3;_x000D_
}_x000D_
}_x000D_
return string;_x000D_
}_x000D_
}()_x000D_
_x000D_
var btoa = Base64.encode;_x000D_
var atob = Base64.decode;_x000D_
_x000D_
console.log("btoa('A') = " + btoa('A'));_x000D_
console.log("btoa('QQ==') = " + atob('QQ=='));_x000D_
console.log("btoa('B') = " + btoa('B'));_x000D_
console.log("btoa('Qg==') = " + atob('Qg=='));
_x000D_
Lists are mutable. whereas tuples are immutable. Accessing an offset element with index makes more sense in tuples than lists, Because the elements and their index cannot be changed.
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
According to the documentation.
In ES6 you can use array destructuring to catch your groups:
let text = '27 months';
let regex = /(\d+)\s*(days?|months?|years?)/;
let [, count, unit] = regex.exec(text) || [];
// count === '27'
// unit === 'months'
Notice:
let
skips the first value of the resulting array, which is the whole matched string|| []
after .exec()
will prevent a destructuring error when there are no matches (because .exec()
will return null
)This was My Mistake:
I had a minor update in a Push Notification content part and I did not even touch my code.
But I thought I might have to re-upload it in order to reflect that change in the latest version.
And I did.
Tried to upload 3 Builds One by One.
But Not a single build has shown in the Test Flight Version.(Shocked)
Later I realized my mistake that just by updating APNS content part without even touching my code, I was trying to upload a new build and was expecting to reflect it in the Test Flight. (So stupid of me)
I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white
to the HTML element. I overwrote that and everything was easy to handle from there.
Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.
GROUP_CONCAT(artists.artistname SEPARATOR '----')
The way you've written it, you're concatenating artists.artistname
with the '----'
string using the default comma separator.
The way to run the emulator from the console (I assume that you installed it before, using Android Studio) is:
run
cd ~/Android/Sdk/tools/bin && ./avdmanager list avd
OR
cd ~/Android/Sdk/tools && ./emulator -list-avds
You will get the list od your virtual installed devices. In my case it was:
Available Android Virtual Devices:
Name: Galaxy_Nexus_API_17
Device: Galaxy Nexus (Google)
Path: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd
Target: Google APIs (Google Inc.)
Based on: Android 4.2 (Jelly Bean) Tag/ABI: google_apis/x86
Skin: galaxy_nexus
Sdcard: /home/piotr/.android/avd/Galaxy_Nexus_API_17.avd/sdcard.img
Copy name of the device you want to run and then
cd ~/Android/Sdk/tools && ./emulator -avd NAME_OF_YOUR_DEVICE
in my case:
cd ~/Android/Sdk/tools && ./emulator -avd Nexus_5X_API_23
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
Sleep meaning that thread is do nothing. Time is too large beacuse anthor thread query,but not disconnect server, default wait_timeout=28800;so you can set values smaller,eg 10. also you can kill the thread.
If you are using Mac(OSX)
Based on the current tab, to select the file on project is : FN + OPTION + F1
Then in the popup you can Select in: Project View > Select In: Project
ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.
Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.
If you're iterating over an object instead of an array, you'll need to access the properties using:
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
That, or change your object to an array.
They are binding to keydown in the autocomplete source, so triggering the keydown will case it to update.
$("#CompanyList").trigger('keydown');
They aren't binding to the 'change' event because that only triggers at the DOM level when the form field loses focus. The autocomplete needs to respond faster than 'lost focus' so it has to bind to a key event.
Doing this:
companyList.autocomplete('option','change').call(companyList);
Will cause a bug if the user retypes the exact option that was there before.
The JPA 2.0 Specification states that:
- The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
- The entity class must a be top-level class. An enum or interface must not be designated as an entity.
- The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
- If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
- Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.
The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.
The target "all" is an example of a dummy target - there is nothing on disk called "all". This means that when you do a "make all", make always thinks that it needs to build it, and so executes all the commands for that target. Those commands will typically be ones that build all the end-products that the makefile knows about, but it could do anything.
Other examples of dummy targets are "clean" and "install", and they work in the same way.
If you haven't read it yet, you should read the GNU Make Manual, which is also an excellent tutorial.
If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b
is a power of two, a % b == a & (b - 1)
.
For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63
, because 63 is 111111 in binary.
The masked, higher digits are not of interest to us. Try it out!
Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!
AST_NODE* Statement(AST_NODE* node)
is missing a semicolon (a major clue was the error message "In function ‘Statement’: ...") and so is line 24,
return node
(Once you fix those, you will encounter other problems, some of which are mentioned by others here.)
There is this tool ChangeVersion [1]
List of features (from the website):
- command line interface
- support for .EXE, .DLL and .RES files
- update FileVersion and ProductVersion based on a version mask
- add/change/remove version key strings
- adjust file flags (debug, special, private etc)
- update project files ( .bdsproj | .bpr | .bpk | .dproj )
- add/change main application icon
- use ini file with configuration
- Windows Vista support (needs elevation)
- easy to integrate into a continuous build environment
Full Disclosure: I know the guy who wrote this tool, I used to work with him. But this also means that I know he makes quality software ;)
[1] the link is dead. There seems to be mirrored version at download.cnet.com.
I had the same issue with VS2017. Following solved the issue.
reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
This should solve your problem. Refer to this link for more details.
why does the Text take up the full space of the View, instead of just the space for "Hello"?
Because the View
is a flex container and by default has flexDirection: 'column'
and alignItems: 'stretch'
, which means that its children should be stretched out to fill its width.
(Note, per the docs, that all components in React Native are display: 'flex'
by default and that display: 'inline'
does not exist at all. In this way, the default behaviour of a Text
within a View
in React Native differs from the default behaviour of span
within a div
on the web; in the latter case, the span would not fill the width of the div
because a span
is an inline element by default. There is no such concept in React Native.)
How can the Text be floated / aligned to the right?
The float
property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:
textAlign: 'right'
on the Text
element<View>
<Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>
(This approach doesn't change the fact that the Text
fills the entire width of the View
; it just right-aligns the text within the Text
.)
alignSelf: 'flex-end'
on the Text
<View>
<Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>
This shrinks the Text
element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View
.
alignItems: 'flex-end'
on the View
<View style={{alignItems: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
This is equivalent to setting alignSelf: 'flex-end'
on all the View
's children.
flexDirection: 'row'
and justifyContent: 'flex-end'
on the View
<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
flexDirection: 'row'
sets the main direction of layout to be horizontal instead of vertical; justifyContent
is just like alignItems
, but controls alignment in the main direction instead of the cross direction.
flexDirection: 'row'
on the View
and marginLeft: 'auto'
on the Text
<View style={{flexDirection: 'row'}}>
<Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>
This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.
position: 'absolute'
and right: 0
on the Text
:<View>
<Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>
Like in real CSS, this takes the Text
"out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View
by default (although you can explicitly set a distance from the top of the View
using the top
style property).
Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../
apiVersion: skaffold/v2beta4
kind: Config
metadata:
name: frontend
build:
artifacts:
- image: nginx-angular-ui
context: ../../../
sync:
# A local build will update dist and sync it to the container
manual:
- src: './dist/apps'
dest: '/usr/share/nginx/html'
docker:
dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
- image: webapi/image
context: ../../../../api/
docker:
dockerfile: ./dockerfile
deploy:
kubectl:
manifests:
- ./.k8s/*.yml
skaffold run -f ./skaffold.yaml
In the root open the .editorconfig file and change:
end_of_line = lf
to
end_of_line = auto
This should fix it for new files.
Something in the lines of
myString.split("\\s+");
This groups all white spaces as a delimiter.
So if I have the string:
"Hello[space character][tab character]World"
This should yield the strings "Hello"
and "World"
and omit the empty space between the [space]
and the [tab]
.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal "\s"
, which means, you need to pass "\\s"
. It can get a bit confusing.
The \\s
is equivalent to [ \\t\\n\\x0B\\f\\r]
.
try this...
public class Student
{
public int Grade { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name{0} : Grade{1}", Name, Grade);
}
}
class Program
{
static void Main(string[] args)
{
List<Student> listStudents = new List<Student>();
listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });
listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
}
}
See also question: Can I create a custom classpath on a per application basis in Tomcat
Tomcat 7 Context hold Loader element. According to docs deployment descriptor (what in <Context>
tag) can be placed in:
$CATALINA_BASE/conf/server.xml
- bad - require server restarts in order to reread config$CATALINA_BASE/conf/context.xml
- bad - shared across all applications$CATALINA_BASE/work/$APP.war:/META-INF/context.xml
- bad - require repackaging in order to change config$CATALINA_BASE/work/[enginename]/[hostname]/$APP/META-INF/context.xml
- nice, but see last option!!$CATALINA_BASE/webapps/$APP/META-INF/context.xml
- nice, but see last option!!$CATALINA_BASE/conf/[enginename]/[hostname]/$APP.xml
- best - completely out of application and automatically scanned for changes!!!Here my config which demonstrate how to use development version of project files out of $CATALINA_BASE
hierarchy (note that I place this file into src/test/resources
dir and intruct Maven to preprocess ${basedir}
placeholders through pom.xml
<filtering>true</filtering>
so after build in new environment I copy it to $CATALINA_BASE/conf/Catalina/localhost/$APP.xml
):
<Context docBase="${basedir}/src/main/webapp"
reloadable="true">
<!-- http://tomcat.apache.org/tomcat-7.0-doc/config/context.html -->
<Resources className="org.apache.naming.resources.VirtualDirContext"
extraResourcePaths="/WEB-INF/classes=${basedir}/target/classes,/WEB-INF/lib=${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
<Loader className="org.apache.catalina.loader.VirtualWebappLoader"
virtualClasspath="${basedir}/target/classes;${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
<JarScanner scanAllDirectories="true"/>
<!-- Use development version of JS/CSS files. -->
<Parameter name="min" value="dev"/>
<Environment name="app.devel.ldap" value="USER" type="java.lang.String" override="true"/>
<Environment name="app.devel.permitAll" value="true" type="java.lang.String" override="true"/>
</Context>
UPDATE Tomcat 8 change syntax for <Resources>
and <Loader>
elements, corresponding part now look like:
<Resources>
<PostResources className="org.apache.catalina.webresources.DirResourceSet"
webAppMount="/WEB-INF/classes" base="${basedir}/target/classes" />
<PostResources className="org.apache.catalina.webresources.DirResourceSet"
webAppMount="/WEB-INF/lib" base="${basedir}/target/${project.build.finalName}/WEB-INF/lib" />
</Resources>
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
app.directive("ngScopeElement", function () {
var directiveDefinitionObject = {
restrict: "A",
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope[iAttrs.ngScopeElement] = iElement;
}
};
}
};
return directiveDefinitionObject;
});
Usage:
app.directive("myDirective", function() {
return {
template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
scope.list[0] // scope.list is the jqlite element,
// scope.list[0] is the native dom element
}
}
});
Some remarks:
scope.list
from myDirective
s postLink-Function, which you are very likely using anywayngScopeElement
uses a preLink-function, so that directives nested within the element having ng-scope-element
can already access scope.list
$string = '9,[email protected],8';
$array = explode(',', $string);
For more complicated situations, you may need to use preg_split
.
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))