If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
PDB is a debug information file used by Visual Studio. These are system DLLs, which you don't have debug symbols for. Go to Tools->Options->Debugging->Symbols and select checkbox "Microsoft Symbol Servers", Visual Studio will download PDBs automatically. Or you may just ignore these warnings if you don't need to see correct call stack in these modules.
Try change _DEBUG to NDEBUG macro definition in C++ project properties (for Release configuration) Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
This answer is likely wrong wrong the context. I thought VBA now run on the CLR these days, but it does not. In any case, this reply may be useful to someone. Or not.
If you run Office 2010 32-bit mode then it's the same as Office 2007. (The "issue" is Office running in 64-bit mode). It's the bitness of the execution context (VBA/CLR) which is important here and the bitness of the loaded VBA/CLR depends upon the bitness of the host process.
Between 32/64-bit calls, most notable things that go wrong are using long
or int
(constant-sized in CLR) instead of IntPtr
(dynamic sized based on bitness) for "pointer types".
The ShellExecute function has a signature of:
HINSTANCE ShellExecute(
__in_opt HWND hwnd,
__in_opt LPCTSTR lpOperation,
__in LPCTSTR lpFile,
__in_opt LPCTSTR lpParameters,
__in_opt LPCTSTR lpDirectory,
__in INT nShowCmd
);
In this case, it is important HWND is IntPtr
(this is because a HWND is a "HANDLE" which is void*
/"void pointer") and not long
. See pinvoke.net ShellExecute as an example. (While some "solutions" are shady on pinvoke.net, it's a good place to look initially).
Happy coding.
As far as any "new syntax", I have no idea.
Here is a solution using traditional graphics (and Dirk's data):
> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE))
> DF
x y z
1 1 6.628380 c
2 2 6.403279 b
3 3 6.708716 a
4 4 7.011677 c
5 5 6.363794 a
6 6 5.912945 b
7 7 2.996335 a
8 8 5.242786 c
9 9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)
This relies on the fact that DF$z
is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z
as follows:
> c("red","blue","green")[DF$z]
[1] "green" "blue" "red" "green" "red" "blue" "red" "green" "green" "red"
You can add a legend using the legend
function:
legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)
Or on an actual device you can go to Settings -> Mobile Networks -> Preferred network types and chose the slowest available... Of course this is very limited, but for some test- purposes it might be enough.
Coming in PHP 7.1 is the ability to catch multiple types.
So that this:
<?php
try {
/* ... */
} catch (FirstException $ex) {
$this->manageException($ex);
} catch (SecondException $ex) {
$this->manageException($ex);
}
?>
and
<?php
try {
} catch (FirstException | SecondException $ex) {
$this->manageException($ex);
}
?>
are functionally equivalent.
You can call Stored Procedure like this inside Stored Procedure B.
CREATE PROCEDURE spA
@myDate DATETIME
AS
EXEC spB @myDate
RETURN 0
There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.
I can't figure out exactly what's there, yet ...
edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.
A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.
If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od
command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.
The cleanest output, i.e. file names/paths only, comes with
git diff-tree --no-commit-id --name-only -r
HTH
There's a huge difference. As has been mentioned, <%@ include
is a static include, <jsp:include
is a dynamic include. Think of it as a difference between a macro and a function call (if you are familiar with those terms). Another way of putting it, a static include is exactly the same thing as copy-pasting the exact content of the included file (the "code") at the location of the <%@ include
statement (which is exactly what the JSP compiler will do.
A dynamic include will make a request (using the request dispatcher) that will execute the indicated page and then include the output from the page in the output of the calling page, in place of the <jsp:include
statement.
The big difference here is that with a dynamic include, the included page will execute in it's own pageContext. And since it's a request, you can send parameters to the page the same way you can send parameters along with any other request. A static include, on the other hand, is just a piece of code that will execute inside the context of the calling page. If you statically include the same file more than once, the code in that file will exist in multiple locations on the calling page so something like
<%
int i = 0;
%>
would generate a compiler error (since the same variable can't be declared more than once).
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999
(which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
If you just want the milliseconds since 01-JAN-1970, then you can use
var theMoment = moment(); // or whatever your moment instance is
var millis;
millis = +theMoment; // a short but not very readable form
// or
millis = theMoment.valueOf();
// or (almost sure not as efficient as above)
millis = theMoment.toDate().getTime();
As far as your question goes: no, if activating from .ini
is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap
, yum install php-soap
). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).
In general, the double-dash --switches
are designed to be used when recompiling PHP from scratch.
You would download the PHP source package (as a compressed .tgz
tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script
./configure --prefix ...
The configure
command used by your PHP may be shown with phpinfo()
. Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap
will then enable SOAP in addition to everything else.
That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype
, gd
, libjpeg
, XML
, expat
, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg
installed might not be enough, and you might need libjpeg-dev
also).
I have to keep a separate virtual machine with everything installed for my recompilation purposes.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that +
returned a non-const value, and you could write:
(a + b).expensive();
In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.
In summary, there is a rationale for this practice, but it is essentially obsolete.
Just run command prompt as administrator and type this in.
easy_install python-dateutil
You can enable TLS 1.2 in IIS by following these instructions. I presume this would be sufficient if you have an ASP.NET-based application that runs on top of IIS, although it looks like it does not really meet your needs.
@Dan,
Do I not need msdtc enabled for transactions to work?
Only distributed transactions - Those that involve more than a single connection. Make doubly sure you are only opening a single connection within the transaction and it won't escalate - Performance will be much better too.
You can use the --table
or -t
option, which will output a nice looking set of results
echo 'desc table_name' | mysql -uroot database -t
or some other method to pass a query to mysql, like:
mysql -uroot table_name --table < /tmp/somequery.sql
output:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(30) | NO | UNI | NULL | |
| first_name | varchar(30) | NO | | NULL | |
| last_name | varchar(30) | NO | | NULL | |
| email | varchar(75) | NO | | NULL | |
| password | varchar(128) | NO | | NULL | |
| is_staff | tinyint(1) | NO | | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
| is_superuser | tinyint(1) | NO | | NULL | |
| last_login | datetime | NO | | NULL | |
| date_joined | datetime | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
I'd say, it depends on your situation. For example, I work in local government, and we have lots of images like mugshots, etc. We don't have a high number of users, but we need to have good security and auditing around the data. The database is a better solution for us since it makes this easier and we aren't going to run into scaling problems.
In the case you copy your public key with clipboard and paste it, it may happen the public key string can be broken which contains new-line.
Make sure your public key string formed as one line.
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
Rails4 has some added datatypes for Postgres.
For example, railscast #400 names two of them:
Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.
Besides, you can also use cidr, inet and macaddr. For more information:
You can use the ng-selected directive on the option elements. It takes expression that if truthy will set the selected property.
In this case:
<option ng-selected="data.unit == item.id"
ng-repeat="item in units"
ng-value="item.id">{{item.label}}</option>
Demo
angular.module("app",[]).controller("myCtrl",function($scope) {_x000D_
$scope.units = [_x000D_
{'id': 10, 'label': 'test1'},_x000D_
{'id': 27, 'label': 'test2'},_x000D_
{'id': 39, 'label': 'test3'},_x000D_
]_x000D_
_x000D_
$scope.data = {_x000D_
'id': 1,_x000D_
'unit': 27_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="myCtrl">_x000D_
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit">_x000D_
<option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>_x000D_
</select>_x000D_
</div>
_x000D_
pure JavaScript is not that difficult:
for(var i=0; i < form.elements.length; i++){
var e = form.elements[i];
console.log(e.name+"="+e.value);
}
Note: because form.elements is a object for-in loop does not work as expected.
Answer found here (by Chris Pietschmann), documented here (W3S).
Jacob Helwig mentions in his answer that:
It looks like rev-parse is being used without sufficient error checking before-hand
Commit 62f162f from Jeff King (peff
) should improve the robustness of git rev-parse
in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):
For cases where we do not match (e.g., "
doesnotexist..HEAD
"), we would then want to try to treat the argument as a filename.
try_difference()
gets this right, and always unmunges in this case.
However,try_parent_shorthand()
never unmunges, leading to incorrect error messages, or even incorrect results:
$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
input type=image will do it for you.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
Simple solution for this common annoying issue:
Just go to your ".context.cs" file (located under ".context.tt" which located under your "*.edmx" file).
Then, add this line to your constructor:
public DBEntities()
: base("name=DBEntities")
{
this.Configuration.ProxyCreationEnabled = false; // ADD THIS LINE !
}
hope this is helpful.
I am only submitting this answer because people expressed concerns over browsers and maintaining the order of objects. I recognize that it is not the most efficient way to accomplish the goal.
Having said this, I broke the problem down into two functions for readability.
// The following function is used for each itertion in the function updateObjectsInArr
const newObjInInitialArr = function(initialArr, newObject) {
let id = newObject.id;
let newArr = [];
for (let i = 0; i < initialArr.length; i++) {
if (id === initialArr[i].id) {
newArr.push(newObject);
} else {
newArr.push(initialArr[i]);
}
}
return newArr;
};
const updateObjectsInArr = function(initialArr, newArr) {
let finalUpdatedArr = initialArr;
for (let i = 0; i < newArr.length; i++) {
finalUpdatedArr = newObjInInitialArr(finalUpdatedArr, newArr[i]);
}
return finalUpdatedArr
}
const revisedArr = updateObjectsInArr(arr1, arr2);
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings
.
Single JsonConvert
with an overload:
JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
If you'd like to make this the default behaviour, add a
Global Setting with code in Application_Start()
in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.
component.html
<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio1" value="option1" type="radio"> TRUE
</label>
<label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio2" value="option2" type="radio"> FALSE
</label>
</div>
component.ts file
@Component({
selector: '',
templateUrl: './.component.html',
styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
checked = true;
}
If you are with Linux machines, "ifconfig eth0 mtu 9000 up" is the command to set the MTU for an interface. However, I have to say, big MTU has some downsides if the network transmission is not so stable, and it may use more kernel space memories.
From cppreference when incrementing iterators:
You should prefer pre-increment operator (++iter) to post-increment operator (iter++) if you are not going to use the old value. Post-increment is generally implemented as follows:
Iter operator++(int) {
Iter tmp(*this); // store the old value in a temporary object
++*this; // call pre-increment
return tmp; // return the old value }
Obviously, it's less efficient than pre-increment.
Pre-increment does not generate the temporary object. This can make a significant difference if your object is expensive to create.
This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.
You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:
%reset
or menu->restart terminal
Android Studio (version: 1.3.2) allows you to seamlessly access the .jar inside a .aar.
Bonus: it automatically decompiles the classes!
Simply follow these steps:
File > New > New Module > Import .JAR/.AAR Package
to import you .aar as a module
Add the newly created module as a dependency to your main project (not sure if needed)
Right click on "classes.jar" as shown in the capture below, and click "Show in explorer". Here is your .jar.
As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.
No, find() method is not a member of std::list
.
Instead, use std::find
from <algorithm>
std :: list < int > l;
std :: list < int > :: iterator pos;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.push_back(6);
int elem = 3;
pos = find(l.begin() , l.end() , elem);
if(pos != l.end() )
std :: cout << "Element is present. "<<std :: endl;
else
std :: cout << "Element is not present. "<<std :: endl;
For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml
has been adjusted:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>
Change this file to comment the Valve
:
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
After that, refresh your browser (not need to restart Tomcat), you can see the manager page.
I usually use the following approach
DECLARE @calls TABLE (
id INT IDENTITY(1,1)
,parameter INT
)
INSERT INTO @calls
select parameter from some_table where some_condition -- here you populate your parameters
declare @i int
declare @n int
declare @myId int
select @i = min(id), @n = max(id) from @calls
while @i <= @n
begin
select
@myId = parameter
from
@calls
where id = @i
EXECUTE p_MyInnerProcedure @myId
set @i = @i+1
end
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site.
For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here
If you're struggling with such an issue using Lollipop (Android 5.*) probably you guys should do one simple step that I'd done before my ADB (I use Ubuntu) got my phone:
Change USB PC connection type to "Send images(PTP)" (before I've been using "Media device(MTP)")
Just like this:
And don't forget to activate checkbox "USB debugging".
Map :
- It processes one row at a time , very similar to map() method of MapReduce.
- You return from the transformation after every row.
MapPartitions
- It processes the complete partition in one go.
- You can return from the function only once after processing the whole partition.
- All intermediate results needs to be held in memory till you process the whole partition.
- Provides you like setup() map() and cleanup() function of MapReduce
Map Vs mapPartitions
http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/
Spark Map
http://bytepadding.com/big-data/spark/spark-map/
Spark mapPartitions
http://bytepadding.com/big-data/spark/spark-mappartitions/
I don't know what version of CI you were using back in 2013, but I am using CI3 and I just tested with two null
parameters passed to limit()
and there was no LIMIT
or OFFSET
in the rendered query (I checked by using get_compiled_select()
).
This means that -- assuming your have correctly posted your coding attempt -- you don't need to change anything (or at least the old issue is no longer a CI issue).
If this was my project, this is how I would write the method to return an indexed array of objects or an empty array if there are no qualifying rows in the result set.
function nationList($limit = null, $start = null) {
// assuming the language value is sanitized/validated/whitelisted
return $this->db
->select('nation.id, nation.name_' . $this->session->userdata('language') . ' AS name')
->from('nation')
->order_by("name")
->limit($limit, $start)
->get()
->result();
}
These refinements remove unnecessary syntax, conditions, and the redundant loop.
For reference, here is the CI core code:
/**
* LIMIT
*
* @param int $value LIMIT value
* @param int $offset OFFSET value
* @return CI_DB_query_builder
*/
public function limit($value, $offset = 0)
{
is_null($value) OR $this->qb_limit = (int) $value;
empty($offset) OR $this->qb_offset = (int) $offset;
return $this;
}
So the $this->qb_limit
and $this->qb_offset
class objects are not updated because null
evaluates as true
when fed to is_null()
or empty()
.
Set the following two environment variables:
NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0
where gpu_id
is the ID of your selected GPU, as seen in the host system's nvidia-smi
(a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).
You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id
parameter in nvidia-smi
run in a terminal in the guest system).
This method based on NVIDIA_VISIBLE_DEVICES
exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES
to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).
Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0
or env
in Kubernetes or Openshift.
If you want GPU load-balancing, make gpu_id
random at each guest system start.
If setting this with python, make sure you are using strings for all environment variables, including numerical ones.
You can verify that a different card is selected for each value of gpu_id
by inspecting nvidia-smi
's Bus-Id parameter (in a terminal run in the guest system).
The accepted solution based on CUDA_VISIBLE_DEVICES
alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).
This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu
), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).
This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.
Hive Partitioning:
Partition divides large amount of data into multiple slices based on value of a table column(s).
Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.
Pros:
Cons:
Hive Bucketing:
Bucketing decomposes data into more manageable or equal parts.
With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.
Pros
Cons
You can use Numpy's genfromtxt()
method to do so, by setting the delimiter
kwarg to a comma.
from numpy import genfromtxt
my_data = genfromtxt('my_file.csv', delimiter=',')
More information on the function can be found at its respective documentation.
Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
The 1*y
method works in Numpy too:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
If you are asking for a way to convert Python lists from Boolean to int, you can use map
to do it:
>>> testList = [False, False, True, True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]
Or using list comprehensions:
>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]
I know there isn't any need to add a plugin for this.
But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.
The rest of karim79's answer is super cool.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="jquery.numeric.js"></script>
</head>
<body>
<form>
Numbers only:
<input class="numeric" type="text" />
Integers only:
<input class="integer" type="text" />
No negative values:
<input class="positive" type="text" />
No negative values (integer only):
<input class="positive-integer" type="text" />
<a href="#" id="remove">Remove numeric</a>
</form>
<script type="text/javascript">
$(".numeric").numeric();
$(".integer").numeric(false, function() {
alert("Integers only");
this.value = "";
this.focus();
});
$(".positive").numeric({ negative: false },
function() {
alert("No negative values");
this.value = "";
this.focus();
});
$(".positive-integer").numeric({ decimal: false, negative: false },
function() {
alert("Positive integers only");
this.value = "";
this.focus();
});
$("#remove").click(
function(e)
{
e.preventDefault();
$(".numeric,.integer,.positive").removeNumeric();
}
);
</script>
</body>
</html>
If you are in a po-up and you want to access the opening window, use window.opener
.
The easiest would be if you could load JQuery in the parent window as well:
window.opener.$("#serverMsg").html
// this uses JQuery in the parent window
or you could use plain old document.getElementById
to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):
element = window.opener.document.getElementById("serverMsg");
element = $(element);
If you are in an iframe or frameset and want to access the parent frame, use window.parent
instead of window.opener
.
According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.
With google
things changes very often: non of the previous answers worked for me.
based on this google training here is how you do it using
fused location provider
this requires Set Up Google Play Services
Activity class
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
usage
in you activity
Intent intent = new Intent(context, GPSTrackerActivity.class);
startActivityForResult(intent,1);
And this method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
Double longitude = extras.getDouble("Longitude");
Double latitude = extras.getDouble("Latitude");
}
}
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
The issue is because of Java version mismatch. Referring to the Wikipedia Java Class Reference:
These are the assigned major numbers. The error regarding the unsupported major.minor version is because during compile time you are using a higher JDK and a lower JDK during runtime.
Thus, the 'major.minor version 52.0' error is possibly because the jar was compiled in JDK 1.8, but you are trying to run it using a JDK 1.7 environment. The reported number is the required number, not the number you are using. To solve this, it's always better to have the JDK and JRE pointed to the same version.
In IntelliJ IDEA,
Restart IntelliJ IDEA.
Another approach which might help is by instructing IntelliJ IDEA which JDK version to start up with.
Go to: /Applications/IntelliJ\ IDEA\ 15\ CE.app/Contents/Info.plist and replace the JVM version with:
<key>JVMVersion</key>
<string>1.8*</string>
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.
As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.
Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
You're looking for a query such as:
DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)
INSERT INTO @table1
(
test
)
SELECT 1
UNION ALL SELECT 2
INSERT INTO @table2
(
test
)
SELECT 1
UNION ALL SELECT 3
-- Here's the important part
SELECT a.*
FROM @table1 a
LEFT join @table2 b on a.test = b.test -- this will return all rows from a
WHERE b.test IS null -- this then excludes that which exist in both a and b
-- Returned results:
2
Try to use this with single quotes in data:
insert into table test_hive values ('1','puneet');
Unicode is just a standard that defines a character set (UCS) and encodings (UTF) to encode this character set. But in general, Unicode is refered to the character set and not the standard.
Read The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) and Unicode In 5 Minutes.
You need to set the height of html
to 100%
body {
background-image:url("../images/myImage.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
}
html {
height: 100%
}
where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month
where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:
class A { }
class B extends A { }
Object oA = new A();
Object oB = new B();
oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true
oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true
A simple approach is to make use of
;
For example:
ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV" deauthorize_users.yml --check
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
$url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}
If anyone is interested, you can have the the offset information for all the consumer groups with the following command:
kafka-consumer-groups --bootstrap-server localhost:9092 --all-groups --describe
The parameter --all-groups is available from Kafka 2.4.0
Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter()
for this:
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
The HttpServletRequest
should already be available to you inside Spring MVC as one of the method arguments of the handleRequest()
method.
I was working on re-ordering a lot of tables and didn't want to have to write the same queries over and over so I made a script to do it all for me. Essentially, it:
pg_dump
pg_dump
query to create a re-ordered table with dataIt can be used by running the following simple command:
./reorder.py -n schema -d database table \
first_col second_col ... penultimate_col ultimate_col --migrate
It prints out the sql so you can verify and test it, that was a big reason I based it on pg_dump
. You can find the github repo here.
If you are using latest versions of Angular (2/5/6) :
In your component.ts
//x.component.ts
prefs = false;
hidePrefs(){
this.prefs = true;
}
Why don't you just save/serve the CSS file as UTF-8?
nav a:hover:after {
content: "?";
}
If that's not good enough, and you want to keep it all-ASCII:
nav a:hover:after {
content: "\2193";
}
The general format for a Unicode character inside a string is \000000
to \FFFFFF
– a backslash followed by six hexadecimal digits. You can leave out leading 0
digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.
Relevant part of the CSS2 spec:
Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:
- with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
- by providing exactly 6 hexadecimal digits: "\000026B" ("&B")
In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.
If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).
- Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
The identifier "te\st" is exactly the same identifier as "test".
Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).
If you really want to have a blocking (synchronous) delay
function (for whatsoever), why not do something like this:
<script type="text/javascript">
function delay(ms) {
var cur_d = new Date();
var cur_ticks = cur_d.getTime();
var ms_passed = 0;
while(ms_passed < ms) {
var d = new Date(); // Possible memory leak?
var ticks = d.getTime();
ms_passed = ticks - cur_ticks;
// d = null; // Prevent memory leak?
}
}
alert("2 sec delay")
delay(2000);
alert("done ... 500 ms delay")
delay(500);
alert("done");
</script>
If you are planning on using your Swift singleton class in Objective-C, this setup will have the compiler generate appropriate Objective-C-like header(s):
class func sharedStore() -> ImageStore {
struct Static {
static let instance : ImageStore = ImageStore()
}
return Static.instance
}
Then in Objective-C class you can call your singleton the way you did it in pre-Swift days:
[ImageStore sharedStore];
This is just my simple implementation.
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using "multiple"
<input type="file" name="datafile" size="40" multiple>
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226
public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
{
List<dynamic> result = new List<dynamic>();
Dictionary<string, object> d;
foreach (DataRow dr in dt.Rows)
{
d = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
d.Add(dc.ColumnName, dr[dc]);
result.Add(GetDynamicObject(d));
}
return result.AsEnumerable<dynamic>();
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
The ASPX code will look something like this:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
Here is another nice clean option that does not require changing your pattern.
var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.Replace(text, pattern, (_match) =>
{
Group group = _match.Groups[1];
string replace = "AA";
return String.Format("{0}{1}{2}", _match.Value.Substring(0, group.Index - _match.Index), replace, _match.Value.Substring(group.Index - _match.Index + group.Length));
});
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You could use eventlet. It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.
Here's an example of a super minimal crawler:
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.
Try using Response.AddHeader
instead of Response.Headers.Add()
Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.
function A(val){
if(typeof(val) === "undefined")
//do this
else
//do this
}
For anyone who wants to pass in arbitrary strings which are exact matches (And not worry about escaping regex special characters), git log takes a --fixed-strings option
git log --fixed-strings --grep "$SEARCH_TERM"
I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.
A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.
If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.
TIMESTAMP LIMITATION
The TIMESTAMP
type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME
type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW()
.
This article covers an interesting relationship between ROW_NUMBER()
and DENSE_RANK()
(the RANK()
function is not treated specifically). When you need a generated ROW_NUMBER()
on a SELECT DISTINCT
statement, the ROW_NUMBER()
will produce distinct values before they are removed by the DISTINCT
keyword. E.g. this query
SELECT DISTINCT
v,
ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... might produce this result (DISTINCT
has no effect):
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| a | 2 |
| a | 3 |
| b | 4 |
| c | 5 |
| c | 6 |
| d | 7 |
| e | 8 |
+---+------------+
Whereas this query:
SELECT DISTINCT
v,
DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... produces what you probably want in this case:
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
| e | 5 |
+---+------------+
Note that the ORDER BY
clause of the DENSE_RANK()
function will need all other columns from the SELECT DISTINCT
clause to work properly.
The reason for this is that logically, window functions are calculated before DISTINCT
is applied.
Using PostgreSQL / Sybase / SQL standard syntax (WINDOW
clause):
SELECT
v,
ROW_NUMBER() OVER (window) row_number,
RANK() OVER (window) rank,
DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v
... you'll get:
+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a | 1 | 1 | 1 |
| a | 2 | 1 | 1 |
| a | 3 | 1 | 1 |
| b | 4 | 4 | 2 |
| c | 5 | 5 | 3 |
| c | 6 | 5 | 3 |
| d | 7 | 7 | 4 |
| e | 8 | 8 | 5 |
+---+------------+------+------------+
(Edit: Forget my previous babble...)
Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.
About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController
(e.g. "UsersController" is the controller of the model "User").
If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.
If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.
SELECT toString(firstName) FROM com.yourcompany.somepackage.User
Totally brilliant.
One can also use slightly modified version of the accepted one and adjust base characters string to it's needs:
public static string Int32ToString(int value, int toBase)
{
string result = string.Empty;
do
{
result = "0123456789ABCDEF"[value % toBase] + result;
value /= toBase;
}
while (value > 0);
return result;
}
The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.
Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.com/htdocs/) with the following content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
More about how this works in these pages: mod_rewrite guide (introduction, using it), reference documentation
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc
file type
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
If you need to do the filteration on multiple types, use the below command.
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
Now $fileNames
variable act as an array from which you can loop and apply your business logic.
Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?
@SqlResultSetMapping(
name="groupDetailsMapping",
classes={
@ConstructorResult(
targetClass=GroupDetails.class,
columns={
@ColumnResult(name="GROUP_ID"),
@ColumnResult(name="USER_ID")
}
)
}
)
@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")
and use following in repository interface:
GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);
According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery
, @SqlResultSetMapping
and @ConstructorResult
you should be able to achieve that behaviour
Declare an object arr
to hold the unique set as keys. Populate arr
by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.
Given testArray:
var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
solution:
var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});
JSON.stringify(arr)
will output
{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}
Object.keys(arr)
will return ["a","b","c","d","e","f","g","h"]
To find the occurrences of any item e.g. b arr['b']
will output 2
Now that Google Play locations services are here, I recommend that developers start using the new fused location provider. You will find it easier to use and more accurate. Please watch the Google I/O video Beyond the Blue Dot: New Features in Android Location by the two guys who created the new Google Play location services API.
I've been working with location APIs on a number of mobile platforms, and I think what these two guys have done is really revolutionary. It's gotten rid of a huge amount of the complexities of using the various providers. Stack Overflow is littered with questions about which provider to use, whether to use last known location, how to set other properties on the LocationManager, etc. This new API that they have built removes most of those uncertainties and makes the location services a pleasure to use.
I've written an Android app that periodically gets the location using Google Play location services and sends the location to a web server where it is stored in a database and can be viewed on Google Maps. I've written both the client software (for Android, iOS, Windows Phone and Java ME) and the server software (for ASP.NET and SQL Server or PHP and MySQL). The software is written in the native language on each platform and works properly in the background on each. Lastly, the software has the MIT License. You can find the Android client here:
https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android
function validateFileExtensions(){
var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
var fileErrors = new Array();
$( "input:file").each(function(){
var file = $(this).value;
var ext = file.split('.').pop();
if( $.inArray( ext, validFileExtensions ) == -1) {
fileErrors.push(file);
}
});
if( fileErrors.length > 0 ){
var errorContainer = $("#validation-errors");
for(var i=0; i < fileErrors.length; i++){
errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
}
return false;
}
return true;
}
Python 3.6 changed the game for string concatenation of known components with Literal String Interpolation.
Given the test case from mkoistinen's answer, having strings
domain = 'some_really_long_example.com'
lang = 'en'
path = 'some/really/long/path/'
The contenders are
f'http://{domain}/{lang}/{path}'
- 0.151 µs
'http://%s/%s/%s' % (domain, lang, path)
- 0.321 µs
'http://' + domain + '/' + lang + '/' + path
- 0.356 µs
''.join(('http://', domain, '/', lang, '/', path))
- 0.249 µs (notice that building a constant-length tuple is slightly faster than building a constant-length list).
Thus currently the shortest and the most beautiful code possible is also fastest.
In alpha versions of Python 3.6 the implementation of f''
strings was the slowest possible - actually the generated byte code is pretty much equivalent to the ''.join()
case with unnecessary calls to str.__format__
which without arguments would just return self
unchanged. These inefficiencies were addressed before 3.6 final.
The speed can be contrasted with the fastest method for Python 2, which is +
concatenation on my computer; and that takes 0.203 µs with 8-bit strings, and 0.259 µs if the strings are all Unicode.
An alternative to converting the image is to create an RGB index from the palette.
from PIL import Image
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
def getPaletteInRgb(img):
"""
Returns list of RGB tuples found in the image palette
:type img: Image.Image
:rtype: list[tuple]
"""
assert img.mode == 'P', "image should be palette mode"
pal = img.getpalette()
colors = chunk(pal, 3, False)
return colors
# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)
NodeJS Solution:
In Nodejs you can get it via promises...
If you write this code, you can be sure that the page is fully loaded when you get to the then...
driver.get('www.sidanmor.com').then(()=> {
// here the page is fully loaded!!!
// do your stuff...
}).catch(console.log.bind(console));
If you write this code, you will navigate, and selenium will wait 3 seconds...
driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...
From Selenium documentation:
this.get( url ) ? Thenable
Schedules a command to navigate to the given URL.
Returns a promise that will be resolved when the document has finished loading.
The blog post How to CSS form drop down style no JavaScript works for me, but it fails in Opera though:
select {_x000D_
border: 0 none;_x000D_
color: #FFFFFF;_x000D_
background: transparent;_x000D_
font-size: 20px;_x000D_
font-weight: bold;_x000D_
padding: 2px 10px;_x000D_
width: 378px;_x000D_
*width: 350px;_x000D_
*background: #58B14C;_x000D_
}_x000D_
_x000D_
#mainselection {_x000D_
overflow: hidden;_x000D_
width: 350px;_x000D_
-moz-border-radius: 9px 9px 9px 9px;_x000D_
-webkit-border-radius: 9px 9px 9px 9px;_x000D_
border-radius: 9px 9px 9px 9px;_x000D_
box-shadow: 1px 1px 11px #330033;_x000D_
background: url("arrow.gif") no-repeat scroll 319px 5px #58B14C;_x000D_
}
_x000D_
<div id="mainselection">_x000D_
<select>_x000D_
<option>Select an Option</option>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</div>
_x000D_
The algorithms use iterator to the beginning and past the end of the sequence. That is, you want to call std::sort()
something like this:
std::sort(std::begin(name), std::end(name));
In case you don't use C++11 and you don't have std::begin()
and std::end()
, they are easy to define yourself (obviously not in namespace std
):
template <typename T, std::size_t Size>
T* begin(T (&array)[Size]) {
return array;
}
template <typename T, std::size_t Size>
T* end(T (&array)[Size]) {
return array + Size;
}
MIME type of the CSV is text/csv according to RFC 4180.
First check your Internet conection..
or try with
Tools -> Android -> Sync
or Try
File -> Settings -> Gradle -> Check Offline Work
Here is my script to do the process described by sje397:
#!/bin/sh
# Needed if running on Windows
FIND="/usr/bin/find"
DIFF="diff -r"
# Extract the jar (war or ear)
JAR_FILE1=$1
JAR_FILE2=$2
JAR_DIR=${PWD} # to assign to a variable
TEMP_DIR=$(mktemp -d)
echo "Extracting jars in $TEMP_DIR"
EXT_DIR1="${TEMP_DIR}/${JAR_FILE1%.*}"
EXT_DIR2="${TEMP_DIR}/${JAR_FILE2%.*}"
mkdir ${EXT_DIR1}
cd ${EXT_DIR1}
jar xf ${JAR_DIR}/${JAR_FILE1}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
mkdir ${EXT_DIR2}
cd ${EXT_DIR2}
jar xf ${JAR_DIR}/${JAR_FILE2}
jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
cd ..
# remove class files so the diff is clean
${FIND} ${TEMP_DIR} -name '*.class' | xargs rm
# diff recursively
${DIFF} ${EXT_DIR1} ${EXT_DIR2}
I can run it on Windows using GIT for Windows. Just open a command prompt. Run bash and then execute the script from there.
Use JSON.
In the following example $php_variable
can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..)
like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
NSDate *timeLater = [NSDate dateWithTimeIntervalSinceNow:60*90];
NSTimeInterval duration = [timeLater timeIntervalSinceNow];
NSInteger hours = floor(duration/(60*60));
NSInteger minutes = floor((duration/60) - hours * 60);
NSInteger seconds = floor(duration - (minutes * 60) - (hours * 60 * 60));
NSLog(@"timeLater: %@", [dateFormatter stringFromDate:timeLater]);
NSLog(@"time left: %d hours %d minutes %d seconds", hours,minutes,seconds);
Outputs:
timeLater: 22:27
timeLeft: 1 hours 29 minutes 59 seconds
I usually use PHP's built in error handlers that can handle every possible error outside of syntax and still render a nice 'Down for maintenance' page otherwise:
Finally i found the problem i was using metro framework and all your solutions will not work with metroTextBox, and all your solutions will work with normal textBox in load , show , visibility_change ,events, even the tab index = 0 is valid.
// private void Form1_VisibleChanged(object sender, EventArgs e)
// private void Form1__Shown(object sender, EventArgs e)
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Select();
this.ActiveControl=textBox1;
textBox1.Focus();
}
One way to get around this is to use implicit casting:
bool DoesEntityExist<T>(T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;
calling it like so:
DoesEntityExist(entity, entityGuid, transaction);
Going a step further, you can turn it into an extension method (it will need to be declared in a static class):
static bool DoesEntityExist<T>(this T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;
calling as so:
entity.DoesEntityExist(entityGuid, transaction);
Most modern Javascript frameworks (JQuery, Prototype, etc...) have a utility function tacked on to String that handles this.
Here's an example in Prototype:
'Some random text'.truncate(10);
// -> 'Some ra...'
This seems like one of those functions you want someone else to deal with/maintain. I'd let the framework handle it, rather than writing more code.
The Ruby Style Guide says it better than I could:
Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)
# boolean expression
if some_condition && some_other_condition
do_something
end
# control flow
document.saved? or document.save!
In Swift 5.0 and Xcode 10.2
You have two ways to approaches
1) Direct approach
btn.contentHorizontalAlignment = .left
2) SharedClass example (write once and use every ware)
This is your shared class(like this you access all components properties)
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
private override init() {
}
}
//UIButton extension
extension UIButton {
func btnProperties() {
contentHorizontalAlignment = .left
}
}
In your ViewController call like this
button.btnProperties()//This is your button
okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.
json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';
json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
No. Scroll speed is determined by the browser (and usually directly by the settings on the computer/device). CSS and Javascript don't (or shouldn't) have any way to affect system settings.
That being said, there are likely a number of ways you could try to fake a different scroll speed by moving your own content around in such a way as to counteract scrolling. However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users, but I would start by finding events that your target browsers fire that indicate scrolling.
Once you can capture the scroll event (assuming you can), then you would be able to adjust your content dynamically so that the portion you want is visible.
Another approach would be to deal with this in Flash, which does give you at least some level of control over scrolling events.
You may have to concatenate the % signs with your parameter, e.g.:
LIKE '%' || @query || '%'
Edit: Actually, that may not make any sense at all. I think I may have misunderstood your problem.
You can also use REPLACE()
:
UPDATE Table
SET Column = REPLACE(Column, 'Test123', 'Test')
There are two problems with this code:
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:
function callA() {
$.ajax({
...
success: function() {
//do stuff
callB();
}
});
}
function callB() {
$.ajax({
...
success: function() {
//do stuff
callC();
}
});
}
function callC() {
$.ajax({
...
});
}
callA();
Maybe it caused by Filename variable
File = TextBox1.Value
It should be
Filename = TextBox1.Value
A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.
Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.
An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.
Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.
Edit: From the git help stash
documentation in the pop section:
Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.
If the --index option is used, then tries to reinstate not only the working tree's changes, but also the index's ones. However, this can fail, when you have conflicts (which are stored in the index, where you therefore can no longer apply the changes as they were originally).
Try hardcopying all your repo into a new dir (so you have a copy of it) and run:
git stash show
and save that output somewhere if you care about it.
then: git stash drop
to drop the conflicting stash
then: git reset HEAD
That should leave your repo in the state it was before (hopefully, I still haven't been able to repro your problem)
===
I am trying to repro your problem but all I get when usin git stash pop
is:
error: Your local changes to the following files would be overwritten by merge:
...
Please, commit your changes or stash them before you can merge.
Aborting
In a clean dir:
git init
echo hello world > a
git add a & git commit -m "a"
echo hallo welt >> a
echo hello world > b
git add b & git commit -m "b"
echo hallo welt >> b
git stash
echo hola mundo >> a
git stash pop
I don't see git trying to merge my changes, it just fails. Do you have any repro steps we can follow to help you out?
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
Use the files
filelist of the element instead of val()
$("input[type=file]").on('change',function(){
alert(this.files[0].name);
});
Similar question has been asked in stackoverflow before.
See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?
Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:
- no DNS support
- misconfigured
- behind load balancing software
For those having the same issue of missing Iber.h on Alpine Linux, in a docker image that you are trying to adapt to Alpine for instance.
The package you are looking for is: openldap-dev
So run
apk add openldap-dev
Available from version 3.3 up to Edge
Available for both armhf and x86_64 Architectures.
setCustomValidity
's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.
You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.
The easiest way is to simply use the title
attribute on the input element - its content is displayed together with the standard browser message.
<input type="text" required title="Lütfen isaretli yerleri doldurunuz" />
If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.
Use setText(str)
method of JLabel
to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
CD E:\Documents and Settings\All Users\Application Data
E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll
Just move your mouse over the missing view and hit keys on windows ALT + ENTER
If the UITextField
is from UISearchBar
then first get the textField
from searchBar
and then apply tintColor
property:
let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.tintColor = UIColor.lightGray
Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:
file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode
data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
Thanks so much everyone for all these input!
I quoted that sentence from a lecture note online: http://www.cs.cornell.edu/courses/cs213/2002fa/lectures/Lecture02/Lecture02.pdf
the first page the 6th slide
" Pass by VALUE The value of a variable is passed along to the function If the function modifies that value, the modifications stay within the scope of that function.
Pass by REFERENCE A reference to the variable is passed along to the function If the function modifies that value, the modifications appear also within the scope of the calling function.
"
Thanks so much again!
Hi this is due to new version of the jQuery => 1.9.0
you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/
jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js
replace :
<script src="http://code.jquery.com/jquery-latest.js"></script>
by :
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
in your page and its working.
all previous answer were correct, I wanna just add an information I saw was not mentioned;
If the project is a private project to correctly push the image have to be configured a personal access token or deploy token with read_registry key enabled.
source: https://gitlab.com/help/user/project/container_registry#using-with-private-projects
hope this is helpful (also if the question is posted so far in the time)
df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')
You aren't trying to save unicode strings, you're trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:
user.last_name = u'Slatkevicius'
or (when you don't have string literals) decode them using the utf-8 encoding:
user.last_name = lastname.decode('utf-8')
A correct answer is
typeof(MyType).GetInterface(nameof(IMyInterface)) != null;
However,
typeof(MyType).IsAssignableFrom(typeof(IMyInterface));
might return a wrong result, as the following code shows with string and IConvertible:
static void TestIConvertible()
{
string test = "test";
Type stringType = typeof(string); // or test.GetType();
bool isConvertibleDirect = test is IConvertible;
bool isConvertibleTypeAssignable = stringType.IsAssignableFrom(typeof(IConvertible));
bool isConvertibleHasInterface = stringType.GetInterface(nameof(IConvertible)) != null;
Console.WriteLine($"isConvertibleDirect: {isConvertibleDirect}");
Console.WriteLine($"isConvertibleTypeAssignable: {isConvertibleTypeAssignable}");
Console.WriteLine($"isConvertibleHasInterface: {isConvertibleHasInterface}");
}
Results:
isConvertibleDirect: True
isConvertibleTypeAssignable: False
isConvertibleHasInterface: True
For My case i did 3 steps to achieve the sucessful build.
revert all the local changes if any (or just keep a copy of it in case you need it for future use)
Do a git clean up, do a pull and check the logs for error
GO to the git bash option and the error i was getting in log in above stem (i my case ) as "error: cannot lock ref and the branch details", so in the git bash i ran the following command git update-ref -d 'Branch_name'
For example if the error was something like **
**error: cannot lock ref 'refs/remotes/origin/EXMPLEISSUE/EXAMPLE-1011_DEMO_web_interface_DOES_NOT_GET_GIT_UPDATE':
Then i ran following command git update-ref -d 'refs/remotes/origin/EXMPLEISSUE/EXAMPLE-1011_DEMO_web_interface_DOES_NOT_GET_GIT_UPDATE'
We have to ensure all the error in logs to be solved similarly before getting a successful pull by doing git update-ref -d 'Branch_name' and finally i can get the take the successful pull from git.
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
Use moment js for any date operation.
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
In my case I was using jackson-databind-2.8.8.jar
that is not compatible with JDK 1.6
I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.
After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.
When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.
For example, if I would like to create the file filename.md
in a series of sub-folders, I can do this (taken from the GitHub blog):
if you are using new recaptcha 2.0 use this: for code behind:
ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});", true);
for simple javascript
<script>$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {});</script>
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
As others have done, creating new System variables M2 and M2_HOME solved the problem. Just making User variables M2 and M2_HOME on my Windows XP machine led to maven not being recognised from the command line. I then deleted the User variables, created copies as System variables and it all came to life.
This was apache-maven-3.0.4 with XP sp3. So the instructions in: http://maven.apache.org/download.cgi seem incorrect.
This will work too
my_country_code="green"
x="country"
eval z='$'my_"$x"_code
echo $z ## o/p: green
In your case
eval final_val='$'magic_way_to_define_magic_variable_"$1"
echo $final_val
In my case, I had two project in a solution, I added a sub-namespace into the referenced project, but when building, I didn't notice that the referenced project build failed and it used the last successfully built version which didn't have this new namespace, so the error was correct, that it cannot be found, because it didn't exist The solution was obviously to fix errors in referenced project.
var string = 123 (is string),
parseInt(parameter is string);
var string = '123';
var int= parseInt(string );
console.log(int); //Output will be 123.
i added both Convert Zero Datetime=True
& Allow Zero Datetime=True
and it works fine
Array.prototype.last = Array.prototype.last || function() {
var l = this.length;
return this[l-1];
}
x = [1,2];
alert( x.last() )
According to the latest version (select2 3.4.5) documented here, it would be as simple as:
$("#my_select").select2("val", "");
I had this problem, too.
Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.
Hey I was following the tutorial on tutorialpoint.com. Add after you complete Step 2 - Install Apache Common Logging API: You must import external jar libraries to the project from the files downloaded at this step. For me the file name was "commons-logging-1.1.1".
This is another great change from Google ... The suggested modification: replace onAttach(Activity activity)
with onAttach(Context context)
crashed my apps on older APIs since onAttach(Context context)
will not be called on native fragments.
I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).
Here is what I did:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Code here
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Code here
}
}
Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.
Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.
UPDATE t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
SET t1.a = 'something',
t2.b = 42,
t3.c = t2.c
WHERE t1.a = 'blah';
To see what this is going to update, you can convert this into a select statement, e.g.:
SELECT t2.t1_id, t2.t3_id, t1.a, t2.b, t2.c AS t2_c, t3.c AS t3_c
FROM t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
WHERE t1.a = 'blah';
An example using the same tables as the other answer:
SELECT Books.BookID, Orders.OrderID,
Orders.Quantity AS CurrentQuantity,
Orders.Quantity + 2 AS NewQuantity,
Books.InStock AS CurrentStock,
Books.InStock - 2 AS NewStock
FROM Books
INNER JOIN Orders ON Books.BookID = Orders.BookID
WHERE Orders.OrderID = 1002;
UPDATE Books
INNER JOIN Orders ON Books.BookID = Orders.BookID
SET Orders.Quantity = Orders.Quantity + 2,
Books.InStock = Books.InStock - 2
WHERE Orders.OrderID = 1002;
EDIT:
Just for fun, let's add something a bit more interesting.
Let's say you have a table of books
and a table of authors
. Your books
have an author_id
. But when the database was originally created, no foreign key constraints were set up and later a bug in the front-end code caused some books to be added with invalid author_id
s. As a DBA you don't want to have to go through all of these books
to check what the author_id
should be, so the decision is made that the data capturers will fix the books
to point to the right authors
. But there are too many books to go through each one and let's say you know that the ones that have an author_id
that corresponds with an actual author
are correct. It's just the ones that have nonexistent author_id
s that are invalid. There is already an interface for the users to update the book details and the developers don't want to change that just for this problem. But the existing interface does an INNER JOIN authors
, so all of the books with invalid authors are excluded.
What you can do is this: Insert a fake author record like "Unknown author". Then update the author_id
of all the bad records to point to the Unknown author. Then the data capturers can search for all books with the author set to "Unknown author", look up the correct author and fix them.
How do you update all of the bad records to point to the Unknown author? Like this (assuming the Unknown author's author_id
is 99999):
UPDATE books
LEFT OUTER JOIN authors ON books.author_id = authors.id
SET books.author_id = 99999
WHERE authors.id IS NULL;
The above will also update books
that have a NULL
author_id
to the Unknown author. If you don't want that, of course you can add AND books.author_id IS NOT NULL
.
You can use it with your local variables, like this:
@animal = "Dog"
@action = "licks"
@second_animal = "Bird"
"The #{@animal} #{@action} the #{@second_animal}"
the output would be: "The Dog licks the Bird"
I realize this question is a bit old but here's a really simple solution that was missing. You don't need to create a custom ListView or even a custom layout.
Just create an anonymous subclass of ArrayAdapter and override getView(). Let super.getView() handle all the heavy lifting. Since simple_list_item_1 is just a text view you can customize it (e.g. set textColor) and then return it.
Here's an example from one of my apps. I'm displaying a list of recent locations and I want all occurrences of "Current Location" to be blue and the rest white.
ListView listView = (ListView) this.findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MobileMuni.getBookmarkStore().getRecentLocations()) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
String currentLocation = RouteFinderBookmarksActivity.this.getResources().getString(R.string.Current_Location);
int textColor = textView.getText().toString().equals(currentLocation) ? R.color.holo_blue : R.color.text_color_btn_holo_dark;
textView.setTextColor(RouteFinderBookmarksActivity.this.getResources().getColor(textColor));
return textView;
}
});
If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.
If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.
If you think your volume is a "network drive", it will be easier. To edit the file located in this drive, you just need to turn on another machine and connect to this network drive, then edit the file like normal.
How to do that purely with docker (without FTP/SSH ...)?
Example:
docker run -d --name shared_vim_editor \
-v <your_volume>:/home/developer/workspace \
jare/vim-bundle:latest
docker exec -it -u root shared_vim_editor /bin/bash
Hope this helps.
replicate
is another option:
replicate(10, 0)
# [1] 0 0 0 0 0 0 0 0 0 0
replicate(5, 1)
# [1] 1 1 1 1 1
To create a matrix:
replicate( 5, numeric(3) )
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0 0 0 0 0
#[2,] 0 0 0 0 0
#[3,] 0 0 0 0 0
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
At the Maven repo, there are samples to add the dependency in maven, sbt, gradle, etc.
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.11
ie for Maven, you just create a project, for example
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4
then look at the pom.xml, then at the library at the dependencies xml element:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
For sbt do something like
sbt new scala/hello-world.g8
then edit the build.sbt to add the library
libraryDependencies += "org.apache.httpcomponents" % "httpcore" % "4.4.11"
As others have noted, golang does not have a ternary operator or any equivalent. This is a deliberate decision thought to intend readability.
This recently lead me to a scenario constructing a bit-mask in a very efficient manner became hard to read when written idiomatically because it took up a lot of lines of screen, very inefficient when encapsulated as a function, or both, as the code produces branches:
package lib
func maskIfTrue(mask uint64, predicate bool) uint64 {
if predicate {
return mask
}
return 0
}
producing:
text "".maskIfTrue(SB), NOSPLIT|ABIInternal, $0-24
funcdata $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
funcdata $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
movblzx "".predicate+16(SP), AX
testb AL, AL
jeq maskIfTrue_pc20
movq "".mask+8(SP), AX
movq AX, "".~r2+24(SP)
ret
maskIfTrue_pc20:
movq $0, "".~r2+24(SP)
ret
What I learned from this was to leverage a little more Go; using a named result in the function (result int)
saves me a line declaring it in the function (and you can do the same with captures), but the compiler also recognizes this idiom (only assign a value IF) and replaces it - if possible - with a conditional instruction.
func zeroOrOne(predicate bool) (result int) {
if predicate {
result = 1
}
return
}
producing a branch-free result:
movblzx "".predicate+8(SP), AX
movq AX, "".result+16(SP)
ret
which go then freely inlines.
package lib
func zeroOrOne(predicate bool) (result int) {
if predicate {
result = 1
}
return
}
type Vendor1 struct {
Property1 int
Property2 float32
Property3 bool
}
// Vendor2 bit positions.
const (
Property1Bit = 2
Property2Bit = 3
Property3Bit = 5
)
func Convert1To2(v1 Vendor1) (result int) {
result |= zeroOrOne(v1.Property1 == 1) << Property1Bit
result |= zeroOrOne(v1.Property2 < 0.0) << Property2Bit
result |= zeroOrOne(v1.Property3) << Property3Bit
return
}
produces https://go.godbolt.org/z/eKbK17
movq "".v1+8(SP), AX
cmpq AX, $1
seteq AL
xorps X0, X0
movss "".v1+16(SP), X1
ucomiss X1, X0
sethi CL
movblzx AL, AX
shlq $2, AX
movblzx CL, CX
shlq $3, CX
orq CX, AX
movblzx "".v1+20(SP), CX
shlq $5, CX
orq AX, CX
movq CX, "".result+24(SP)
ret
In MacOS Cmd+C is useful to minimizing the full screen
Why not just have the parent wait for the child to close. This is more than you need.
// Execute child process
System.Diagnostics.Process proc =
System.Diagnostics.Process.Start("notepad.exe");
proc.WaitForExit();
this is my answer. $ cat file > copy_file
I struggled a lot to find the answer.
You don't really need to do anything with body size. All you need to remove the inline style from the map code:
<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=new+york&aq=&sll=53.546224,-2.106543&sspn=0.02453,0.084543&ie=UTF8&hq=&hnear=New+York,+United+States&t=m&z=10&iwloc=A&output=embed"></iframe><br /><small><a href="https://maps.google.co.uk/maps?f=q&source=embed&hl=en&geocode=&q=new+york&aq=&sll=53.546224,-2.106543&sspn=0.02453,0.084543&ie=UTF8&hq=&hnear=New+York,+United+States&t=m&z=10&iwloc=A" style="color:#0000FF;text-align:left">View Larger Map</a></small>
remove all the inline style and add class or ID and then style it the way you like.
Slightly altered version of Sven Marnach's solution..
import os
folder_location = 'C:\SomeFolderName'
file_list = create_file_list(folder_location)
def create_file_list(path):
return_list = []
for filenames in os.walk(path):
for file_list in filenames:
for file_name in file_list:
if file_name.endswith((".txt")):
return_list.append(file_name)
return return_list
in my case,
i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.
Require all granted
Hope the full virtual host setup structure will save you.
<VirtualHost *:80>
DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
ServerName project.loc
<Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
Require all granted
</Directory>
ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common
</VirtualHost>
all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.
In your concrete example the problem is that you don't use this construct correctly:
@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })
@JsonSubTypes.Type
should contain the actual non-abstract subtypes of your abstract class.
Therefore if you have:
abstract class Parent
and the concrete subclasses
Ch1 extends Parent
and
Ch2 extends Parent
Then your annotation should look like:
@JsonSubTypes({
@JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
@JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})
Here name
should match the value of your 'discriminator':
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT,
property = "type")
in the property
field, here it is equal to type
. So type
will be the key and the value you set in name
will be the value.
Therefore, when the json string comes if it has this form:
{
"type": "ch1",
"other":"fields"
}
Jackson will automatically convert this to a Ch1
class.
If you send this:
{
"type": "ch2",
"other":"fields"
}
You would get a Ch2
instance.
From JsonProperty javadoc,
Defines name of the logical property, i.e. JSON object field name to use for the property. If value is empty String (which is the default), will try to use name of the field that is annotated.
I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:
function transaction ($con, $Q){
mysqli_query($con, "START TRANSACTION");
for ($i = 0; $i < count ($Q); $i++){
if (!mysqli_query ($con, $Q[$i])){
echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
break;
}
}
if ($i == count ($Q)){
mysqli_query($con, "COMMIT");
return 1;
}
else {
mysqli_query($con, "ROLLBACK");
return 0;
}
}
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
Obsolete gone, this works to me
public static IPAddress GetIPAddress()
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address =>
address.AddressFamily == AddressFamily.InterNetwork).First();
return ip;
}
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
You could use ob_start();
before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML
.
Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.
Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.
Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).
The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.
Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.
Make sure you defined all the translations in all the string.xml
files
The reason ++i
can be slightly faster than i++
is that i++
can require a local copy of the value of i before it gets incremented, while ++i
never does. In some cases, some compilers will optimize it away if possible... but it's not always possible, and not all compilers do this.
I try not to rely too much on compilers optimizations, so I'd follow Ryan Fox's advice: when I can use both, I use ++i
.
Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date
field can be done in any of the following ways:
Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
For an ascending sort, omit the -
prefix on the string version or use values of 1
, asc
, or ascending
.
Try this method:
var a = "anan güzel mi?";_x000D_
if (a.endsWith("?")) a = a.slice(0, -1); _x000D_
document.body.innerHTML = a;
_x000D_
You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.
Let's say you have an associative array like this:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => array('x'=>123)
);
In the first iteration : $key="one"
and $value=1
.
Sometimes you need this key ,if you want only the value , you can avoid using it.
In the last iteration : $key='seventeen'
and $value = array('x'=>123)
so to get value of the first element in this array
value, you need a key
, x in this case: $value['x'] =123
.
If anyone cares, for NTEXT
, use the following format:
SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT)
FROM [DataTable]
I think you might be looking for Except
:
The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.
Check out this link, this link, or Google, for more information.
This code is used to check weather your application with package name is installed or not if not then it will open playstore link of your app otherwise your installed app
String your_apppackagename="com.app.testing";
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (applicationInfo == null) {
// not installed it will open your app directly on playstore
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
} else {
// Installed
Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
startActivity( LaunchIntent );
}
A lot of the comments answer most of your questions, but I mainly wanted to contribute to this question:
Is there a way in which the behavior of the backtick actually differs from that of a single quote?
A difference I've noticed for template strings is the disability to set one as an object property. More information in this post; an interesting quote from the accepted answer:
Template strings are expressions, not literals1.
But basically, if you ever wanted to use it as an object property you'd have to use it wrapped with square brackets.
// Throws error
const object = {`templateString`: true};
// Works
const object = {[`templateString`]: true};
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
If you have local array with options (received by ajax call), i think you should use data
parameter as function returning results for select box:
var pills = [{id:0, text: "red"}, {id:1, text: "blue"}];
$('#selectpill').select2({
placeholder: "Select a pill",
data: function() { return {results: pills}; }
});
$('#uppercase').click(function() {
$.each(pills, function(idx, val) {
pills[idx].text = val.text.toUpperCase();
});
});
$('#newresults').click(function() {
pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});
FIDDLE: http://jsfiddle.net/RVnfn/576/
In case if you customize select2 interface with buttons, just call updateResults
(this method not allowed to call from outsite of select2 object but you can add it to allowedMethods
array in select2 if you need to) method after updateting data array(pills in example).
Custom data adapter with additional updateOptions
(its unclear why original ArrayAdapter
lacks this functionality) method can be used to dynamically update options list (all options in this example):
$.fn.select2.amd.define('select2/data/customAdapter',
['select2/data/array', 'select2/utils'],
function (ArrayAdapter, Utils) {
function CustomDataAdapter ($element, options) {
CustomDataAdapter.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomDataAdapter, ArrayAdapter);
CustomDataAdapter.prototype.updateOptions = function (data) {
this.$element.find('option').remove(); // remove all options
this.addOptions(this.convertToOptions(data));
}
return CustomDataAdapter;
}
);
var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');
var sel = $('select').select2({
dataAdapter: customAdapter,
data: pills
});
$('#uppercase').click(function() {
$.each(pills, function(idx, val) {
pills[idx].text = val.text.toUpperCase();
});
sel.data('select2').dataAdapter.updateOptions(pills);
});
FIDDLE: https://jsfiddle.net/xu48n36c/1/
in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)
docs: https://select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax-be-used
Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.
$('select').select2({
ajax: {
transport: function(params, success, failure) {
var items = pills;
// fitering if params.data.q available
if (params.data && params.data.q) {
items = items.filter(function(item) {
return new RegExp(params.data.q).test(item.text);
});
}
var promise = new Promise(function(resolve, reject) {
resolve({results: items});
});
promise.then(success);
promise.catch(failure);
}
}
});
BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.
FIDDLE: https://jsfiddle.net/xu48n36c/3/
You can use:
npm show {pkg} version
(so npm show express version
will return now 3.0.0rc3
).
install PIL using the command "sudo apt-get install python-imaging" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values
import PIL
import Image
FILENAME='fn.gif' #image can be in gif jpeg or png format
im=Image.open(FILENAME).convert('RGB')
pix=im.load()
w=im.size[0]
h=im.size[1]
for i in range(w):
for j in range(h):
print pix[i,j]
Not tested but you can try something like this :
Declare @count as int
Set @count=1
Declare @inputFile varchar(max)
Declare @Sample Table
(id int,filepath varchar(max) ,Isexists char(3))
while @count<(select max(id) from yourTable)
BEGIN
Set @inputFile =(Select filepath from yourTable where id=@count)
DECLARE @isExists INT
exec master.dbo.xp_fileexist @inputFile ,
@isExists OUTPUT
insert into @Sample
Select @count,@inputFile ,case @isExists
when 1 then 'Yes'
else 'No'
end as isExists
set @count=@count+1
END
ArrayAdapter<String>
should work.
i.e.:
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,
spinnerArray); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
One way to do that is to set the cascade option on you "One" side of relationship:
class Employee {
//
@OneToMany(cascade = {CascadeType.PERSIST})
private Set<Vehicles> vehicles = new HashSet<Vehicles>();
//
}
by this, when you call
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
it will save the vehicles too.
Usually I prefer to use this extension:
Swift 3.x and Swift 4.0:
extension FileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
return paths[0]
}
}
Swift 2.x:
extension NSFileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
}