Adding to Santosh :
You can load React by
import React from 'react'
For large data l recommend you use the library "dask"
e.g:
# Dataframes implement the Pandas API
import dask.dataframe as dd
df = dd.read_csv('s3://.../2018-*-*.csv')
You can read more from the documentation here.
Another great alternative would be to use modin because all the functionality is identical to pandas yet it leverages on distributed dataframe libraries such as dask.
This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):
During my form/model load :
$.ajax({
type: "POST",
...
success: function (data) {
selectCountries(fixedEncodeURI(data.countries));
}
Call to select data for Select2:
var countrySelect = $('.select_country');
function selectCountries(countries)
{
if (countries) {
$.ajax({
type: 'GET',
url: "/regions/getCountries/",
data: $.param({ 'idsSelected': countries }, true),
}).then(function (data) {
// create the option and append to Select2
$.each(data, function (index, value) {
var option = new Option(value.text, value.id, true, true);
countrySelect.append(option).trigger('change');
console.log(option);
});
// manually trigger the `select2:select` event
countrySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
}
and if you may be having issues with encoding you may change as your requirement:
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");
}
If you are matching the full value of the field use
WHERE UPPER(fieldName) = 'ANGEL'
EDIT: From your comment you want to use:
SELECT
RPAD(a.name, 10,'=') "Nombre del Cliente"
, RPAD(b.name, 12,'*') "Nombre del Consumidor"
FROM
s_customer a,
s_region b
WHERE
a.region_id = b.id
AND UPPER(a.name) LIKE '%SPORT%'
Note that git checkout --ours|--theirs
will overwrite the files entirely, by choosing either theirs
or ours
version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).
If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs
, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file
; see details in this answer.
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething
is updated as well sonce both reference the same object, so when you access the second element myList.get(1)
(which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething);
save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
java: Java application executor which is associated with a console to display output/errors
javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.
javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.
All are part of JRE and use the same JVM.
var votevalue = $.map($(this).data('votevalue'), Number);
SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.
Here is one source for information on the SQL Server logical processing phases.
You are most likely looking for the IIS_IUSRS account.
The correct script for postgres (Ubuntu) is:
COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';
Try the SVG2VectorDrawable Plugin. Go to Preferences->Plugins->Browse Plugins and install SVG2VectorDrawable. Great for converting sag files to vector drawable. Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.
If SET time_zone or SET GLOBAL time_zone does not work, you can change as below:
Change timezone system, example: ubuntu... $ sudo dpkg-reconfigure tzdata
Restart the server or you can restart apache2 and mysql (/etc/init.d/mysql restart)
In my case, the problem was that the new library (gradle dependency) that I had added was relying on some other dependencies and two of those underlying dependencies were conflicting/clashing with some dependencies of other libraries/dependencies in my build script. Specifically, I added Apache Commons Validator
(for email validation), and two of its dependencies (Apache Commons Logging
and Apache Commons Collections
) were conflicting with those used by Robolectric (because different versions of same libraries were present in my build path). So I excluded those conflicting versions of dependencies (modules
) when adding the new dependency (the Validator
):
compile ('commons-validator:commons-validator:1.4.1') {
exclude module: 'commons-logging'
exclude module: 'commons-collections'
}
You can see the dependencies of your gradle module(s) (you might have only one module in your project) using the following gradle command (I use the gradle wrapper that gets created for you if you have created your project in Android Studio/Intellij Idea). Run this command in your project's root directory:
./gradlew :YOUR-MODULE-NAME:dependencies
After adding those exclude
directives and retrying to run, I got a duplicate file
error for NOTICE.txt
that is used by some apache commons libraries like Logging and Collections. I had to exclude that text file when packaging. In my build.gradle, I added:
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/notice.txt'
exclude 'META-INF/NOTICE.txt'
}
It turned out that the new library (the Validator
) can work with slightly older versions of its dependencies/modules (which are already imported into my build path by another library (Robolectric)). This was the case with this specific library, but other libraries might be using the latest API of the underlying dependencies (in which case you have to try to see if the other libraries that rely on the conflicting module/dependency are able to work with the newer version (by excluding the older version of the module/dependecy under those libraries's entries)).
The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.
So instead, you should format your Groovy like this:
stage('Setting the variables values') {
steps {
sh '''#!/bin/bash
echo "hello world"
'''
}
}
And it will execute with /bin/bash.
The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.
Try using headers to do authentication:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662
you can use this trick to run tomcat using cmd and directly by tomcat bin folder.
1. set the path of jdk.
2.
To set path. go to Desktop and right click on computer icon. Click the Properties
go to Advance System Settings.
then Click Advance to Environment variables.
Click new and set path AS,
in the column Variable name=JAVA_HOME
Variable Value=C:\Program Files\Java\jdk1.6.0_19
Click ok ok.
now path is stetted.
3.
Go to tomcat folder where you installed the tomcat. go to bin folder. there are two window batch files.
1.Startup
2.Shutdown.
By using cmd if you installed the tomcate in D Drive
type on cmd screen
D:
Cd tomcat\bin then type Startup.
4. By clicking them you can start and stop the tomcat.
5.
Final step.
if you start and want to check it.
open a Browser in URL bar type.
**HTTP://localhost:8080/**
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
You are doing integer arithmetic, so there the result is correct. Try
percentage=((double)number/total)*100;
BTW the %f
expects a double
not a float
. By pure luck that is converted here, so it works out well. But generally you'd mostly use double
as floating point type in C nowadays.
nVarchar2 is a Unicode-only storage.
Though both data types are variable length String datatypes, you can notice the difference in how they store values. Each character is stored in bytes. As we know, not all languages have alphabets with same length, eg, English alphabet needs 1 byte per character, however, languages like Japanese or Chinese need more than 1 byte for storing a character.
When you specify varchar2(10), you are telling the DB that only 10 bytes of data will be stored. But, when you say nVarchar2(10), it means 10 characters will be stored. In this case, you don't have to worry about the number of bytes each character takes.
Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.
This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.
This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API's.
As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.
To treat validation when a field is null in the database, you could add the following condition.
String name = (oRs.getString ("name_column"))! = Null? oRs.getString ("name_column"): "";
with this you can validate when a field is null and do not mark an exception.
go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.
run "DOSBox 0.74 Options.bat"
the script starts notepad with configuration file: here change
windowresolution=1600x800
output=ddraw
(the resolution can't be changed if output=surface - that's the default).
I solved like this
$stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
$list=array();
$i=0;
while ($cresult=$stmt->fetch()){
$list[$i][0]=$cde;
$list[$i][1]=$v_off;
$list[$i][2]=$em_nm;
$list[$i][3]=$q_id;
$list[$i][4]=$v_m;
$i=$i+1;
}
echo json_encode($list);
This will be returned to ajax as result set and by using json parse in javascript part like this :
obj = JSON.parse(dataX);
I found this question because I was having issues with the OPTIONS request most browsers send. My app was routing the OPTIONS requests and using my IoC to construct lots of objects and some were throwing exceptions on this odd request type for various reasons.
Basically put in an ignore route for all OPTIONS requests if they are causing you problems:
var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "{*pathInfo}", constraints);
More info: Stop Web API processing OPTIONS requests
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
This should work !!!
file_name
= Name of the file you want to split.
10000
= Number of rows each split file would contain
file_part_
= Prefix of split file name (file_part_0,file_part_1,file_part_2..etc goes on)
split -d -l 10000 file_name.csv file_part_
echo $STRING | cut -d " " -f $N
I wanted to add, that in order to prevent it from being messed up in the first place you can type :set paste
before pasting. After pasting, you can type :set nopaste
for things like js-beautify and indenting to work again.
I found this page with detailed instructions to upgrade Anaconda to a major newer version of Python (from Anaconda 4.0+). First,
conda update conda
conda remove argcomplete conda-manager
I also had to conda remove
some packages not on the official list:
Depending on packages installed on your system, you may get additional UnsatisfiableError
errors - simply add those packages to the remove list. Next, install the version of Python,
conda install python==3.6
which takes a while, after which a message indicated to conda install anaconda-client
, so I did
conda install anaconda-client
which said it's already there. Finally, following the directions,
conda update anaconda
I did this in the Windows 10 command prompt, but things should be similar in Mac OS X.
I did it with css, ie: adding classes for arrows, but you can use images as well.
Bellow is an example with fontAwesome:
JS:
owl.owlCarousel({
...
// should be empty otherwise you'll still see prev and next text,
// which is defined in js
navText : ["",""],
rewindNav : true,
...
});
CSS
.owl-carousel .owl-nav .owl-prev,
.owl-carousel .owl-nav .owl-next,
.owl-carousel .owl-dot {
font-family: 'fontAwesome';
}
.owl-carousel .owl-nav .owl-prev:before{
// fa-chevron-left
content: "\f053";
margin-right:10px;
}
.owl-carousel .owl-nav .owl-next:after{
//fa-chevron-right
content: "\f054";
margin-right:10px;
}
Using images:
.owl-carousel .owl-nav .owl-prev,
.owl-carousel .owl-nav .owl-next,
.owl-carousel .owl-dot {
//width, height
width:30px;
height:30px;
...
}
.owl-carousel .owl-nav .owl-prev{
background: url('left-icon.png') no-repeat;
}
.owl-carousel .owl-nav .owl-next{
background: url('right-icon.png') no-repeat;
}
Maybe someone will find this helpful :)
GetAwaiter()
, that is used by await
, is implemented as an extension method in the Async CTP. I'm not sure what exactly are you using (you mention both the Async CTP and VS 2012 RC in your question), but it's possible the Async targeting pack uses the same technique.
The problem then is that extension methods don't work with dynamic
. What you can do is to explicitly specify that you're working with a Task
, which means the extension method will work, and then switch back to dynamic
:
private async void MyButtonClick(object sender, RoutedEventArgs e)
{
dynamic request = new SerializableDynamicObject();
request.Operation = "test";
Task<SerializableDynamicObject> task = Client(request);
dynamic result = await task;
// use result here
}
Or, since the Client()
method is actually not dynamic, you could call it with SerializableDynamicObject
, not dynamic
, and so limit using dynamic
as much as possible:
private async void MyButtonClick(object sender, RoutedEventArgs e)
{
var request = new SerializableDynamicObject();
dynamic dynamicRequest = request;
dynamicRequest.Operation = "test";
var task = Client(request);
dynamic result = await task;
// use result here
}
here is what you should put
local stringnumber = "10"
local a = tonumber(stringnumber)
print(a + 10)
output:
20
Looks like all the useEffect examples dont factor in you might want to trigger this with a state change.
const [aStateVariable, setAStateVariable] = useState(false);
const handleClick = () => {
setAStateVariable(true);
}
useEffect(() => {
if(aStateVariable === true) {
window.scrollTo(0, 0)
}
}, [aStateVariable])
In your case, since you are only showing 3 columns:
Name Value Business
or
Name Business Ecommerce Pro
why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.
I just fixed this problem by adding the following code in header:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Try:
SELECT * FROM table GROUP BY email
urllib3
To do that, you will need to manually encode query parameters in the URL.
>>> import urllib3
>>> http = urllib3.PoolManager()
>>> from urllib.parse import urlencode
>>> encoded_args = urlencode({"name":"Zion","salary":"1123","age":"23"})
>>> url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args
>>> r = http.request('PUT', url)
>>> import json
>>> json.loads(r.data.decode('utf-8'))
{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}
requests
>>> import requests
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
>>> r.status_code
200
I was getting from a conflict with join table defined in an association class ( with additional custom fields ) annotation and a join table defined in a many-to-many annotation.
The mapping definitions in two entities with a direct many-to-many relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.
The explanation and solution is that identified by FMaz008 above. In my situation, it was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the associative entity class. There is an example provided in this forum post Association models with extra fields:
public class Person {
/** @OneToMany(targetEntity="AssignedItems", mappedBy="person") */
private $assignedItems;
}
public class Items {
/** @OneToMany(targetEntity="AssignedItems", mappedBy="item") */
private $assignedPeople;
}
public class AssignedItems {
/** @ManyToOne(targetEntity="Person")
* @JoinColumn(name="person_id", referencedColumnName="id")
*/
private $person;
/** @ManyToOne(targetEntity="Item")
* @JoinColumn(name="item_id", referencedColumnName="id")
*/
private $item;
}
In JavaScript, there are no integers but only Number
s, which are implemented as double precision floating point numbers.
It means that if a Number a
is large enough, it can be considered equal to three consecutive integers:
a = 100000000000000000_x000D_
if (a == a+1 && a == a+2 && a == a+3){_x000D_
console.log("Precision loss!");_x000D_
}
_x000D_
True, it's not exactly what the interviewer asked (it doesn't work with a=0
), but it doesn't involve any trick with hidden functions or operator overloading.
For reference, there are a==1 && a==2 && a==3
solutions in Ruby and Python. With a slight modification, it's also possible in Java.
With a custom ==
:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Or an increasing a
:
def a
@a ||= 0
@a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
It's possible to modify Java Integer
cache:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
Integer a = 42;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Bad idea.");
}
}
}
In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor
In Eclipse open the Device Manager:
In the device manager you can add files to the SD Card here:
You need to correctly separate static data from instance data. In your code, onLoan
and setLoanItem()
are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.
BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.
We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.
Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):
In app did load at top, just do this...
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(CFStringRef)@"icz",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.
But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.
$ curl -D headers THEURLGOESHERE > /dev/null
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 27393 100 27393 0 0 24983 0 0:00:01 0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive
The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,
NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
(CFStringRef)@"text/calendar",
NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);
I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.
So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.
One way to get the list of distinct column names from the database is to use distinct()
in conjunction with values()
.
In your case you can do the following to get the names of distinct categories:
q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.
# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"
There are a couple of things to remember here. First, this will return a ValuesQuerySet
which behaves differently from a QuerySet
. When you access say, the first element of q
(above) you'll get a dictionary, NOT an instance of ProductOrder
.
Second, it would be a good idea to read the warning note in the docs about using distinct()
. The above example will work but all combinations of distinct()
and values()
may not.
PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:
class ProductOrder(models.Model):
product = models.CharField(max_length=20, primary_key=True)
category = models.CharField(max_length=30)
rank = models.IntegerField()
It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult. Example:
Valid:
@RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
final BindingResult bindingResult,
@RequestParam("pk") final long pk,
final Model model) {
}
Not Valid:
RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(@Valid final UpdateQuantityForm form,
@RequestParam("pk") final long pk,
final BindingResult bindingResult,
final Model model) {
}
If you want to use LINQ, use resourceSet.OfType<DictionaryEntry>()
. Using LINQ allows you, for example, to select resources based on their index (int) instead of key (string):
ResourceSet resourceSet = Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var entry in resourceSet.OfType<DictionaryEntry>().Select((item, i) => new { Index = i, Key = item.Key, Value = item.Value }))
{
Console.WriteLine(@"[{0}] {1}", entry.Index, entry.Key);
}
SWIFT 5
If you don't have a ViewController set as the initial ViewController in storyboard, you need to do 2 things:
Finally, you can now add your code in SceneDelegate:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Make sure you set an Storyboard ID for the view controller you want to instantiate
window?.rootViewController = storyboard.instantiateViewController(withIdentifier: identifier)
window?.makeKeyAndVisible()
}
I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.
However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:
class Foo {
private int id;
private string name;
public Foo(int id = 0, string name = "") {
this.id = id;
this.name = name;
}
}
class Main() {
// Foo Int:
Foo myFooOne = new Foo(12);
// Foo String:
Foo myFooTwo = new Foo(name:"Timothy");
// Foo Both:
Foo myFooThree = new Foo(13, name:"Monkey");
}
When you implement the constructor, you can use the optional arguments since defaults have been set.
I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.
According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.
In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.
When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.
Your reference is "pointing" to null, thus "Null -> Pointer".
The object lives in the VM memory space and the only way to access it is using this
references. Take this example:
public class Some {
private int id;
public int getId(){
return this.id;
}
public setId( int newId ) {
this.id = newId;
}
}
And on another place in your code:
Some reference = new Some(); // Point to a new object of type Some()
Some otherReference = null; // Initiallly this points to NULL
reference.setId( 1 ); // Execute setId method, now private var id is 1
System.out.println( reference.getId() ); // Prints 1 to the console
otherReference = reference // Now they both point to the only object.
reference = null; // "reference" now point to null.
// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );
// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
This an important thing to know - when there are no more references to an object (in the example above when reference
and otherReference
both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.
I believe you're using \w (word character) where you ought to be using \s (whitespace). Word characters typically consist of [A-Za-z0-9_], so that excludes your space, which then further fails to match on the optional minus sign or a digit.
If you want to checkout all the files 'anywhere'
git checkout -- $(git rev-parse --show-toplevel)
If you are using bash you can try alias:
into the .bashrc file add this line:
alias p='cd /home/serdar/my_new_folder/path/'
when you write "p" on the command line, it will change the directory.
I tried all the solutions above and I'm not discrediting any of them, but in my case, they didn't work.
For me, the problem was caused because the <header>
tag had a margin-top
of 5em and the <footer>
had a margin-bottom of 5em. I removed them and instead put some padding
(top and bottom, respectively). I'm not sure if replacing the margin was an ideal fix to the problem, but the point is that, if the first and last elements in your <body>
has some margins, you might want to look into it and remove them.
My html
and body
tags had the following styles
body {
line-height: 1;
min-height: 100%;
position: relative; }
html {
min-height: 100%;
background-color: #3c3c3c; }
If you do run()
in main method, the thread of main method will invoke the run
method instead of the thread you require to run.
The start()
method creates new thread and for which the run()
method has to be done
It is strange, but why this topic is not have this answer:
$lastKey = array_keys($array)[count($array)-1];
>>
is arithmetic shift right, >>>
is logical shift right.
In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.
For example: -2 represented in 8 bits would be 11111110
(because the most significant bit has negative weight). Shifting it right one bit using arithmetic shift would give you 11111111
, or -1. Logical right shift, however, does not care that the value could possibly represent a signed number; it simply moves everything to the right and fills in from the left with 0s. Shifting our -2 right one bit using logical shift would give 01111111
.
As previously mentioned, best practice is del(); or pop() if you need to know the value.
An alternate solution is to re-stack only those elements you want:
a = ['a', 'b', 'c', 'd']
def remove_element(list_,index_):
clipboard = []
for i in range(len(list_)):
if i is not index_:
clipboard.append(list_[i])
return clipboard
print(remove_element(a,2))
>> ['a', 'b', 'd']
eta: hmm... will not work on negative index values, will ponder and update
I suppose
if index_<0:index_=len(list_)+index_
would patch it... but suddenly this idea seems very brittle. Interesting thought experiment though. Seems there should be a 'proper' way to do this with append() / list comprehension.
pondering
in my project wsgi.py file i have this code (it works with virtualenv,django,apache2 in windows and python 3.4)
import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read())
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()
in virtualhost file conf i have
<VirtualHost *:80>
ServerName mysite
WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
DocumentRoot c:/myproject/myproject/
<Directory "c:/myproject/myproject/myproject/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.
The posttitle part of the URL is after your index.php
file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
It may be possible that the server is already running. Please check it by the command mongo is working or not.
For all those using Ubuntu with ppa:ondrej/php
PPA this will fix the problem:
apt install php7.0-mbstring php7.0-zip php7.0-xml
(see https://launchpad.net/~ondrej/+archive/ubuntu/php)
Thanks @Alexandre Barbosa for pointing this out!
EDIT 20160423:
One-liner to fix this issue:
sudo add-apt-repository -y ppa:ondrej/php && sudo apt update && sudo apt install -y php7.0-mbstring php7.0-zip php7.0-xml
(this will add the ppa noted above and will also make sure you always have the latest php. We use Ondrej's PHP ppa for almost two years now and it's working like charm)
The idea of non-blocking is that the loop iterations are quick. So to iterate for each tick should take short enough a time that the setTimeout will be accurate to within reasonable precision (off by maybe <100 ms or so).
In theory though you're right. If I write an application and block the tick, then setTimeouts will be delayed. So to answer you're question, who can assure setTimeouts execute on time? You, by writing non-blocking code, can control the degree of accuracy up to almost any reasonable degree of accuracy.
As long as javascript is "single-threaded" in terms of code execution (excluding web-workers and the like), that will always happen. The single-threaded nature is a huge simplification in most cases, but requires the non-blocking idiom to be successful.
Try this code out either in your browser or in node, and you'll see that there is no guarantee of accuracy, on the contrary, the setTimeout will be very late:
var start = Date.now();
// expecting something close to 500
setTimeout(function(){ console.log(Date.now() - start); }, 500);
// fiddle with the number of iterations depending on how quick your machine is
for(var i=0; i<5000000; ++i){}
Unless the interpreter optimises the loop away (which it doesn't on chrome), you'll get something in the thousands. Remove the loop and you'll see it's 500 on the nose...
Checking the Options Over Write Database worked for me :)
Open up terminal first and then go to directory of web server
cd /Library/WebServer/Documents
and then type this and what you will do is you will give read
and write
permission
sudo chmod -R o+w /Library/WebServer/Documents
This will surely work!
$this
variable in PHP is to try it against the interpreter in various contexts:print isset($this); //true, $this exists
print gettype($this); //Object, $this is an object
print is_array($this); //false, $this isn't an array
print get_object_vars($this); //true, $this's variables are an array
print is_object($this); //true, $this is still an object
print get_class($this); //YourProject\YourFile\YourClass
print get_parent_class($this); //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this); //delicious data dump of $this
print $this->yourvariable //access $this variable with ->
So the $this
pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:
Class Dog{
public $my_member_variable; //member variable
function normal_method_inside_Dog() { //member method
//Assign data to member variable from inside the member method
$this->my_member_variable = "whatever";
//Get data from member variable from inside the member method.
print $this->my_member_variable;
}
}
$this
is reference to a PHP Object
that was created by the interpreter for you, that contains an array of variables.
If you call $this
inside a normal method in a normal class, $this
returns the Object (the class) to which that method belongs.
It's possible for $this
to be undefined if the context has no parent Object.
php.net has a big page talking about PHP object oriented programming and how $this
behaves depending on context.
https://www.php.net/manual/en/language.oop5.basic.php
Run
gradlew -q app:dependencies
It will remove what is wrong.
So when sending the message to telegram you use:
$token = <Enter Your Token Here>
$url = "https://api.telegram.org/bot".$token;
$chat_id = <The Chat Id Goes Here>;
$test = <Message goes Here>;
//sending Message normally without styling
$response = file_get_content($url."\sendMessage?chat_id=$chat_id&text=$text");
If our message has html tags in it we add "parse_mode" so that our url becomes:
$response = file_get_content($url."\sendMessage?chat_id=$chat_id&text=$text&parse_mode=html")
parse mode can be "HTML" or "markdown"
You can convert CSV string to Array with this function.
function csv2array(
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
) {
$arr = array_map(
function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
if ($FirstLineTitle && !$FirstLine) {
$FirstLine = explode( $delimiter, $result[0] );
}
$lineResult = array_map(
function ( $field ) {
return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
},
$trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
);
return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
},
($result = preg_split(
$skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
preg_replace_callback(
'/"(.*?)"/s',
function ( $field ) {
return urlencode( utf8_encode( $field[1] ) );
},
$enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
)
))
);
return $FirstLineTitle ? array_splice($arr, 1) : $arr;
}
You need to install the Chrome driver. You can install this package using NuGet as shown below:
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)
Another option is to create a shortcut, returning a list:
from functools import reduce
_compose = lambda f, g: lambda *args: f(g(*args))
lmap = reduce(_compose, (list, map))
>>> lmap(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
I have had the same issue that I solved this way:
Instead of adding the meta to the current page header that caused the same error as you had:
Page.Header.Controls.Add(meta);
I used this instead:
Master.FindControl("YourHeadContentPlaceHolder").Controls.Add(meta);
and it works like a charm.
Here´s an example using this Technic. In this specifik example the code is making a call to Firebase using a mock MyCompletionListener
that is an interface masked as an abstract class, an interface with a constructor
private interface Listener {
void onComplete(databaseError, databaseReference);
}
public abstract class MyCompletionListener implements Listener{
String id;
String name;
public MyCompletionListener(String id, String name) {
this.id = id;
this.name = name;
}
}
private void removeUserPresenceOnCurrentItem() {
mFirebase.removeValue(child("some_key"), new MyCompletionListener(UUID.randomUUID().toString(), "removeUserPresenceOnCurrentItem") {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
}
});
}
}
@Override
public void removeValue(DatabaseReference ref, final MyCompletionListener var1) {
CompletionListener cListener = new CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (var1 != null){
System.out.println("Im back and my id is: " var1.is + " and my name is: " var1.name);
var1.onComplete(databaseError, databaseReference);
}
}
};
ref.removeValue(cListener);
}
I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:
upload_max_filesize = "20M"
post_max_size = "25M"
This is the recommended solution for Heroku.
As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:
use Illuminate\Support\Facades\Http;
$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');
You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response
instance returned.
$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
Please note that you will, of course, need to install Guzzle like so:
composer require guzzlehttp/guzzle
There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client
This is definitely now the easiest way to make external API calls within Laravel.
PYTHON 3
import urllib.request
wp = urllib.request.urlopen("http://example.com")
pw = wp.read()
print(pw)
PYTHON 2
import urllib
import sys
wp = urllib.urlopen("http://example.com")
for line in wp:
sys.stdout.write(line)
While I have tested both the Codes in respective versions.
In Opera 12 when you bind using the plain JavaScript, 'oTransitionEnd' will work:
document.addEventListener("oTransitionEnd", function(){
alert("Transition Ended");
});
however if you bind through jQuery, you need to use 'otransitionend'
$(document).bind("otransitionend", function(){
alert("Transition Ended");
});
In case you are using Modernizr or bootstrap-transition.js you can simply do a change:
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
You can find some info here as well http://www.ianlunn.co.uk/blog/articles/opera-12-otransitionend-bugs-and-workarounds/
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:
And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.
If you used for your GIT the password authentication before, but now are using SSH authentication, you need to switch remote URLs from HTTPS to SSH:
git remote set-url origin [email protected]:USERNAME/REPOSITORY.git
POSIX sh doesn't understand ==
for string equality, as that is a bash-ism. Use =
instead.
The other people saying that brackets aren't supported by sh are wrong, btw.
You have several options
integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)
since you didn't mention it bit if you are on SQL Server 2008 you can use the time datatype otherwise use minutes since midnight
List the packages by:
adb shell su 0 pm list packages
Review which package you want to uninstall and copy the package name from there. For example:
com.android.calculator2
Lastly type in:
adb uninstall com.android.calculator2
and you are done.
Although this has been answer https://stackoverflow.com/a/28375912/5413283, and regarding padding it is not mentioned in the original answer but here https://stackoverflow.com/a/33697157/5413283.
i am just adding here for visual presentation and a cleaner code.
Create a new parent div and add the bootstrap collapse. Remove the classes from the textarea
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // bootstrap class on parent -->
If you want to have spaces around, wrap textarea
with padding. Do not add margin
, it has the same issue.
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<div class="py-4"> <!-- padding for textarea -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // padding for textarea -->
</div> <!-- // bootstrap class on parent -->
Same as bootstrap 4. Wrap the textare
with collapse
class.
<div class="collapse" id="collapseOne"> <!-- bootstrap class on parent -->
<textarea class="form-control" rows="4"></textarea>
</div> <!-- // bootstrap class on parent -->
And for padding
Bootstrap 3 does not have p-* classes like Bootstrap 4 . So you need to create your own. Do not use padding
it will not work, use margin
.
#collapseOne textarea {
margin: 10px 0 10px 0;
}
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
According to Android Developer site
I think you cant(as far as i know) hide navigation bar permanently..
However you can do one trick. Its a trick mind you.
Just when the navigation bar
shows up when user touches the screen. Immediately hide it again.
Its fun.
Check this.
void setNavVisibility(boolean visible) {
int newVis = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_LAYOUT_STABLE;
if (!visible) {
newVis |= SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_FULLSCREEN
| SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// If we are now visible, schedule a timer for us to go invisible.
if (visible) {
Handler h = getHandler();
if (h != null) {
h.removeCallbacks(mNavHider);
if (!mMenusOpen && !mPaused) {
// If the menus are open or play is paused, we will not auto-hide.
h.postDelayed(mNavHider, 1500);
}
}
}
// Set the new desired visibility.
setSystemUiVisibility(newVis);
mTitleView.setVisibility(visible ? VISIBLE : INVISIBLE);
mPlayButton.setVisibility(visible ? VISIBLE : INVISIBLE);
mSeekView.setVisibility(visible ? VISIBLE : INVISIBLE);
}
See this for more information on this ..
"Resource temporarily unavailable"
is the error message corresponding to EAGAIN
, which means that the operation would have blocked but nonblocking operation was requested. For send()
, that could be due to any of:
fcntl()
; orMSG_DONTWAIT
flag to send()
; orSO_SNDTIMEO
socket option.You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "[email protected]";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("[email protected]", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
Based on the stacktrace, an intuit class com.intuit.ipp.aggcat.util.SAML2AssertionGenerator needs a saml jar on the classpath.
A saml class org.opensaml.xml.XMLConfigurator needs on it's turn log4j, which is inside the WAR but cannot find it.
One explanation for this is that the class XMLConfigurator that needs log4j was found not inside the WAR but on a downstream classloader. could a saml jar be missing from the WAR?
The class XMLConfigurator that needs log4j cannot find it at the level of the classloader that loaded it, and the log4j version on the WAR is not visible on that particular classloader.
In order to troubleshoot this, a way is to add this before the oauth call:
System.out.println("all versions of log4j Logger: " + getClass().getClassLoader().getResources("org/apache/log4j/Logger.class") );
System.out.println("all versions of XMLConfigurator: " + getClass().getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassLoader().getResources("org/opensaml/xml/XMLConfigurator.class") );
System.out.println("all versions of log4j visible from the classloader of the OAuthAuthorizer class: " + OAuthAuthorizer.class.getClassloader().getResources("org/apache/log4j/Logger.class") );
Also if you are using Java 7, have a look at jHades, it's a tool I made to help troubleshooting these type of problems.
In order to see what is going on, could you post the results of the classpath queries above, for which container is this happening, tomcat, jetty? It would be better to put the full stacktrace with all the caused by's in pastebin, just in case.
Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.
Restart the service to let the changes take effect.
With Swift 3 and Swift 4, String
has a method called data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
has the following declaration:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Returns a Data containing a representation of the String encoded using a given encoding.
With Swift 4, String
's data(using:allowLossyConversion:)
can be used in conjunction with JSONDecoder
's decode(_:from:)
in order to deserialize a JSON string into a dictionary.
Furthermore, with Swift 3 and Swift 4, String
's data(using:allowLossyConversion:)
can also be used in conjunction with JSONSerialization
's json?Object(with:?options:?)
in order to deserialize a JSON string into a dictionary.
With Swift 4, JSONDecoder
has a method called decode(_:from:)
. decode(_:from:)
has the following declaration:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodes a top-level value of the given type from the given JSON representation.
The Playground code below shows how to use data(using:allowLossyConversion:)
and decode(_:from:)
in order to get a Dictionary
from a JSON formatted String
:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
With Swift 3 and Swift 4, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
The Playground code below shows how to use data(using:allowLossyConversion:)
and json?Object(with:?options:?)
in order to get a Dictionary
from a JSON formatted String
:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}
The accepted answer is very useful and quite comprehensive. However, the OP states
I would like to see a simple example to write a callback function.
So here you go, from C++11 you have std::function
so there is no need for function pointers and similar stuff:
#include <functional>
#include <string>
#include <iostream>
void print_hashes(std::function<int (const std::string&)> hash_calculator) {
std::string strings_to_hash[] = {"you", "saved", "my", "day"};
for(auto s : strings_to_hash)
std::cout << s << ":" << hash_calculator(s) << std::endl;
}
int main() {
print_hashes( [](const std::string& str) { /** lambda expression */
int result = 0;
for (int i = 0; i < str.length(); i++)
result += pow(31, i) * str.at(i);
return result;
});
return 0;
}
This example is by the way somehow real, because you wish to call function print_hashes
with different implementations of hash functions, for this purpose I provided a simple one. It receives a string, returns an int (a hash value of the provided string), and all that you need to remember from the syntax part is std::function<int (const std::string&)>
which describes such function as an input argument of the function that will invoke it.
If you want to migrate the repo including the wiki and all issues and milestones, you can use node-gitlab-2-github and GitLab to GitHub migration
This worked perfect for me.
Double legacyRow = row.getCell(col).getNumericCellValue();
String legacyRowStr = legacyRow.toString();
if(legacyRowStr.contains(".0")){
legacyRowStr = legacyRowStr.substring(0, legacyRowStr.length()-2);
}
I use the following (coffeescript):
$ ->
# disable chrome's html5 datepicker
for datefield in $('input[data-datepicker=true]')
$(datefield).attr('type', 'text')
# enable custom datepicker
$('input[data-datepicker=true]').datepicker()
which gets converted to plain javascript:
(function() {
$(function() {
var datefield, _i, _len, _ref;
_ref = $('input[data-datepicker=true]');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
datefield = _ref[_i];
$(datefield).attr('type', 'text');
}
return $('input[data-datepicker=true]').datepicker();
});
}).call(this);
Behavior differences
Some differences on Bash 4.3.11:
POSIX vs Bash extension:
[
is POSIX[[
is a Bash extension inspired from Korn shellregular command vs magic
[
is just a regular command with a weird name.
]
is just the last argument of [
.
Ubuntu 16.04 actually has an executable for it at /usr/bin/[
provided by coreutils, but the bash built-in version takes precedence.
Nothing is altered in the way that Bash parses the command.
In particular, <
is redirection, &&
and ||
concatenate multiple commands, ( )
generates subshells unless escaped by \
, and word expansion happens as usual.
[[ X ]]
is a single construct that makes X
be parsed magically. <
, &&
, ||
and ()
are treated specially, and word splitting rules are different.
There are also further differences like =
and =~
.
In Bashese: [
is a built-in command, and [[
is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword
<
[[ a < b ]]
: lexicographical comparison[ a \< b ]
: Same as above. \
required or else does redirection like for any other command. Bash extension.expr x"$x" \< x"$y" > /dev/null
or [ "$(expr x"$x" \< x"$y")" = 1 ]
: POSIX equivalents, see: How to test strings for lexicographic less than or equal in Bash?&&
and ||
[[ a = a && b = b ]]
: true, logical and[ a = a && b = b ]
: syntax error, &&
parsed as an AND command separator cmd1 && cmd2
[ a = a ] && [ b = b ]
: POSIX reliable equivalent[ a = a -a b = b ]
: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a
or b
like !
or (
which would be interpreted as logical operations(
[[ (a = a || a = b) && a = b ]]
: false. Without ( )
, would be true because [[ && ]]
has greater precedence than [[ || ]]
[ ( a = a ) ]
: syntax error, ()
is interpreted as a subshell[ \( a = a -o a = b \) -a a = b ]
: equivalent, but ()
, -a
, and -o
are deprecated by POSIX. Without \( \)
would be true because -a
has greater precedence than -o
{ [ a = a ] || [ a = b ]; } && [ a = b ]
non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ]
because the ||
and &&
shell operators have equal precedence unlike [[ || ]]
and [[ && ]]
and -o
, -a
and [
word splitting and filename generation upon expansions (split+glob)
x='a b'; [[ $x = 'a b' ]]
: true, quotes not neededx='a b'; [ $x = 'a b' ]
: syntax error, expands to [ a b = 'a b' ]
x='*'; [ $x = 'a b' ]
: syntax error if there's more than one file in the current directory.x='a b'; [ "$x" = 'a b' ]
: POSIX equivalent=
[[ ab = a? ]]
: true, because it does pattern matching (* ? [
are magic). Does not glob expand to files in current directory.[ ab = a? ]
: a?
glob expands. So may be true or false depending on the files in the current directory.[ ab = a\? ]
: false, not glob expansion=
and ==
are the same in both [
and [[
, but ==
is a Bash extension.case ab in (a?) echo match; esac
: POSIX equivalent[[ ab =~ 'ab?' ]]
: false, loses magic with ''
in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1
)[[ ab? =~ 'ab?' ]]
: true=~
[[ ab =~ ab? ]]
: true, POSIX extended regular expression match, ?
does not glob expand[ a =~ a ]
: syntax error. No bash equivalent.printf 'ab\n' | grep -Eq 'ab?'
: POSIX equivalent (single line data only)awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?'
: POSIX equivalent.Recommendation: always use []
There are POSIX equivalents for every [[ ]]
construct I've seen.
If you use [[ ]]
you:
[
is just a regular command with a weird name, no special semantics are involved.Thanks to Stéphane Chazelas for important corrections and additions.
Java provides the static method System.currentTimeMillis()
. And that's returning a long value, so it's a good reference. A lot of other classes accept a 'timeInMillis' parameter which is long as well.
And a lot of people find it easier to use the Joda Time library to do calculations on dates and times.
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.
Basically in HashMap, user has to provide both Key and Value, whereas in HashSet you provide only Value, the Key is derived automatically from Value by using hash function. So after having both Key and Value, HashSet can be stored as HashMap internally.
Agile is a general philosophy regarding software production, Scrum is an implementation of that philosophy pertaining specifically to project management.
After reading all of the solutions, I looked for a component and I found one which does exactly what the original question asked for: scrolling to anchor links. https://www.npmjs.com/package/ng2-scroll-to
When you install it, you use syntax like:
// app.awesome.component.ts
@Component({
...
template: `...
<a scrollTo href="#main-section">Scroll to main section</a>
<button scrollTo scrollTargetSelector="#test-section">Scroll to test section</a>
<button scrollTo scrollableElementSelector="#container" scrollYTarget="0">Go top</a>
<!-- Further content here -->
<div id="container">
<section id="main-section">Bla bla bla</section>
<section id="test-section">Bla bla bla</section>
<div>
...`,
})
export class AwesomeComponent {
}
It has worked really well for me.
On the git stash manpage you can read (in the "Discussion" section, just after "Options" description) that:
A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created.
So you can treat stash (e.g. stash@{0}
is first / topmost stash) as a merge commit, and use:
$ git diff stash@{0}^1 stash@{0} -- <filename>
Explanation: stash@{0}^1
means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away. We use this form of "git diff" (with two commits) because stash@{0}
/ refs/stash
is a merge commit, and we have to tell git which parent we want to diff against. More cryptic:
$ git diff stash@{0}^! -- <filename>
should also work (see git rev-parse manpage for explanation of rev^!
syntax, in "Specifying ranges" section).
Likewise, you can use git checkout to check a single file out of the stash:
$ git checkout stash@{0} -- <filename>
or to save it under another filename:
$ git show stash@{0}:<full filename> > <newfile>
or
$ git show stash@{0}:./<relative filename> > <newfile>
(note that here <full filename> is full pathname of a file relative to top directory of a project (think: relative to stash@{0}
)).
You might need to protect stash@{0}
from shell expansion, i.e. use "stash@{0}"
or 'stash@{0}'
.
I agree with Beytan Kurt.
I had 503 thrown for both the Central Admin site as well as the SharePoint landing page. In both cases the Passwords were expired.
After resetting the password in the AD, and refreshing the Identity, CA worked but the SharePoint landing page threw a 500 error.
It turned out that the .Net Framework Version was set to V4.0. I changed it to V2.0 and it worked.
Remember after each change you need to recycle the appropriate app pool.
Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)
SQL*Plus
and login as SYSTEM
. You should know what password you’ve used during the installation of Oracle DB XE.alter system set processes=150 scope=spfile;
in SQL*PlusFrom here:
Using CSS3 you don't need to make your own image with the transparency.
Just have a div with the following
position:absolute;
left:0;
background: rgba(255,255,255,.5);
The last parameter in background (.5) is the level of transparency (a higher number is more opaque).
To call the function on click of some html element (control).
$('#controlID').click(myFunction);
You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready
$(document).ready(function(){
$('#controlID').click(myFunction);
});
You can use anonymous function to bind the event to the html element.
$(document).ready(function(){
$('#controlID').click(function(){
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
});
});
If you want to bind click with many elements you can use class selector
$('.someclass').click(myFunction);
Edit based on comments by OP, If you want to call function under some condition
You can use if for conditional execution, for example,
if(a == 3)
myFunction();
Something like this...
var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;
See also LINQ query on a DataTable
I setup my git
to autorebase on a git checkout
# in my ~/.gitconfig file
[branch]
autosetupmerge = always
autosetuprebase = always
Otherwise, it automatically merges when you switch between branches, which I think is the worst possible choice as the default.
However, this has a side effect, when I switch to a branch and then git cherry-pick <commit-id>
I end up in this weird state every single time it has a conflict.
I actually have to abort the rebase
, but first I fix the conflict, git add /path/to/file
the file (another very strange way to resolve the conflict in this case?!), then do a git commit -i /path/to/file
. Now I can abort the rebase
:
git checkout <other-branch>
git cherry-pick <commit-id>
...edit-conflict(s)...
git add path/to/file
git commit -i path/to/file
git rebase --abort
git commit .
git push --force origin <other-branch>
The second git commit .
seems to come from the abort. I'll fix my answer if I find out that I should abort the rebase
sooner.
The --force
on the push is required if you skip other commits and both branches are not smooth (both are missing commits from the other).
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
Had similar message
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. More than one file was found with OS independent path 'constant-values.html'
To resolve it, I had to enable packages view(1) in Android Studio, then browse through the tree to libraries, and locate the duplicates(2)
Then, ctrl+alt+f12 (or RMB menu)(3) - and found libraries which caused the issue. Made list of files inside those libs which caused the issues, and wrote them to app's build.gradle file inside android section. Other option is to deal with the library, containing duplicate files
packagingOptions {
exclude 'allclasses-frame.html'
exclude 'allclasses-noframe.html'
<..>
If you're not opposed to implicit type casting I'll offer this an alternative solution. Is it more readable with better formatting? You be the judge.
DECLARE @StartDate datetime = '10/01/2012 08:40:18.000'
,@EndDate datetime = '10/04/2012 09:52:48.000'
SELECT
STR(ss/3600, 5) + ':' + RIGHT('0' + LTRIM(ss%3600/60), 2) + ':' + RIGHT('0' + LTRIM(ss%60), 2) AS [hh:mm:ss]
FROM (VALUES(DATEDIFF(s, @StartDate, @EndDate))) seconds (ss)
If you append this to user.js
:
exports.User = User;
then in server.js
you can do:
var userFile = require('./user.js');
var User = userFile.User;
http://nodejs.org/docs/v0.4.10/api/globals.html#require
Another way is:
global.User = User;
then this would be enough in server.js
:
require('./user.js');
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/logonFormButtons"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal">
<Button
android:id="@+id/logonFormBTLogon"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/logon"
android:layout_weight="0.5" />
<Button
android:id="@+id/logonFormBTCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:layout_weight="0.5" />
</LinearLayout>
Use files.exclude:
workspace settings
tabAdd this code to the settings.json
file displayed on the right side:
// Place your settings in this file to overwrite default and user settings.
{
"settings": {
"files.exclude": {
"**/.git": true, // this is a default value
"**/.DS_Store": true, // this is a default value
"**/node_modules": true, // this excludes all folders
// named "node_modules" from
// the explore tree
// alternative version
"node_modules": true // this excludes the folder
// only from the root of
// your workspace
}
}
}
If you chose File -> Preferences -> User Settings then you configure the exclude folders globally for your current user.
Just a few points for completeness:
this answer is discussing only integer representations. There may be other answers for floating point;
the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number.
When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented.
when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
For example css files are in folder named CSS
and html files are in folder HTML
, and both these are in folder named XYZ
means we refer css files in html as
<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />
Here ..
moves up to HTML
and .
refers to the current directory XYZ
---by this logic you would just reference as:
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
I have created a data frame in a for loop with the help of a temporary empty data frame. Because for every iteration of for loop, a new data frame will be created thereby overwriting the contents of previous iteration.
Hence I need to move the contents of the data frame to the empty data frame that was created already. It's as simple as that. We just need to use .append function as shown below :
temp_df = pd.DataFrame() #Temporary empty dataframe
for sent in Sentences:
New_df = pd.DataFrame({'words': sent.words}) #Creates a new dataframe and contains tokenized words of input sentences
temp_df = temp_df.append(New_df, ignore_index=True) #Moving the contents of newly created dataframe to the temporary dataframe
Outside the for loop, you can copy the contents of the temporary data frame into the master data frame and then delete the temporary data frame if you don't need it
I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp
class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.
Depending on your situation an exact requirements, there are two natural replacements for Timestamp
:
Instant
is a point on the time-line. For most purposes I would consider it safest to use this. An Instant
is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.LocalDateTime
is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant
or a LocalDateTime
into your database column of datatype timestamp
. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time
or JSR-310.
It’s easiest to convert your string to LocalDateTime
, so let’s take that first:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String text = "2011-10-02 18:48:05.123";
LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
System.out.println(dateTime);
This prints
2011-10-02T18:48:05.123
If your string was in yyyy-MM-dd format, instead do:
String text = "2009-10-20";
LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
System.out.println(dateTime);
This prints
2009-10-20T00:00
Or still better, take the output from LocalDate.parse()
and store it into a database column of datatype date
.
In both cases the procedure for converting from a LocalDateTime
to an Instant
is:
Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(ts);
I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:
Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.
To append a name/value name/value pair to a Headers object (headers), run these steps:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headers’s guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
To fill a Headers object headers with a given object object, run these steps:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
The delete(name) method steps are:
- If name is not a name, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
The get(name) method steps are:
- If name is not a name, then throw a TypeError.
- Return the result of getting name from this’s header list.
The has(name) method steps are:
- If name is not a name, then throw a TypeError.
The set(name, value) method steps are:
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
To extract a body and a
Content-Type
value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.
In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method isGET
orHEAD
, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...
The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.
The clone() method steps are:
- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.
In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.
#include <stdio.h>
int main() {
int c;
while((c = getchar()) != EOF) {
putchar(c);
}
printf("%d at EOF\n", c);
}
modified the above code to give more clarity on EOF, Press Ctrl+d and putchar is used to print the char avoid using printf within while loop.
List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;
The implicit conversion failes because List<>
implements IList
, not viceversa. So you can say IList<T> foo = new List<T>()
, but not List<T> foo = (some IList-returning method or property)
.
I was designing a GUI in SceneBuilder, trying to make the main container adapt to whatever the window size is. It should always be 100% wide.
This is where you can set these values in SceneBuilder:
Toggling the dotted/red lines will actually just add/remove the attributes that Korki posted in his solution (AnchorPane.topAnchor etc.).
As wikipedia states algorithm for the leap year should be
(((year%4 == 0) && (year%100 !=0)) || (year%400==0))
Here is a sample program how to check for leap year.
It's almost always advisable to not use scriptlets in your JSP. They're considered bad form. Instead, try using JSTL (JSP Standard Tag Library) combined with EL (Expression Language) to run the conditional logic you're trying to do. As an added benefit, JSTL also includes other important features like looping.
Instead of:
<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
out.print("I see! You don't have a name.. well.. Hello no name");
}
else {%>
<%@ include file="response.jsp" %>
<% } %>
Use:
<c:choose>
<c:when test="${empty user}">
I see! You don't have a name.. well.. Hello no name
</c:when>
<c:otherwise>
<%@ include file="response.jsp" %>
</c:otherwise>
</c:choose>
Also, unless you plan on using response.jsp somewhere else in your code, it might be easier to just include the html in your otherwise statement:
<c:otherwise>
<h1>Hello</h1>
${user}
</c:otherwise>
Also of note. To use the core tag, you must import it as follows:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
You want to make it so the user will receive a message when the user submits a username. The easiest way to do this is to not print a message at all when the "user" param is null
. You can do some validation to give an error message when the user submits null
. This is a more standard approach to your problem. To accomplish this:
In scriptlet:
<% String user = request.getParameter("user");
if( user != null && user.length() > 0 ) {
<%@ include file="response.jsp" %>
}
%>
In jstl:
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>
The other answers may have been useful years ago, but they are now out of date.
Given that a project has a tsconfig file, run this command...
tsc --watch
... to watch for changed files and compile as needed. The documentation explains:
Run the compiler in watch mode. Watch input files and trigger recompilation on changes. The implementation of watching files and directories can be configured using environment variable. See configuring watch for more details.
To answer the original question, recursive directory watching is possible even on platforms that don't have native support, as explained by the Configuring Watch docs:
The watching of directory on platforms that don’t support recursive directory watching natively in node, is supported through recursively creating directory watcher for the child directories using different options selected by TSC_WATCHDIRECTORY
Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):
string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
(new System.IO.StreamReader(
System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
.Entries.Where(x => x.Name.Equals(targetFileName,
StringComparison.InvariantCulture))
.FirstOrDefault()
.Open(), Encoding.UTF8)
.ReadToEnd())
.ToArray());
This is a slight modification to Edens answer - which for me in chrome didn't catch the error. Although you'll still get an error in the console: "Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'sameorigin'." At least this will catch the error message and then you can deal with it.
<iframe id="myframe" src="https://google.ca"></iframe>
<script>
myframe.onload = function(){
var that = document.getElementById('myframe');
try{
(that.contentWindow||that.contentDocument).location.href;
}
catch(err){
//err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
console.log('err:'+err);
}
}
</script>
I came across this solution but this does not really fit my need. So I digged a bit in the d3 source code. I personally would recommend to do it like d3.scale does.
So here you scale the domain to the range. The advantage is that you can flip signs to your target range. This is useful since the y axis on a computer screen goes top down so large values have a small y.
public class Rescale {
private final double range0,range1,domain0,domain1;
public Rescale(double domain0, double domain1, double range0, double range1) {
this.range0 = range0;
this.range1 = range1;
this.domain0 = domain0;
this.domain1 = domain1;
}
private double interpolate(double x) {
return range0 * (1 - x) + range1 * x;
}
private double uninterpolate(double x) {
double b = (domain1 - domain0) != 0 ? domain1 - domain0 : 1 / domain1;
return (x - domain0) / b;
}
public double rescale(double x) {
return interpolate(uninterpolate(x));
}
}
And here is the test where you can see what I mean
public class RescaleTest {
@Test
public void testRescale() {
Rescale r;
r = new Rescale(5,7,0,1);
Assert.assertTrue(r.rescale(5) == 0);
Assert.assertTrue(r.rescale(6) == 0.5);
Assert.assertTrue(r.rescale(7) == 1);
r = new Rescale(5,7,1,0);
Assert.assertTrue(r.rescale(5) == 1);
Assert.assertTrue(r.rescale(6) == 0.5);
Assert.assertTrue(r.rescale(7) == 0);
r = new Rescale(-3,3,0,1);
Assert.assertTrue(r.rescale(-3) == 0);
Assert.assertTrue(r.rescale(0) == 0.5);
Assert.assertTrue(r.rescale(3) == 1);
r = new Rescale(-3,3,-1,1);
Assert.assertTrue(r.rescale(-3) == -1);
Assert.assertTrue(r.rescale(0) == 0);
Assert.assertTrue(r.rescale(3) == 1);
}
}
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
For Mac users, see this answer:
Essentially, your OS may be blocking Intel from running what it needs to get your AVD going. Go into System Preferences -> Security and Privacy
and you should see an option there to enable the Intel processes. Restart Android Studio and you should be good to go.
You can position both the image and the text with position:absolute
or position:relative
. Then the z-index property will work. E.g.
#sometext {
position:absolute;
z-index:1;
}
image.center {
position:absolute;
z-index:0;
}
Use whatever method you like to center it.
Another option/hack is to make the image the background, either on the whole page or just within the text box.
String LastId = "id";
database.execSQL("ALTER TABLE " + PhraseContract.TABLE_NAME + " RENAME TO " + PhraseContract.TABLE_NAME + "old");
database.execSQL("CREATE TABLE " + PhraseContract.TABLE_NAME
+"("
+ PhraseContract.COLUMN_ID + " INTEGER PRIMARY KEY,"
+ PhraseContract.COLUMN_PHRASE + " text ,"
+ PhraseContract.COLUMN_ORDER + " text ,"
+ PhraseContract.COLUMN_FROM_A_LANG + " text"
+")"
);
database.execSQL("INSERT INTO " +
PhraseContract.TABLE_NAME + "("+ PhraseContract.COLUMN_ID +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +")" +
" SELECT " + LastId +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +
" FROM " + PhraseContract.TABLE_NAME + "old");
database.execSQL("DROP TABLE " + PhraseContract.TABLE_NAME + "old");
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
Html Code:
<select id="multiple" multiple="multiple" name="multiple">
<option value=""> -- Select -- </option>
<option value="1">Opt1</option>
<option value="2">Opt2</option>
<option value="3">Opt3</option>
<option value="4">Opt4</option>
<option value="5">Opt5</option>
</select>
JQuery Code:
$('#multiple :selected').each(function(i, sel){
alert( $(sel).val() );
});
Hope it works
No. Java doesn't support default parameters like C++. You need to define a different method:
public int doSomething()
{
return doSomething(value1, value2);
}
Let's not forget the most important thing to learn out of a question like this: SQL Injection.
Use PDO and prepared statements.
Click here for a tutorial on PDO.
Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.
You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for
(à la C language):
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
if (arr[i] === 'a') {_x000D_
arr.splice(i, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
If you really think about it, a forEach
is just syntactic sugar for a for
loop... So if it's not helping you, just please stop breaking your head against it.
Same thing for tooltips:
For me following solution works because it does not add event listeners on every 'mouseenter' and it is possible to hover back on the tooltip element which keeps the tooltip alive.
$ ->
$('.element').tooltip({
html: true,
trigger: 'manual'
}).
on 'mouseenter', ->
clearTimeout window.tooltipTimeout
$(this).tooltip('show') unless $('.tooltip:visible').length > 0
.
on 'mouseleave', ->
_this = this
window.tooltipTimeout = setTimeout ->
$(_this).tooltip('hide')
, 100
$(document).on 'mouseenter', '.tooltip', ->
clearTimeout window.tooltipTimeout
$(document).on 'mouseleave', '.tooltip', ->
trigger = $($(this).siblings('.element')[0])
window.tooltipTimeout = setTimeout ->
trigger.tooltip('hide')
, 100
Short, clear and clean: use len(df)
len()
is your friend, and it can be used for row counts as len(df)
.
Alternatively, you can access all rows by df.index
and all columns by df.columns
, and as you can use the len(anyList)
for getting the count of list, use
len(df.index)
for getting the number of rows, and len(df.columns)
for the column count.
Or, you can use df.shape
which returns the number of rows and columns together. If you want to access the number of rows, only use df.shape[0]
. For the number of columns, only use: df.shape[1]
.
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931
>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array(),
array('id' => 'ASC')
);
Its complete installation nightmare, but I'll give one more hope you can avoid building opencv from source:
pip install opencv-contrib-python
I had the same issue with wrong AVD settings. Probably, "Target Android 6.0" was wrong choice.
Next settings were changed to fix ":app:installDebug FAILED" issue: System Image: Marshmallow , API 23, ABI x86, Target Google API.
see the detail information about this here: RN Android Setup
Connect to DB using base user:
mysql -u base_user -pbase_user_pass
And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.
Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {}
syntax is now equivalent to namespace App {}
. As a result, the following works:
// test.ts
export namespace App {
export class SomeClass {
getName(): string {
return 'name';
}
}
}
// main.ts
import { App } from './test';
var a = new App.SomeClass();
Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:
// test.ts
export class SomeClass {
getName(): string {
return 'name';
}
}
// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();
Here is what I use. All of these are in the Central and have sources.
For Tomcat 7 (Java 7, Servlet 3.0)
Note - Servlet, JSP and EL APIs are provided in Tomcat. Only JSTL (if used) needs to be bundled with the web app.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
For Tomcat 8 (Java 8, Servlet 3.1)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I had such an error in this case:
java -cp lib.jar com.mypackage.Main
It works with ;
for Windows and :
for Unix:
java -cp lib.jar; com.mypackage.Main
You can try sth like this, if you have month_name which is string datetype.After converting, you can feel free to order by Month.
For example, your table like this:
month
Dec
Jan
Feb
Nov
Mar
.
.
.
My syntax is:
Month(cast(month+'1 2016' as datetime))
Feedback Guys, first create database example live; before execute sql file below.
sqlcmd -U SA -P yourPassword -S YourHost -d live -i live.sql
WAMPServer is designed to be a single seat developers tool. Apache is therefore configure by default to only allow access from the PC running the server i.e. localhost or 127.0.0.1 or ::1
But as it is a full version of Apache all you need is a little knowledge of the server you are using.
The simple ( hammer to crack a nut ) way is to use the 'Put Online' wampmanager menu option.
left click wampmanager icon -> Put Online
This however tells Apache it can accept connections from any ip address in the universe. That's not a problem as long as you have not port forwarded port 80 on your router, or never ever will attempt to in the future.
The more sensible way is to edit the httpd.conf file ( again using the wampmanager menu's ) and change the Apache access security manually.
left click wampmanager icon -> Apache -> httpd.conf
This launches the httpd.conf file in notepad.
Look for this section of this file
<Directory "d:/wamp/www">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
Now assuming your local network subnet uses the address range 192.168.0.?
Add this line after Allow from localhost
Allow from 192.168.0
This will tell Apache that it is allowed to be accessed from any ip address on that subnet. Of course you will need to check that your router is set to use the 192.168.0 range.
This is simply done by entering this command from a command window ipconfig
and looking at the line labeled IPv4 Address.
you then use the first 3 sections of the address you see in there.
For example if yours looked like this:-
IPv4 Address. . . . . . . . . . . : 192.168.2.11
You would use
Allow from 192.168.2
UPDATE for Apache 2.4 users
Of course if you are using Apache 2.4 the syntax for this has changed.
You should replace ALL of this section :
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
With this, using the new Apache 2.4 syntax
Require local
Require ip 192.168.0
You should not just add this into httpd.conf
it must be a replace.
In WAMPServer 3 there is a Virtual Host defined by default. Therefore the above suggestions do not work. You no longer need to make ANY amendments to the httpd.conf
file. You should leave it exactly as you find it.
Instead, leave the server OFFLINE
as this funtionality is defunct and no longer works, which is why the Online/Offline
menu has become optional and turned off by default.
Now you should edit the \wamp\bin\apache\apache{version}\conf\extra\httpd-vhosts.conf
file. In WAMPServer3.0.6 and above there is actually a menu that will open this file in your editor
left click wampmanager -> Apache -> httpd-vhost.conf
just like the one that has always existsed that edits your httpd.conf
file.
It should look like this if you have not added any of your own Virtual Hosts
#
# Virtual Hosts
#
<VirtualHost *:80>
ServerName localhost
DocumentRoot c:/wamp/www
<Directory "c:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Now simply change the Require
parameter to suite your needs EG
If you want to allow access from anywhere replace Require local
with
Require all granted
If you want to be more specific and secure and only allow ip addresses within your subnet add access rights like this to allow any PC in your subnet
Require local
Require ip 192.168.1
Or to be even more specific
Require local
Require ip 192.168.1.100
Require ip 192.168.1.101
DAO and Repository pattern are ways of implementing Data Access Layer (DAL). So, let's start with DAL, first.
Object-oriented applications that access a database, must have some logic to handle database access. In order to keep the code clean and modular, it is recommended that database access logic should be isolated into a separate module. In layered architecture, this module is DAL.
So far, we haven't talked about any particular implementation: only a general principle that putting database access logic in a separate module.
Now, how we can implement this principle? Well, one know way of implementing this, in particular with frameworks like Hibernate, is the DAO pattern.
DAO pattern is a way of generating DAL, where typically, each domain entity has its own DAO. For example, User
and UserDao
, Appointment
and AppointmentDao
, etc. An example of DAO with Hibernate: http://gochev.blogspot.ca/2009/08/hibernate-generic-dao.html.
Then what is Repository pattern? Like DAO, Repository pattern is also a way achieving DAL. The main point in Repository pattern is that, from the client/user perspective, it should look or behave as a collection. What is meant by behaving like a collection is not that it has to be instantiated like Collection collection = new SomeCollection()
. Instead, it means that it should support operations such as add, remove, contains, etc. This is the essence of Repository pattern.
In practice, for example in the case of using Hibernate, Repository pattern is realized with DAO. That is an instance of DAL can be both at the same an instance of DAO pattern and Repository pattern.
Repository pattern is not necessarily something that one builds on top of DAO (as some may suggest). If DAOs are designed with an interface that supports the above-mentioned operations, then it is an instance of Repository pattern. Think about it, If DAOs already provide a collection-like set of operations, then what is the need for an extra layer on top of it?
EXPOSE
is a way of documenting--publish
(or -p
) is a way of mapping a host port to a running container portNotice below that:
EXPOSE
is related to Dockerfiles
( documenting )--publish
is related to docker run ...
( execution / run-time )Exposing and publishing ports
In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.
You expose ports using the
EXPOSE
keyword in the Dockerfile or the--expose
flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.You publish ports using the
--publish
or--publish-all
flag todocker run
. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than30000
) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.from:
Docker container networkingUpdate October 2019: the above piece of text is no longer in the docs but an archived version is here: docs.docker.com/v17.09/engine/userguide/networking/#exposing-and-publishing-ports
Maybe the current documentation is the below:
Published ports
By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the
--publish
or-p
flag. This creates a firewall rule which maps a container port to a port on the Docker host.and can be found here: docs.docker.com/config/containers/container-networking/#published-ports
Also,
EXPOSE
...The
EXPOSE
instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.from: Dockerfile reference
EXPOSE
/ --publish
are not defined:At @Golo Roden's answer it is stated that::
"If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."
Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE
or --publish
, the host
and other containers
of the same network will be able to access a service you may start inside that container.
I've used the following Dockerfile
. Basically, I start with ubuntu and install a tiny web-server:
FROM ubuntu
RUN apt-get update && apt-get install -y mini-httpd
I build
the image as "testexpose" and run
a new container with:
docker run --rm -it testexpose bash
Inside the container, I launch a few instances of mini-httpd
:
root@fb8f7dd1322d:/# mini_httpd -p 80
root@fb8f7dd1322d:/# mini_httpd -p 8080
root@fb8f7dd1322d:/# mini_httpd -p 8090
I am then able to use curl
from the host or other containers to fetch the home page of mini-httpd
.
Very detailed articles on the subject by Ivan Pepelnjak:
After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:
Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));
Please inform me if you have any difficulties implementing this solution so I can help.
Everybody mentioned a constructor call through an initialization list, but nobody said that a parent class's constructor can be called explicitly from the derived member's constructor's body. See the question Calling a constructor of the base class from a subclass' constructor body, for example. The point is that if you use an explicit call to a parent class or super class constructor in the body of a derived class, this is actually just creating an instance of the parent class and it is not invoking the parent class constructor on the derived object. The only way to invoke a parent class or super class constructor on a derived class' object is through the initialization list and not in the derived class constructor body. So maybe it should not be called a "superclass constructor call". I put this answer here because somebody might get confused (as I did).
You could try this:
$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
$hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);
I did some research and found out that byte.Parse is even slower than Convert.ToByte. The fastest conversion I could come up with uses approximately 15 ticks per byte.
public static byte[] StringToByteArrayFastest(string hex) {
if (hex.Length % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
public static int GetHexVal(char hex) {
int val = (int)hex;
//For uppercase A-F letters:
//return val - (val < 58 ? 48 : 55);
//For lowercase a-f letters:
//return val - (val < 58 ? 48 : 87);
//Or the two combined, but a bit slower:
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
// also works on .NET Micro Framework where (in SDK4.3) byte.Parse(string) only permits integer formats.
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
Simply do not provide otherButtonTitles in the constructor.
let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.
int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
//do stuff
if (++processed == 50) break;
}
or use LINQ
foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
//do stuff
}
or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
All my services were running as expected, and I still couldn't connect.
I had to update the TCP/IP properties section in the SQL Server Configuration Manager for my SQL Server Express protocols, and set the IPALL port to 1433 in order to connect to the server as expected.
Just extending Barnards's answer with commons-io. Separate answer because I can not format code in comments.
InputStream is = null;
try {
is = url.openStream ();
byte[] imageBytes = IOUtils.toByteArray(is);
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
Am trying to grep pattern from dozen files .tar.gz but its very slow
tar -ztf file.tar.gz | while read FILENAME do if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null then echo "$FILENAME contains string" fi done
That's actually very easy with ugrep option -z
:
-z, --decompress
Decompress files to search, when compressed. Archives (.cpio,
.pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
.tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
matching pathnames of files in archives are output in braces. If
-g, -O, -M, or -t is specified, searches files within archives
whose name matches globs, matches file name extensions, matches
file signature magic bytes, or matches file types, respectively.
Supported compression formats: gzip (.gz), compress (.Z), zip,
bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).
Which requires just one command to search file.tar.gz
as follows:
ugrep -z "string" file.tar.gz
This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:
$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}: { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello
If you just want the file names, use option -l
(--files-with-matches
) and customize the filename output with option --format="%z%~"
to get rid of the braces:
$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt
Module rewrite_module is built-in in to the server most cases
Use .htaccess
Use the Mod Rewrite Generator at http://www.generateit.net/mod-rewrite/
It's really a matter of opinion. In your example, System.out.println(5)
would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int
is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
scipy.ndimage.interpolation.shift
) is the slowest solution listed in this page.shift4_numba
(defined below) if you want good all-aroundershift4_numba
import numba
@numba.njit
def shift4_numba(arr, num, fill_value=np.nan):
if num >= 0:
return np.concatenate((np.full(num, fill_value), arr[:-num]))
else:
return np.concatenate((arr[-num:], np.full(-num, fill_value)))
shift5_numba
import numba
@numba.njit
def shift5_numba(arr, num, fill_value=np.nan):
result = np.empty_like(arr)
if num > 0:
result[:num] = fill_value
result[num:] = arr[:-num]
elif num < 0:
result[num:] = fill_value
result[:num] = arr[-num:]
else:
result[:] = arr
return result
shift5
shift5_numba
, just remove the @numba.njit decorator.shift_scipy
: scipy.ndimage.interpolation.shift
(scipy 1.4.1) - The option from accepted answer, which is clearly the slowest alternative.shift1
: np.roll
and out[:num] xnp.nan
by IronManMark20 & gzcshift2
: np.roll
and np.put
by IronManMark20shift3
: np.pad
and slice
by gzcshift4
: np.concatenate
and np.full
by chrisaycockshift5
: using two times result[slice] = x
by chrisaycockshift#_numba
: @numba.njit decorated versions of the previous.The shift2
and shift3
contained functions that were not supported by the current numba (0.50.1).
For Nginx (without apache) and PHP 7.2, installing php7.2-xml wasn't enough. Had to install php7.2-simplexml package to get it to work
So the commands for debian/ubuntu, update packages and install both packages
apt update
apt install php7.2-xml php7.2-simplexml
And restart both Nginx and php
systemctl restart nginx php7.2-fpm
Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too. Here's an example of using prepared statements and bound parameters in PHP:
$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
return $dbh->errorInfo();
}
return "success";
In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to '
. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.
I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:
compile 'platforms:android:android-support-v4:23.1.1'
so I changed it to:
compile 'com.android.support:support-v4:23.1.1'
And it started working.
Actually this is possible and the accepted answer only deals with centralising, which is straightforward enough. Also you really don't need to use JavaScript.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute
, but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
For example:
/* Main site body */_x000D_
.wrapper {_x000D_
width: 940px;_x000D_
margin: 0 auto;_x000D_
position: relative; /* Ensure absolute positioned child elements are relative to this*/_x000D_
}_x000D_
_x000D_
/* Absolute positioned wrapper for the element you want to fix position */_x000D_
.fixed-wrapper {_x000D_
width: 220px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */_x000D_
}_x000D_
_x000D_
/* The element you want to fix the position of */_x000D_
.fixed {_x000D_
width: 220px;_x000D_
position: fixed;_x000D_
/* Do not set top / left! */_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="fixed-wrapper">_x000D_
<div class="fixed">_x000D_
Content in here will be fixed position, but 240px to the left of the site body._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Sadly, I was hoping this thread might solve my issue with Android's WebKit rendering box-shadow blur pixels as margins on fixed position elements, but it seems it's a bug.
Anyway, I hope this helps!
I found these instructions on a blog post that indicated this step, which worked for me (Windows 8, 64-bit):
Make sure that in windows features, you have both WCF options under .Net framework are ticked. So go to Control Panel –> Programs and Features –> Turn Windows Features ON/Off –> Features –> Add Features –> .NET Framework X.X Features. Make sure that .Net framework says it is installed, and make sure that the WCF Activation node underneath it is selected (checkbox ticked) and both options under WCF Activation are also checked.These are: * HTTP Activation * Non-HTTP Activation Both options need to be selected (checked box ticked).
Here is a simple javascript
solution which works in most cases:
document.getElementById("selectId").selectedIndex = "0";
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:
C:\path\to\script> php script.php
Or, if you're using the PHP CGI, I think it's:
C:\path\to\script> php-cgi script.php
Plus, you would also set ini_set('max_execution_time', 0);
in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.
check your include file, I had this issue because I accidentally #imported "filename.m" instead of "filename.h", autocorrect (tab) put an "m" not "h".
if you are using ionic framework, go to config.xml file and change the "version" attribute in the "widget" tag. increase the version number. then rebuild, sign and upload ur apk to play store. that fixed my problem.
In 2020 you can listen state changes with useEffect hook like this
export function MyComponent(props) {
const [myState, setMystate] = useState('initialState')
useEffect(() => {
console.log(myState, '- Has changed')
},[myState]) // <-- here put the parameter to listen
}
Before starting, Make sure that USB DEBUGGING IS ENABLED in your phone settings !!!
1) BASIC STEP - Plug in device via USB, then go to device page in Android developers blog. There you can find necessary information regarding adding USB vendor ids. Add your device specific ids, and restart eclipse if needed.
2)If you were able to see the device connected(using command: 'adb devices'
) earlier, but not anymore, then just try restarting ADB. (you can use the commands: 'adb kill-server'
followed by 'adb start-server'
. adb commands need to be executed from platform tools folder in the Android SDK, if you havent exported it).
3)If neither of them works out and you are on windows machine, then check the installed usb drivers are correct. If not install proper drivers Please find more information on how to install/update drivers in http://developer.android.com/tools/extras/oem-usb.html
If this also is not working, try installing Universal ADB windows driver https://plus.google.com/103583939320326217147/posts/BQ5iYJEaaEH
4)You may also try increasing the timeout time Go to preferences-> android->DDMS in eclipse, then try increasing 'ADB connection timeout(ms)' value
Update based on newer answers:
5)Run > Run Configurations > Target. Please make sure, the option "Always prompt to pick device" is enabled.
Special case: Windows 8 and Nexus 10 (from this question: ADB No Devices Found)
Windows 8 wouldn't recognize my Nexus 10 device. Fixed by Setting the transfer mode to Camera (PTP) through the settings dialogue on the device.
Settings > Storage > Menu > USB Computer connection to "Camera (PTP)"
It is the difference between greedy and non-greedy quantifiers.
Consider the input 101000000000100
.
Using 1.*1
, *
is greedy - it will match all the way to the end, and then backtrack until it can match 1
, leaving you with 1010000000001
.
.*?
is non-greedy. *
will match nothing, but then will try to match extra characters until it matches 1
, eventually matching 101
.
All quantifiers have a non-greedy mode: .*?
, .+?
, .{2,6}?
, and even .??
.
In your case, a similar pattern could be <([^>]*)>
- matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than >
in-between <
and >
).
Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.
Hope this helps to those who come searching here.
grep -irnw "filepath" -ve "pattern"
or
grep -ve "pattern" < file
above command will give us the result as -v finds the inverse of the pattern being searched
Even you don't need to measure the length of string. A ! operator can solve everything for you. Remember always: !(empty string) = true !(some string) = false
So you could write:
<input ng-model="somefield">
<span ng-show="!somefield">Sorry, the field is empty!</span>
<span ng-hide="!somefield">Thanks. Successfully validated!</span>
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"