A simple function that blits an image front
onto an image back
and returns the result. It works with both 3 and 4-channel images and deals with the alpha channel. Overlaps are handled as well.
The output image has the same size as back, but always 4 channels.
The output alpha channel is given by (u+v)/(1+uv) where u,v are the alpha channels of the front and back image and -1 <= u,v <= 1. Where there is no overlap with front, the alpha value from back is taken.
import cv2
def merge_image(back, front, x,y):
# convert to rgba
if back.shape[2] == 3:
back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
if front.shape[2] == 3:
front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)
# crop the overlay from both images
bh,bw = back.shape[:2]
fh,fw = front.shape[:2]
x1, x2 = max(x, 0), min(x+fw, bw)
y1, y2 = max(y, 0), min(y+fh, bh)
front_cropped = front[y1-y:y2-y, x1-x:x2-x]
back_cropped = back[y1:y2, x1:x2]
alpha_front = front_cropped[:,:,3:4] / 255
alpha_back = back_cropped[:,:,3:4] / 255
# replace an area in result with overlay
result = back.copy()
print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + alpha_back * back_cropped[:,:,:3]
result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255
return result
In windows , [Similar scenario]
I was facing the same problem But It was during requesting for Certificate Signing Request.
I did the below , It Worked for me.
Once OpenSSL installed, Ran command prompt as administrator after the system reboot.[for the best I did both.. run as admin and system reboot]
did, 1.[Error Case]
C:\OpenSSL-Win64\bin>openssl req -new -key server.key -out server.csr
WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf AND Unable to load config info from C:\OpenSSL-Win64\bin\openssl.cnf
2.[Worked with Warning]
C:\OpenSSL-Win64\bin> openssl req -new -key server.key -out server.csr -config C:\OpenSSL-Win64\bin\openssl.cfg
[Warning message]: WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf
But prompted me for the Pass Phrase for server.key It worked for me.
I referred,This link for my assistance.
Thank you.
Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it.
I don't see any up to date info listed here, so here goes:
To answer this question now, 2 favicons will not do it if you want your icon to look great everywhere. See the sizes below:
16 x 16 – Standard size for browsers
24 x 24 – IE9 pinned site size for user interface
32 x 32 – IE new page tab, Windows 7+ taskbar button, Safari Reading List sidebar
48 x 48 – Windows site
57 x 57 – iPod touch, iPhone up to 3G
60 x 60 – iPhone touch up to iOS7
64 x 64 – Windows site, Safari Reader List sidebar in HiDPI/Retina
70 x 70 – Win 8.1 Metro tile
72 x 72 – iPad touch up to iOS6
76 x 76 – iOS7
96 x 96 – GoogleTV
114 x 114 – iPhone retina touch up to iOS6
120 x 120 – iPhone retina touch iOS7
128 x 128 – Chrome Web Store app, Android
144 x 144 – IE10 Metro tile for pinned site, iPad retina up to iOS6
150 x 150 – Win 8.1 Metro tile
152 x 152 – iPad retina touch iOS7
196 x 196 – Android Chrome
310 x 150 – Win 8.1 wide Metro tile
310 x 310 – Win 8.1 Metro tile
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.
If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address
.
Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:
wordpress:
image: wordpress:4.1
stateful: true
ports:
- 80:80
links:
- mysql:wordpress-mysql
environment:
- WORDPRESS_DB_HOST=wordpress-mysql.kontena.local
- WORDPRESS_DB_PASSWORD=secret
mysql:
image: mariadb:5.5
stateful: true
environment:
- MYSQL_ROOT_PASSWORD=secret
Here is one way of removing a duplicate object.
The blog class should be something like this or similar, like proper pojo
public class Blog {
private String title;
private String author;
private String url;
private String description;
private int hashCode;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object obj) {
Blog blog = (Blog)obj;
if(title.equals(blog.title) &&
author.equals(blog.author) &&
url.equals(blog.url) &&
description.equals(blog.description))
{
hashCode = blog.hashCode;
return true;
}else{
hashCode = super.hashCode();
return false;
}
}
}
And use it like this to remove duplicates objects. The key data structure here is the Set and LinkedHashSet. It will remove duplicates and also keep order of entry
Blog blog1 = new Blog();
blog1.setTitle("Game of Thrones");
blog1.setAuthor("HBO");
blog1.setDescription("The best TV show in the US");
blog1.setUrl("www.hbonow.com/gameofthrones");
Blog blog2 = new Blog();
blog2.setTitle("Game of Thrones");
blog2.setAuthor("HBO");
blog2.setDescription("The best TV show in the US");
blog2.setUrl("www.hbonow.com/gameofthrones");
Blog blog3 = new Blog();
blog3.setTitle("Ray Donovan");
blog3.setAuthor("Showtime");
blog3.setDescription("The second best TV show in the US");
blog3.setUrl("www.showtime.com/raydonovan");
ArrayList<Blog> listOfBlogs = new ArrayList<>();
listOfBlogs.add(blog1);
listOfBlogs.add(blog2);
listOfBlogs.add(blog3);
Set<Blog> setOfBlogs = new LinkedHashSet<>(listOfBlogs);
listOfBlogs.clear();
listOfBlogs.addAll(setOfBlogs);
for(int i=0;i<listOfBlogs.size();i++)
System.out.println(listOfBlogs.get(i).getTitle());
Running this should print
Game of Thrones
Ray Donovan
The second one will be removed because it is a duplicate of the first object.
Why not just use rm -rf /some/dir
? That will remove the directory if it's present, otherwise do nothing. Unlike rm -r /some/dir
this flavor of the command won't crash if the folder doesn't exist.
If you have the numpy
package:
In [16]: x = [1,2,3,4]
...: import numpy
...: numpy.average(x)
Out[16]: 2.5
For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:
extension=php_xmlrpc.dll
Then simply install php7.0-xml:
sudo apt-get install php7.0-xml
And restart PHP:
sudo service php7.0-fpm restart
And restart Apache:
sudo service apache2 restart
If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).
What does your routeTemplate look like for this case?
You posted this url:
/offers/40D5E19D-0CD5-4FBD-92F8-43FDBB475333/prices/
In order for this to work I would expect a routing like this in your WebApiConfig
:
routeTemplate: {controller}/{offerId}/prices/
Other assumptions are:
- your controller is called OffersController
.
- the JSON object you are passing in the request body is of type OfferPriceParameters
(not any derived type)
- you don't have any other methods on the controller that could interfere with this one (if you do, try commenting them out and see what happens)
And as Filip mentioned it would help your questions if you started accepting some answers as 'accept rate of 0%' might make people think that they are wasting their time
The event
attribute of <f:ajax>
can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on*
attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText>
component which renders <input type="text">
lists the following on*
attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):
blur
change
click
dblclick
focus
keydown
keypress
keyup
mousedown
mousemove
mouseout
mouseover
mouseup
select
Additionally, JSF has two more special event names for EditableValueHolder
and ActionSource
components, the real HTML DOM event being rendered depends on the component type:
valueChange
(will render as change
on text/select inputs and as click
on radio/checkbox inputs)action
(will render as click
on command links/buttons)The above two are the default events for the components in question.
Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange
or action
events, such as PrimeFaces <p:ajax>
which supports among others tabChange
, itemSelect
, itemUnselect
, dateSelect
, page
, sort
, filter
, close
, etc depending on the parent <p:xxx>
component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.
There is issue of 31st and 28th Feb with getDate()
I use this function getTime
and 24*60*60*1000 = 86400000
var dateWith31 = new Date("2017-08-31");_x000D_
var dateWith29 = new Date("2016-02-29");_x000D_
_x000D_
var amountToIncreaseWith = 1; //Edit this number to required input_x000D_
_x000D_
console.log(incrementDate(dateWith31,amountToIncreaseWith));_x000D_
console.log(incrementDate(dateWith29,amountToIncreaseWith));_x000D_
_x000D_
function incrementDate(dateInput,increment) {_x000D_
var dateFormatTotime = new Date(dateInput);_x000D_
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));_x000D_
return increasedDate;_x000D_
}
_x000D_
The range function in python has the syntax:
range(start, end, step)
It has the same syntax as python lists where the start is inclusive but the end is exclusive.
So if you want to count from 5 to 1, you would use range(5,0,-1)
and if you wanted to count from last
to posn
you would use range(last, posn - 1, -1)
.
If you want to save the ASCII value of the character: (I did this in BASH and it worked)
{
char="A"
testing=$( printf "%d" "'${char}" )
echo $testing}
output: 65
select date 'now()' - date '1955-12-15';
Here is the simple query which calculates total no of days.
First check the value is checked
$("#ans").find("checkbox").each(function(){
if ($(this).prop('checked')==true){
var id = $(this).val()
}
});
Else set the 0 value
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
cp
has multiple usages:
$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
or: cp [OPTION]... SOURCE... DIRECTORY
or: cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
@AndyRoss's answer works for the
cp SOURCE DEST
style of cp
, but does the wrong thing if you use the
cp SOURCE... DIRECTORY/
style of cp
.
I think that "DEST" is ambiguous without a trailing slash in this usage (i.e. where the target directory doesn't yet exist), which is perhaps why cp
has never added an option for this.
So here's my version of this function which enforces a trailing slash on the dest dir:
cp-p() {
last=${@: -1}
if [[ $# -ge 2 && "$last" == */ ]] ; then
# cp SOURCE... DEST/
mkdir -p "$last" && cp "$@"
else
echo "cp-p: (copy, creating parent dirs)"
echo "cp-p: Usage: cp-p SOURCE... DEST/"
fi
}
Assuming the renderDetailItem method has the following signature...
(rowData, sectionID, rowID, highlightRow)
Try doing this...
<TouchableHighlight key={rowID} underlayColor='#dddddd'>
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
Usinge the file
argument in the print
function, you can have different files per print:
print('Redirect output to file', file=open('/tmp/example.log', 'w'))
There is no DATEDIFF()
function in Oracle. On Oracle, it is an arithmetic issue
select DATE1-DATE2 from table
You may be able to use the aggregate
(or agg
) function to concatenate the values. (Untested code)
df.groupby('A')['B'].agg(lambda col: ''.join(col))
curlPost('google.com', [
'username' => 'admin',
'password' => '12345',
]);
function curlPost($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error !== '') {
throw new \Exception($error);
}
return $response;
}
Swift 4 without NSString.
extension String {
func matches(regex: String) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) else { return [] }
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, self.count))
return matches.map { match in
return String(self[Range(match.range, in: self)!])
}
}
}
Try to load your scripts in Head section.
Moreover, it will be better if you define your scripts under some call like: document.ready
, if you defined these scripts in body section
map
may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.
An example of the tiny speed advantage of map when using exactly the same function:
$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop
An example of how performance comparison gets completely reversed when map needs a lambda:
$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop
Check the output on the server environment from which jupyter notebook
was launched if you can. You'll probably find error messages and print()
results.
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
It will be increasing because you have a need for temporary storage space, possibly due to a cartesian product or a large sort operation.
The dynamic performance view V$TEMPSEG_USAGE
will help diagnose the cause.
Here's an example that you could use :
var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
dddd : Full day Name
Do : day of the Month
MMMM : Full Month name
YYYY : 4 digits Year
For more informations :
The main problem is that:
in a constructor, the injection of the dependencies has not yet occurred*
*obviously excluding Constructor Injection
Real-world example:
public class Foo {
@Inject
Logger LOG;
@PostConstruct
public void fooInit(){
LOG.info("This will be printed; LOG has already been injected");
}
public Foo() {
LOG.info("This will NOT be printed, LOG is still null");
// NullPointerException will be thrown here
}
}
IMPORTANT:
@PostConstruct
and @PreDestroy
have been completely removed in Java 11.
To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
from Google
An .axd file is a HTTP Handler file. There are two types of .axd files.
These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.
Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere
And ofcourse it is necessary
Isn't easier than doing like :
1- Install jquery in your project:
yarn add jquery
2- Import jquery and start playing with DOM:
import $ from 'jquery';
A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =
:
HOME=c
An environment variable is a regular variable that has been marked for export to the environment.
export HOME
HOME=c
You can combine the assignment with the export
statement.
export HOME=c
For performance, a numpy solution inspired by Knuth, (p22) :
from numpy import empty, uint8
from math import factorial
def perms(n):
f = 1
p = empty((2*n-1, factorial(n)), uint8)
for i in range(n):
p[i, :f] = i
p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs
for j in range(i):
p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs
f = f*(i+1)
return p[:n, :]
Copying large blocs of memory saves time -
it's 20x faster than list(itertools.permutations(range(n))
:
In [1]: %timeit -n10 list(permutations(range(10)))
10 loops, best of 3: 815 ms per loop
In [2]: %timeit -n100 perms(10)
100 loops, best of 3: 40 ms per loop
What implicit conversions are going on here,
i will be converted to an unsigned integer.
and is this code safe for all values of u and i?
Safe in the sense of being well-defined yes (see https://stackoverflow.com/a/50632/5083516 ).
The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2's complement representation of the number.
Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the "real result".
division and casting to larger unsigned integer types will have well-defined results but those results will not be 2's complement representations of the "real result".
(Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)
While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the "real result" when converting a 2's complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don't use 2's complement for signed integers.
https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation https://msdn.microsoft.com/en-us/library/0eex498h.aspx
I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:
#define DIM 3
#define WORMS 50000 //gusanos
void halla_centros_V000(double CENW[][DIM])
{
CENW[i][j]=...
...
}
int main()
{
double *CENW_MEM=new double[WORMS*DIM];
double (*CENW)[DIM];
CENW=(double (*)[3]) &CENW_MEM[0];
halla_centros_V000(CENW);
delete[] CENW_MEM;
}
You could also use countplot
from seaborn
. This package builds on pandas
to create a high level plotting interface. It gives you good styling and correct axis labels for free.
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
It also supports coloring the bars in the right color with a little trick
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
You could take your entire server-side model and turn it into a Javascript object by doing the following:
var model = @Html.Raw(Json.Encode(Model));
In your case if you just want the FloorPlanSettings object, simply pass the Encode
method that property:
var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
<?php
// Sapan Mohanty
// Skype:sapan.mohannty
//***********************************
$oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
$NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
echo mysql_error();
mysql_select_db('OLDDBNAME', $oldData );
mysql_select_db('NEWDBNAME', $NewData );
$getAllTablesName = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
$getAllTablesNameExe = mysql_query($getAllTablesName);
//echo mysql_error();
while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {
$oldDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
$oldDataCountResult = mysql_fetch_object($oldDataCount);
$newDataCount = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
$newDataCountResult = mysql_fetch_object($newDataCount);
if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
echo "<br/><b>" . $dataTableName->table_name . "</b>";
echo " | Old: " . $oldDataCountResult->noOfRecord;
echo " | New: " . $newDataCountResult->noOfRecord;
if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
echo " | <font color='green'>*</font>";
} else {
echo " | <font color='red'>*</font>";
}
echo "<br/>----------------------------------------";
}
}
?>
@Override
protected void onPostExecute(final Boolean success) {
mProgressDialog.dismiss();
mProgressDialog = null;
setting the value null works for me
Just got the same issue after installing Developer Tools Microsoft ASP.NET and Web Tools 2015 (Beta7). I tried to reinstall ASP.NET Project Templates but it didn't help.
While looking into "Add / remove programs" -> "Visual 2015" -> "Modify" , I found the "Web developer tools" unchecked. This SO answer helps me to figure this.
After reinstalling this, everything reappears
You can use Sort
List<string> ListaServizi = new List<string>() { };
ListaServizi.Sort();
Do you have a typo in your .h? I once came across this error when i had the method properly called in my main, but with a typo in the .h/.cpp (a "g" vs a "q" in the method name, which made it kinda difficult to spot). It falls under the "copy/paste error" category.
Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.
For example
Write into DB
String stringToBeInserted = jsonObject.toString();
//and insert this string into DB
Read from DB
String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);
There's another explanation for why .env
doesn't exist, and it happens when you move all the Laravel files.
Take this workflow: in your project directory you do laravel new whatever
, Laravel is installed in whatever
, you do mv * ..
to move all the files to your project folder, and you remove whatever
. The problem is, mv
doesn't move hidden files by default, so the .env
files are left behind, and are removed!
Surely you just need:
double seconds = milliseconds / 1000.0;
There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0
(as a double
literal) forces. (I'm assuming your milliseconds
value is an integer of some form.)
Note that as usual with double
, you may not be able to represent the result exactly. Consider using BigDecimal
if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double
is probably appropriate, but...)
This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).
I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.
Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.
Ok uninstall the app, but we admit that the data not must be lost? This can be resolve, upgrading versionCode and versionName and try the application in "Release" mode.
For example, this is important when we want to try the migration of our Database. We can compare the our application on play store with actual application not release yet.
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
One more point I want to add. In spring-servlet.xml
we include component scan for Controller package.
In following example we include filter annotation for controller package.
<!-- Scans for annotated @Controllers in the classpath -->
<context:component-scan base-package="org.test.web" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In applicationcontext.xml
we add filter for remaining package excluding controller.
<context:component-scan base-package="org.test">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
In my case this turned out to be a bad USB hub.
The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.
The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino
Here is a simple interpretation about your problem:
== (equal to) used to evaluate arithmetic expression
where as
equals() method used to compare string
Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.
If you are looking for a command-line based solution, you can ignore my answer. I am gonna suggest you to use GitKraken. It's an extraordinary git UI client. It shows the Git tree on the homepage. You can just look at them and know what is going on with the project. Just select a specific commit, right-click on it and select the option 'Create a branch here'. It will give you a text box to enter the branch name. Enter branch name, select 'OK' and you are set. It's really very easy to use.
I had the same problem. All i did was - From the pom.xml file i deleted the dependency for junit 3.8 and added a new dependency for junit 4.8. Then i did maven clean and maven install. It did the trick. To verify , after maven install i went project->properties-build path->maven dependencies and saw that now the junit 3.8 jar is gone !, instead junit 4.8 jar is listed. cool!!. Now my test runs like a charm.. Hope this helps somehow..
I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.
Best of luck!
Use this code.
driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");
For all those still affected by this.
I've been getting the error...
OLEDB error "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."
...as described by the OP, Shailesh Sahu.
I have 64bit Windows 7.
My problem is within PowerShell scripts, but is using a connection string, similar to the OP's post, so hopefully my findings can be applied to C#, PowerShell and any other language relying on the "Microsoft.ACE.OLEDB" driver.
I followed instructions on this MS forum thread: http://goo.gl/h73RmI
I first tried installing the 64bit version, then installing the 32bit version of the AccessDatabaseEngine.exe from this page http://www.microsoft.com/en-us/download/details.aspx?id=13255
But still no joy.
I then ran the code below in PowerShell (from SQL Panda's site http://goo.gl/A3Hu96)
(New-Object system.data.oledb.oledbenumerator).GetElements() | select SOURCES_NAME, SOURCES_DESCRIPTION
...which gave me this result (I've removed other data sources for brevity)...
SOURCES_NAME SOURCES_DESCRIPTION
------------ -------------------
Microsoft.ACE.OLEDB.15.0 Microsoft Office 15.0 Access Database Engine OLE DB Provider
As you can see, I have Microsoft.ACE.OLEDB.15.0 (fifteen) not Microsoft.ACE.OLEDB.12.0 (twelve)
So, I amended my connection string to 15 and it worked.
So, a quick PowerShell snippet to demonstrate how to soft-code the version...
$AceVersion = ((New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB*" } | Sort-Object SOURCES_NAME -Descending | Select-Object -First 1 SOURCES_NAME).SOURCES_NAME
$connString = "Provider=$AceVersion;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=NO`";"
amended to pick the latest ACE version, if more than one
Hopefully, anyone finding this can now check to see what OLEDB version is installed and use the appropriate version number.
None of the above approaches work in iOS 4.0
The pickerView's height is no longer re-sizable. There is a message which gets dumped to console if you attempt to change the frame of a picker in 4.0:
-[UIPickerView setFrame:]: invalid height value 66.0 pinned to 162.0
I ended up doing something quite radical to get the effect of a smaller picker which works in both OS 3.xx and OS 4.0. I left the picker to be whatever size the SDK decides it should be and instead made a cut-through transparent window on my background image through which the picker becomes visible. Then simply placed the picker behind (Z Order wise) my background UIImageView so that only a part of the picker is visible which is dictated by the transparent window in my background.
Shift+Ctrl+C if you are in graphical mode of Linux, but first you need to select what you need to copy.
Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.
Build pattern emphasizes on complexity of creating object (solved by "steps")
Abstract pattern emphasizes "just" on "abstraction" of (multiple but related) objects.
QueryTypes is the canonical answer as of EF Core 2.1, but there is another way I have used when migrating from a database first approach (the view is already created in the database):
Sometimes PostgreSQL fails to make the best choice of indexes for a particular condition. As an example, suppose there is a transactions table with several million rows, of which there are several hundred for any given day, and the table has four indexes: transaction_id, client_id, date, and description. You want to run the following query:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description = 'Refund'
GROUP BY client_id
PostgreSQL may choose to use the index transactions_description_idx instead of transactions_date_idx, which may lead to the query taking several minutes instead of less than one second. If this is the case, you can force using the index on date by fudging the condition like this:
SELECT client_id, SUM(amount)
FROM transactions
WHERE date >= 'yesterday'::timestamp AND date < 'today'::timestamp AND
description||'' = 'Refund'
GROUP BY client_id
Also, VB.NET has much better xml parsing support via the compiler than C#. If you have the option and the desire, check it out.
You can use below code to find out principal (user email who logged in)
org.opensaml.saml2.core.impl.NameIDImpl principal =
(NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String email = principal.getValue();
This code is written on top of SAML.
I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt
Reference link: https://www.npmjs.com/package/node-webtokens
jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
jwt.parse(token).verify(pwd, (error, parsedToken) => {
// other statements
});
});
This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.
A simple example which I have created: https://github.com/hansiemithun/jwe-example
Using only virtualenv (without virtualenvwrapper), setting environment variables is easy through the activate
script you sourcing in order to activate the virtualenv.
Run:
nano YOUR_ENV/bin/activate
Add the environment variables to the end of the file like this:
export KEY=VALUE
You can also set a similar hook to unset the environment variable as suggested by Danilo Bargen in his great answer above if you need.
You can make a template of templates too, and reach private variable.
var a= {e:10, gy:'sfdsad'}; //global object
console.log(`e is ${a.e} and gy is ${a.gy}`);
//e is 10 and gy is sfdsad
var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}
console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad
backtick( b ); // use fonction's variable
//e is 20 and gy is fghj
function backtick( temp ) {
var a= {e:20, gy:'fghj'}; // local object
console.log( eval(`\`${temp}\``) );
}
You can certainly us the a Select Agregation statement as Postulated by Ben James, However This will result in a view with as many columns as you have tables. An alternate method may be as follows:
SELECT COUNT(user_table.id) AS TableCount,'user_table' AS TableSource FROM user_table
UNION SELECT COUNT(cat_table.id) AS TableCount,'cat_table' AS TableSource FROM cat_table
UNION SELECT COUNT(course_table.id) AS TableCount, 'course_table' AS TableSource From course_table;
The Nice thing about an approch like this is that you can explicitly write the Union statements and generate a view or create a temp table to hold values that are added consecutively from a Proc cals using variables in place of your table names. I tend to go more with the latter, but it really depends on personal preference and application. If you are sure the tables will never change, you want the data in a single row format, and you will not be adding tables. stick with Ben James' solution. Otherwise I'd advise flexibility, you can always hack a cross tab struc.
Extend to Danny W. Adair Answer, to get month also
def calculate_age(b):
t = date.today()
c = ((t.month, t.day) < (b.month, b.day))
c2 = (t.day< b.day)
return t.year - b.year - c,c*12+t.month-b.month-c2
If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from
GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES,
to draw lines,
GL_POINTS
(if you need to draw only vertices), or
GL_TRIANGLE_STRIP
, GL_TRIANGLE_FAN
, and GL_TRIANGLES
to draw filled triangles
as first argument to your
glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)
or
glDrawArrays(GLenum mode, GLint first, GLsizei count)
calls.
You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.
Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.
You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.
You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.
Slightly tweaking @Mathieu Viales's answer, here's a .NET Standard compatible snippet using the new System.Text.Json serializer thus eliminating the dependency on Newtonsoft.Json.
using System.Text.Json;
builder.Entity<YourEntity>().Property(p => p.Strings)
.HasConversion(
v => JsonSerializer.Serialize(v, default),
v => JsonSerializer.Deserialize<List<string>>(v, default));
Note that while the second argument in both Serialize()
and Deserialize()
is typically optional, you'll get an error:
An expression tree may not contain a call or invocation that uses optional arguments
Explicitly setting that to the default (null) for each clears that up.
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
For loading weights, you need to have a model first. It must be:
existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):
model.save_model('filename')
model = load_model('filename')
Like said previously, you can choose between a lot of choices, take a look at all those choices: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis
What I suggest is to find your best combination: MySQL + Memcache is really great if you need ACID and you want to join some tables MongoDB + Redis is perfect for document store Neo4J is perfect for graph database
What i do: I start with MySQl + Memcache because I'm use to, then I start using others database framework. In a single project, you can combine MySQL and MongoDB for instance !
Dim counties As New List(Of County)
Dim dtCounties As DataTable
dtCounties = _combinedRefRepository.Get_Counties()
If dtCounties.Rows.Count <> 0 Then
For Each row As DataRow In dtCounties.Rows
Dim county As New County
county.CountyId = row.Item(0).ToString()
county.CountyName = row.Item(1).ToString().ToUpper()
counties.Add(county)
Next
dtCounties.Dispose()
End If
So I've been using this and it has worked very well: - it works more like a DROP IF EXISTS but gets the job done
DECLARE
VE_TABLENOTEXISTS EXCEPTION;
PRAGMA EXCEPTION_INIT(VE_TABLENOTEXISTS, -942);
PROCEDURE DROPTABLE(PIS_TABLENAME IN VARCHAR2) IS
VS_DYNAMICDROPTABLESQL VARCHAR2(1024);
BEGIN
VS_DYNAMICDROPTABLESQL := 'DROP TABLE ' || PIS_TABLENAME;
EXECUTE IMMEDIATE VS_DYNAMICDROPTABLESQL;
EXCEPTION
WHEN VE_TABLENOTEXISTS THEN
DBMS_OUTPUT.PUT_LINE(PIS_TABLENAME || ' NOT EXIST, SKIPPING....');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END DROPTABLE;
BEGIN
DROPTABLE('YOUR_TABLE_HERE');
END DROPTABLE;
/
Hope this helps Also reference: PLS-00103 Error in PL/SQL Developer
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
The most obvious to me would be:
np.any(my_array[:, 0] == value)
You have to be specific about the columns you are selecting. If your user
table had four columns id, name, username, opted_in
you must select exactly those four columns from the query. The syntax looks like:
INSERT INTO user (id, name, username, opted_in)
SELECT id, name, username, opted_in
FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
However, there does not appear to be any reason to join against user_permission
here, since none of the columns from that table would be inserted into user
. In fact, this INSERT
seems bound to fail with primary key uniqueness violations.
MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT
statements in your code, using the last insert id from the first query, or create an AFTER INSERT
trigger on the primary table.
INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)
Or using a trigger:
CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END
You can as well do:
git checkout --theirs /path/to/file
to keep the remote file, and:
git checkout --ours /path/to/file
to keep local file.
Then git add
them and everything is done.
Edition:
Keep in mind that this is for a merge
scenario. During a rebase
--theirs
refers to the branch where you've been working.
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
Check for the existence by retrieving its object_id:
if object_id('tempdb..##clients_keyword') is not null
drop table ##clients_keyword
I used the below code from this website, it works great https://www.freecodecamp.org/news/how-to-redirect-http-to-https-using-htaccess/
RewriteEngine On_x000D_
RewriteCond %{SERVER_PORT} 80_x000D_
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
_x000D_
Hope it helps
RanRag has already answered it for your specific question.
However, more generally, what you are doing with
if [[ "$string" =~ ^hello ]]
is a regex match. To do the same in Python, you would do:
import re
if re.match(r'^hello', somestring):
# do stuff
Obviously, in this case, somestring.startswith('hello')
is better.
I don't believe there is a way to ignore a file in the repository. We often run into this with web.config and other configuration files.
Although not perfect, the solution I most often see and use is to have .default file and an nant task to create local copies.
For example, in the repo is a file called web.config.default
that has default values. Then create a nant task that will rename all the web.config.default
files to web.config
that can then be customized to local values. This task should be called when a new working copy is retrieved or a build is run.
You'll also need to ignore the web.config
file that is created so that it isn't committed to the repository.
The Linux kernel is mostly written in C (and a bit of assembly language, I'd imagine), but some of the important userspace utilities (programs) are shell scripts written in the Bash scripting language. Beyond that, it's sort of hard to define "Linux" since you basically build a Linux system by picking bits and pieces you want and putting them together, and depending on what an individual Linux user wants, you can get pretty much any language involved. (As Paul said, Python and C++ play important roles)
I was getting this error because I was starting from http://mysite.com
, but had specified http://WWW.mysite.com
in my Facebook settings - the www mattered... I ended up solving by using .httpaccess to always kill the "www", and pointing FB to http://mysite.com
worst. subdomain. ever. :u)
You could analyse the user agent ($_SERVER['HTTP_USER_AGENT']
) or compare the client’s IP address ($_SERVER['REMOTE_ADDR']
) with a list of IP addresses of search engine bots.
I shall not repeat the same answer on Copy-on-Write. I think Andrew's answer and Charlie's answer have already made it very clear. I will give you an example from OS world, just to mention how widely this concept is used.
We can use fork()
or vfork()
to create a new process. vfork follows the concept of copy-on-write. For example, the child process created by vfork will share the data and code segment with the parent process. This speeds up the forking time. It is expected to use vfork if you are performing exec followed by vfork. So vfork will create the child process which will share data and code segment with its parent but when we call exec, it will load up the image of a new executable in the address space of the child process.
For latest laravel version also check your version because I was also facing this error but after update latest php version, I got rid from this error.
Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:
def Recomputate \
(
TheRotaryGyrator,
# the rotary gyrator to operate on
Computrons,
# the computrons to perform the recomputation with
Forthwith,
# whether to recomputate forthwith or at one's leisure
) :
# recomputates the specified rotary gyrator with
# the desired computrons.
...
#end Recomputate
You can’t do this sort of thing with docstrings.
When doing django ranges with a filter make sure you know the difference between using a date object vs a datetime object. __range is inclusive on dates but if you use a datetime object for the end date it will not include the entries for that day if the time is not set.
startdate = date.today()
enddate = startdate + timedelta(days=6)
Sample.objects.filter(date__range=[startdate, enddate])
returns all entries from startdate to enddate including entries on those dates. Bad example since this is returning entries a week into the future, but you get the drift.
startdate = datetime.today()
enddate = startdate + timedelta(days=6)
Sample.objects.filter(date__range=[startdate, enddate])
will be missing 24 hours worth of entries depending on what the time for the date fields is set to.
I want to point out other case not reflected in any of the answers. I have a Dictionary<Tkey,TValue>
shared in a multi threaded app, which uses a ReaderWriterLockSlim
to protect the read and write operations. This is a reading method that throws the exception:
public IEnumerable<Data> GetInfo()
{
List<Data> info = null;
_cacheLock.EnterReadLock();
try
{
info = _cache.Values.SelectMany(ce => ce.Data); // Ad .Tolist() to avoid exc.
}
finally
{
_cacheLock.ExitReadLock();
}
return info;
}
In general, it works fine, but from time to time I get the exception. The problem is a subtlety of LINQ: this code returns an IEnumerable<Info>
, which is still not enumerated after leaving the section protected by the lock. So, it can be changed by other threads before being enumerated, leading to the exception. The solution is to force the enumeration, for example with .ToList()
as shown in the comment. In this way, the enumerable is already enumerated before leaving the protected section.
So, if using LINQ in a multi-threaded application, be aware to always materialize the queries before leaving the protected regions.
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
This works in all pc or phones browsers, expanding on the top answers. One can build a more complex event object window["scroll_evt"] then call it in the handleScroll() function. This one triggers for 2 concurrent conditions, if certain delay has elapsed or certain delta is passed to eliminate some unwanted triggers.
window["scroll_evt"]={"delta":0,"delay":0,"direction":0,"time":Date.now(),"pos":$(window).scrollTop(),"min_delta":120,"min_delay":10};
$(window).scroll(function() {
var currentScroll = $(this).scrollTop();
var currentTime = Date.now();
var boolRun=(window["scroll_evt"]["min_delay"]>0)?(Math.abs(currentTime - window["scroll_evt"]["time"])>window["scroll_evt"]["min_delay"]):false;
boolRun = boolRun && ((window["scroll_evt"]["min_delta"]>0)?(Math.abs(currentScroll - window["scroll_evt"]["pos"])>window["scroll_evt"]["min_delta"]):false);
if(boolRun){
window["scroll_evt"]["delta"] = currentScroll - window["scroll_evt"]["pos"];
window["scroll_evt"]["direction"] = window["scroll_evt"]["delta"]>0?'down':'up';
window["scroll_evt"]["delay"] =currentTime - window["scroll_evt"]["time"];//in milisecs!!!
window["scroll_evt"]["pos"] = currentScroll;
window["scroll_evt"]["time"] = currentTime;
handleScroll();
}
});
function handleScroll(){
event.stopPropagation();
//alert(window["scroll_evt"]["direction"]);
console.log(window["scroll_evt"]);
}
You can just use the built-in R functions tapply
with length
tapply(myvec$order_no, myvec$name, FUN = function(x) length(unique(x)))
The only correct way that I could do page refresh was through JavaScript, many of top .NET answers failed for me.
Response.Write("<script type='text/javascript'> setTimeout('location.reload(true); ', timeout);</script>");
Put the above code in button click event or anywhere you want to force page refresh.
Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff
statement unnecessary.
Using the data from Dinre's example:
In base R:
cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)
Using the dplyr package:
library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))
To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.
You can do this by using following code.
$('#dropDownId').val();
If you want to get the selected value from the select list`s options. This will do the trick.
$('#dropDownId option:selected').text();
Delete all local tags and get the list of remote tags:
git tag -l | xargs git tag -d
git fetch
Remove all remote tags
git tag -l | xargs -n 1 git push --delete origin
Clean up local tags
git tag -l | xargs git tag -d
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
@Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
Try the following. It works for me.
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
am.restartPackage(componentInfo.getPackageName());
If I get you right, you need ..\..\src
I hate to answer my own questions, but I did finally find a solution that actually works (using socket communication between services may fix the problem, but it creates even more problems). Since our database is legacy, it merely required Microsoft.ACE.OLEDB.12.0
in the connection string. It turns out that this was also included in Office 2007 (and MSDE 2007), where there is only a 32-bit version available. So, instead of installing MSDE 2010 32-bit, we install MSDE 2007, and it works just fine. Other applications can then install 64-bit MSDE 2010 (or 64-bit Office 2010), and it does not conflict with our application.
Thus far, it appears this is an acceptable solution for all Windows OS environments.
This one drove me crazy for Xamarin.
I ran into this with a ViewPager implementation for TabLayout WITHIN a Fragment, that is itself implemented in the DrawerLayout:
- DrawerLayout
- DrawerFragment
- TabLayout
- TabViewPager
- TabViewPagerFragments
So you have to implement the following code in your DrawerFragment. Be aware to choose the correct FragmentManager-Path. Because you might have two different FragmentManager References:
--> Choose the one you use. If you want to make use of the ChildFragmentManager, you had to use the class declaration Android.App.FragmentManager for your ViewPager!
Android.Support.V4.App.FragmentManager
Implement the following Method in your "Main" Fragment - in this example: DrawerFragment
public override void OnDetach() {
base.OnDetach();
try {
Fragment x = this;
var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/support/v4/app/FragmentManagerImpl;");
JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
}
catch (Exception e) {
Log.Debug("Error", e+"");
}
}
Android.App.FragmentManager
public class TabViewPager: Android.Support.V13.App.FragmentPagerAdapter {}
That means you had to init the ViewPager with Android.App.FragmentManager.
Implement the following Method in your "Main" Fragment - in this example: DrawerFragment
public override void OnDetach() {
base.OnDetach();
try {
Fragment x = this;
var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/app/FragmentManagerImpl;");
JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
}
catch (Exception e) {
Log.Debug("Error", e+"");
}
}
I run on wamp and I had this problem once. There can be many factors to this though there is 5 main ones that come to my mind.
1st. A program can cause this(Even antivirus software just depends what you have.)
2nd. Is your computer full or using alot of space this happen to a partner site of mine.
3rd. Check your regerstry files there could be errors or other things. (This end up being my problem.)
4th. After you uninstalled it did you manually delete the files that were left on your computer.(Yes even after you uninstall with wamp it has a tendency to leave a folder or 2 with some important data on it. When you install this will not be remodified and will stay the same.)
5th. Download the latest wamp or the lastest stable version of it.
Hope one of these things help.
New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.
Option Explicit
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Sub weGucciFam()
Dim tmp As Variant, str As String, h As Double, w As Double
Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"
keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28
str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height
Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
.PageSetup.PaperSize = xlPaper11x17
.PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
.PageSetup.BottomMargin = 0
.PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
.PageSetup.LeftMargin = 0
.PageSetup.HeaderMargin = 0
.PageSetup.FooterMargin = 0
.SeriesCollection(1).Delete
DoEvents
.Paste
DoEvents
.Export Filename:=str, Filtername:="jpeg"
.Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
wsTMP.Shapes(1).Delete
Loop
Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
111 means connection refused, which in turn means that your mysqld only listens to the localhost
interface.
To alter it you may want to look at the bind-address
value in the mysqld
section of your my.cnf
file.
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
The only way I'm aware of is building CSV list and then passing it as string. Then, on SP side, just split it and do whatever you need.
This works for everyone:
pip install -r /path/to/requirements.txt
Removing submodule manually involves number of steps and this worked for me.
Assuming you are in the project root directory and sample git module name is "c3-pro-ios-framework"
Remove the files associated to the submodule
rm -rf .git/modules/c3-pro-ios-framework/
Remove any references to submodule in config
vim .git/config
Remove .gitmodules
rm -rf .gitmodules
Remove it from the cache without the "git"
git rm --cached c3-pro-ios-framework
Add submodule
git submodule add https://github.com/chb/c3-pro-ios-framework.git
You could also supply variables on the command line with -PmavenUser=user -PmavenPassword=password
.
This might be useful you can't use a gradle.properties file for some reason. E.g. on a build server we're using Gradle with the -g
option so that each build plan has it's own GRADLE_HOME
.
In the (not too) early days, all that existed was ASCII. This was okay, as all that would ever be needed were a few control characters, punctuation, numbers and letters like the ones in this sentence. Unfortunately, today's strange world of global intercommunication and social media was not foreseen, and it is not too unusual to see English, ???????, ??, ????????, e???????, and ????????? in the same document (I hope I didn't break any old browsers).
But for argument's sake, lets say Joe Average is a software developer. He insists that he will only ever need English, and as such only wants to use ASCII. This might be fine for Joe the user, but this is not fine for Joe the software developer. Approximately half the world uses non-Latin characters and using ASCII is arguably inconsiderate to these people, and on top of that, he is closing off his software to a large and growing economy.
Therefore, an encompassing character set including all languages is needed. Thus came Unicode. It assigns every character a unique number called a code point. One advantage of Unicode over other possible sets is that the first 256 code points are identical to ISO-8859-1, and hence also ASCII. In addition, the vast majority of commonly used characters are representable by only two bytes, in a region called the Basic Multilingual Plane (BMP). Now a character encoding is needed to access this character set, and as the question asks, I will concentrate on UTF-8 and UTF-16.
So how many bytes give access to what characters in these encodings?
It's worth mentioning now that characters not in the BMP include ancient scripts, mathematical symbols, musical symbols, and rarer Chinese/Japanese/Korean (CJK) characters.
If you'll be working mostly with ASCII characters, then UTF-8 is certainly more memory efficient. However, if you're working mostly with non-European scripts, using UTF-8 could be up to 1.5 times less memory efficient than UTF-16. When dealing with large amounts of text, such as large web-pages or lengthy word documents, this could impact performance.
Note: If you know how UTF-8 and UTF-16 are encoded, skip to the next section for practical applications.
1
to avoid clashing with the ASCII characters.As can be seen, UTF-8 and UTF-16 are nowhere near compatible with each other. So if you're doing I/O, make sure you know which encoding you are using! For further details on these encodings, please see the UTF FAQ.
Character and String data types: How are they encoded in the programming language? If they are raw bytes, the minute you try to output non-ASCII characters, you may run into a few problems. Also, even if the character type is based on a UTF, that doesn't mean the strings are proper UTF. They may allow byte sequences that are illegal. Generally, you'll have to use a library that supports UTF, such as ICU for C, C++ and Java. In any case, if you want to input/output something other than the default encoding, you will have to convert it first.
Recommended/default/dominant encodings: When given a choice of which UTF to use, it is usually best to follow recommended standards for the environment you are working in. For example, UTF-8 is dominant on the web, and since HTML5, it has been the recommended encoding. Conversely, both .NET and Java environments are founded on a UTF-16 character type. Confusingly (and incorrectly), references are often made to the "Unicode encoding", which usually refers to the dominant UTF encoding in a given environment.
Library support: The libraries you are using support some kind of encoding. Which one? Do they support the corner cases? Since necessity is the mother of invention, UTF-8 libraries will generally support 4-byte characters properly, since 1, 2, and even 3 byte characters can occur frequently. However, not all purported UTF-16 libraries support surrogate pairs properly since they occur very rarely.
Counting characters: There exist combining characters in Unicode. For example the code point U+006E (n), and U+0303 (a combining tilde) forms ñ, but the code point U+00F1 forms ñ. They should look identical, but a simple counting algorithm will return 2 for the first example, 1 for the latter. This isn't necessarily wrong, but may not be the desired outcome either.
Comparing for equality: A, А, and Α look the same, but they're Latin, Cyrillic, and Greek respectively. You also have cases like C and Ⅽ, one is a letter, the other a Roman numeral. In addition, we have the combining characters to consider as well. For more info see Duplicate characters in Unicode.
Surrogate pairs: These come up often enough on SO, so I'll just provide some example links:
Others?:
If you want to check repetition more than 1 in descending order then implement below query.
SELECT duplicate_data,COUNT(duplicate_data) AS duplicate_data
FROM duplicate_data_table_name
GROUP BY duplicate_data
HAVING COUNT(duplicate_data) > 1
ORDER BY COUNT(duplicate_data) DESC
If want simple count query.
SELECT COUNT(duplicate_data) AS duplicate_data
FROM duplicate_data_table_name
GROUP BY duplicate_data
ORDER BY COUNT(duplicate_data) DESC
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
private List<String> FindString(String stringToLookFor, List<String> arrayToSearchIn)
{
List<String> ReceptacleOfWordsFound = new ArrayList<String>();
if(!arrayToSearchIn.isEmpty())
{
for(String lCurrentString : arrayToSearchIn)
{
if(lCurrentString.toUpperCase().contains(stringToLookFor.toUpperCase())
ReceptacleOfWordsFound.add(lCurrentString);
}
}
return ReceptacleOfWordsFound;
}
This method should completely avoid activities below the grey area retrieving click events.
Remove this line if you have it:
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
Put this on your activity created
getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
then override the touch event with this
@Override
public boolean onTouchEvent(MotionEvent ev)
{
if(MotionEvent.ACTION_DOWN == ev.getAction())
{
Rect dialogBounds = new Rect();
getWindow().getDecorView().getHitRect(dialogBounds);
if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
// You have clicked the grey area
displayYourDialog();
return false; // stop activity closing
}
}
// Touch events inside are fine.
return super.onTouchEvent(ev);
}
I hope this is useful to some of you, it can be used to remove outline from links, images and flash and from MSIE 9:
a, a:hover, a:active, a:focus, a img, object, embed {
outline: none;
ie-dummy: expression(this.hideFocus=true); /* MSIE - Microsoft Internet Explorer 9 remove outline */
}
The code below is able to hide image border:
img {
border: 0;
}
If you would like to support Firefox 3.6.8 but not Firefox 4... Clicking down on an input type=image can produce a dotted outline as well, to remove it in the old versions of firefox the following will do the trick:
input::-moz-focus-inner {
border: 0;
}
IE 9 doesn't allow in some cases to remove the dotted outline around links unless you include this meta tag between and in your pages:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:
https://github.com/facebook/facebook-android-sdk.git
git://github.com/facebook/facebook-android-sdk.git
$array = array(
'something' => array(1,2,3),
'somethingelse' => array(1,2,3,4)
);
$last_value = end($array);
$last_key = key($array); // 'somethingelse'
This works because PHP moves it's array pointer internally for $array
Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setInterval
rather than the setTimeout
?
setInterval(function() {
location.reload();
}, 30000);
let me know you thoughts.
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Use jQuery
Look how easy it would be if you did.
Example:
$('#td1').html('hello world');
Use setInterval(func, delay) to run the func
every delay
milliseconds.
setTimeout()
runs your function once after delay
milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.
QPushButton *button = new QPushButton;
button->setIcon(QIcon(":/icons/..."));
button->setIconSize(QSize(65, 65));
This is how I solved the problem:
@{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
var nonID = Number(@nonProID);
var proID = Number(@proID);
</script>
It is self-documenting and it doesn't involve conversion to and from text.
Note: be careful to use the Number()
function not create new Number()
objects - as the exactly equals operator may behave in a non-obvious way:
var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false
To be able to use 'ngModule'
, the 'FormsModule'
(from @angular/forms
) needs to be added to your import[]
array in the AppModule
(should be there by default in a CLI project).
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
Extending Django User Model (UserProfile) like a Pro
I've found this very useful: link
An extract:
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.employee.department
All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType
as return type and not JsonResult
.
Unfortunately JsonResult
is using JavaScriptSerializer
without option to disable it. The best way to get around this is to inherit JsonResult
.
I copied most of the code from original JsonResult
and created JsonStringResult
class that returns passed string as application/json
. Code for this class is below
public class JsonStringResult : JsonResult
{
public JsonStringResult(string data)
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
Data = data;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Get request is not allowed!");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
response.Write(Data);
}
}
}
Example usage:
var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);
remove href
attribute:
<a id="" onclick="f1()">jhhghj</a>
if link styles are important then:
<a href="javascript:void(f1())">jhhghj</a>
According to the documentation for UINavigationItem
:
self.navigationItem.setHidesBackButton(true, animated: true)
You can P/Invoke down to the Win32 GetAsyncKeyState to test any key on the keyboard.
You can pass in values from the Keys enum (e.g. Keys.Shift) to this function, so it only requires a couple of lines of code to add it.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
If you are simply looking to make the input relative to the screen width, an easy way would be to use Dimensions:
// De structure Dimensions from React
var React = require('react-native');
var {
...
Dimensions
} = React;
// Store width in variable
var width = Dimensions.get('window').width;
// Use width variable in style declaration
<TextInput style={{ width: width * .8 }} />
I've set up a working project here. Code is also below.
https://rnplay.org/apps/rqQPCQ
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
Dimensions
} = React;
var width = Dimensions.get('window').width;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={{fontSize:22}}>Percentage Width In React Native</Text>
<View style={{marginTop:100, flexDirection: 'row',justifyContent: 'center'}}>
<TextInput style={{backgroundColor: '#dddddd', height: 60, width: width*.8 }} />
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:100
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
Implicit wait --
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).
Explicit wait--
Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.
There is also a new option now in http://vimr.org/, which looks quite promising.
no your ans is Wrong
Selection of Al and Ah is from AX not from EAX
e.g
EAX=0000 0000 0000 0000 0000 0000 0000 0111
So if we call AX it should return
0000 0000 0000 0111
if we call AH it should return
0000 0000
and when we call AL it should return
0000 0111
Example number 2
EAX: 22 33 55 77
AX: 55 77
AH: 55
AL: 77
example 3
EAX: 1111 0000 0000 0000 0000 0000 0000 0111
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111
Your int length = jsonObj.length();
should be int length = ja_data.length();
You can opt to create your own custom events so you'll still have a clear separation of logic.
Bind to a custom event:
$('#laneconfigdisplay').bind('contentchanged', function() {
// do something after the div content has changed
alert('woo');
});
In your function that updates the div:
// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above
You should try below code. It is working for me.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/checked"
android:state_checked="true">
<color android:color="@color/yello" />
</item>
<!-- checked -->
<item android:drawable="@drawable/unchecked"
android:state_checked="false">
<color android:color="@color/black"></color>
</item>
<!-- unchecked -->
<item android:drawable="@drawable/checked"
android:state_focused="true">
<color android:color="@color/yello"></color>
</item>
<!-- on focus -->
<item android:drawable="@drawable/unchecked">
<color android:color="@color/black"></color>
</item>
<!-- default -->
</selector>
and CheckBox
<CheckBox
Button="@style/currentcy_check_box_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="@string/step_one_currency_aud" />
When learning a new concept I don't like using libraries or code dumps. I found a good description here and in the documentation of how to resize an image by pinching. This answer is a slightly modified summary. You will probably want to add more functionality later, but it will help you get started.
The ImageView
just uses the app logo since it is already available. You can replace it with any image you like, though.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
android:layout_centerInParent="true"/>
</RelativeLayout>
We use a ScaleGestureDetector
on the activity to listen to touch events. When a scale (ie, pinch) gesture is detected, then the scale factor is used to resize the ImageView
.
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize the view and the gesture detector
mImageView = findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
// this redirects all touch events in the activity to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent event) {
return mScaleGestureDetector.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
// when a scale gesture is detected, use it to resize the image
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector){
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
You can limit the size of the scaling with something like
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
Thanks again to Pinch-to-zoom with multi-touch gestures In Android
You will probably want to do other things like panning and scaling to some focus point. You can develop these things yourself, but if you would like to use a pre-made custom view, copy TouchImageView.java
into your project and use it like a normal ImageView
. It worked well for me and I only ran into one bug. I plan to further edit the code to remove the warning and the parts that I don't need. You can do the same.
For those using yarn.
I tried using npm shrinkwrap until I discovered the yarn cli ignored my npm-shrinkwrap.json file.
Yarn has https://yarnpkg.com/lang/en/docs/selective-version-resolutions/ for this. Neat.
Check out this answer too: https://stackoverflow.com/a/41082766/3051080
I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.
I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.
Thanks everyone!
Here's an O(n) solution using reduce and Object.assign
const joinById = ( ...lists ) =>
Object.values(
lists.reduce(
( idx, list ) => {
list.forEach( ( recod ) => {
if( idx[ recod.id ] )
idx[ recod.id ] = Object.assign( idx[ recod.id ], recod )
else
idx[ recod.id ] = recod
} )
return idx
},
{}
)
)
Each list gets reduced to a single object where the keys are ids and the values are the objects. If there's a value at the given key already, it gets object.assign called on it and the current record.
Here's the generic O(n*m) solution, where n is the number of records and m is the number of keys. This will only work for valid object keys. You can convert any value to base64 and use that if you need to.
const join = ( keys, ...lists ) =>
lists.reduce(
( res, list ) => {
list.forEach( ( record ) => {
let hasNode = keys.reduce(
( idx, key ) => idx && idx[ record[ key ] ],
res[ 0 ].tree
)
if( hasNode ) {
const i = hasNode.i
Object.assign( res[ i ].value, record )
res[ i ].found++
} else {
let node = keys.reduce( ( idx, key ) => {
if( idx[ record[ key ] ] )
return idx[ record[ key ] ]
else
idx[ record[ key ] ] = {}
return idx[ record[ key ] ]
}, res[ 0 ].tree )
node.i = res[ 0 ].i++
res[ node.i ] = {
found: 1,
value: record
}
}
} )
return res
},
[ { i: 1, tree: {} } ]
)
.slice( 1 )
.filter( node => node.found === lists.length )
.map( n => n.value )
This is essentially the same as the joinById method, except that it keeps an index object to identify records to join. The records are stored in an array and the index stores the position of the record for the given key set and the number of lists it's been found in.
Each time the same key set is encountered, the node is found in the tree, the element at it's index is updated, and the number of times it's been found is incremented.
finally, the idx object is removed from the array with the slice, any elements that weren't found in each set are removed. This makes it an inner join, you could remove this filter and have a full outer join.
finally each element is mapped to it's value, and you have the merged array.
The
setInterval()
method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more @ setInterval() @ MDN Web Docs
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
Take a look at this: Complete Example
Server:
let exp = require('express');
let app = exp();
//UPDATE: this is seems to be deprecated
//let io = require('socket.io').listen(app.listen(9009));
//New Syntax:
const io = require('socket.io')(app.listen(9009));
app.all('/', function (request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
Client:
<!--LOAD THIS SCRIPT FROM SOMEWHERE-->
<script src="http://127.0.0.1:9009/socket.io/socket.io.js"></script>
<script>
var socket = io("127.0.0.1:9009/", {
"force new connection": true,
"reconnectionAttempts": "Infinity",
"timeout": 10001,
"transports": ["websocket"]
}
);
</script>
I remember this from the combination of stackoverflow answers many days ago; but I could not find the main links to mention them
Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here
> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop
C:\Users\myname\Desktop is the ouput folder you can change that to your preference
http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL
Here's the more modern streams approach:
myIntegerSet.stream().filter((it) -> it % 2 != 0).collect(Collectors.toSet())
However, this makes a new set, so memory constraints might be an issue if it's a really huge set.
EDIT: previous version of this answer suggested Apache CollectionUtils but that was before steams came about.
The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered)
it seems that we are talking about a service not correctly installed. I will try to reinstall the application.
Detached head means:
If you have no changes: you can switch to master by applying the following command
git checkout master
If you have changes that you want to keep:
In case of a detached HEAD, commits work like normal, except no named branch gets updated. To get master branch updated with your committed changes, make a temporary branch where you are (this way the temporary branch will have all the committed changes you have made in the detached HEAD), then switch to the master branch and merge the temporary branch with the master.
git branch temp
git checkout master
git merge temp
Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.
I have same problem after update android studio to 1.5, and i fix it by update the gradle location,
Hope this method works for you,
You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others
To use Run (Simple Method)
Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn
ProgramPath is the full path to your script you want to run
ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)
])
IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run Method
WaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.
NOTE: The Run method can return the exit code but you must set WaitOnReturn to True, and assign the 'WshShell.Run' to a variable. (EX: ExitCode=WshShell.Run (Command,intWindowStyle,True)
)
To Use EXEC (Advanced Method)
Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
'Currently Waiting on the program to finish execution.
WScript.Sleep 300
Loop
ProgramPath same as Run READ RUN'S DESCRIPTION
ProgramArgs DITTO
ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe". Note that in order to use stdin and stdout (we'll cover what these are a bit further down) you must choose "CScript.exe".
Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.
More Details about the members of Process Object
Process.StdIn.WriteLine "Hello Other Worlds"
)Process.StdOut.ReadLine
. This is the stream that the called script will receive any information sent by the calling script's stdin. If you used the stdin's example then StdOut.Readline will return "Hello Other Worlds". If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not RespondingRead
or ReadAll
instead of ReadLine
if you want. Use Read (X)
if you want to read X amount of characters. Or ReadAll
if you want the rest of the stream.For more information about WshShell.Exec go to Exec Method Windows Scripting Host
Use an extension method instead:
public static class ExtensionMethods
{
public static int IntValue(this Enum argEnum)
{
return Convert.ToInt32(argEnum);
}
}
And the usage is slightly prettier:
var intValue = Question.Role.IntValue();
In addition to the anwsers above you can use PadLeft or PadRight:
string name = "John";
string surname = "Smith";
Console.WriteLine("Name:".PadRight(15)+"Surname:".PadRight(15));
Console.WriteLine( name.PadRight(15) + surname.PadRight(15));
This will fill in the string with spaces to the left or right.
Try this:
SELECT ID, Email, ProductName, ProductModel FROM Products WHERE ID IN (SELECT MAX(ID) FROM Products GROUP BY Email)
Create a UIImageView and add UIImage to it:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image Name"]] ;
Then add it to your view:
[self.view addSubView: imageView];
The question is answered already, but I want add more information about the causes.
Android app unable to start activity componentinfo
This error often comes with appropriate logs. You can read logs and can solve this issue easily.
Here is a sample log. In which you can see clearly ClassCastException
. So this issue came because TextView
cannot be cast to EditText
.
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050): at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050): ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109): at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109): ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167): at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167): ... 11 more
findViewById()
of non existing viewLike when you use findViewById(R.id.button)
when button id does not exist in layout XML.
If you wrong cast some class, then you get this error. Like you cast RelativeLayout
to LinearLayout
or EditText
to TextView
.
manifest.xml
If you did not register Activity in manifest.xml
then this error comes.
findViewById()
with declaration at top levelBelow code is incorrect. This will create error. Because you should do findViewById()
after calling setContentView()
. Because an View can be there after it is created.
public class MainActivity extends Activity {
ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
//...
}
}
abstract
Activity class.When you try to start an Activity which is abstract, you will will get this error. So just remove abstract
keyword before activity class name.
If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.
Read about Downcast and Upcast
Provided that any element has the id attribute on a webpage. One could simply link/jump to the element that is referenced by the tag.
Within the same page:
<div id="markOne"> ..... </div>
......
<a href="#markOne">Jump to markOne</a>
Other page:
<div id="http://randomwebsite.com/mypage.html#markOne">
Jumps to the markOne element in the mypage of the linked website
</div>
The targets don't necessarily have an anchor element.
You can go check this fiddle out.
If I get your question correctly, you could do something like this.
>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()
which would give you something like
Or as a line plot,
>>> plt.plot(*zip(*testList2))
>>> plt.show()
EDIT - If you want to add a title and labels for the axis, you could do something like
>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()
which would give you
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18
.
var height = document.body.clientHeight;
var width = document.body.clientWidth;
Check: this article for better explanation.
To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.
//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);
function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
//get the src attribute
source = jQuery(".xyro_refresh").attr("src");
//remove previously added timestamps
source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
//prep new src attribute by adding a timestamp
new_source = source + "?timestamp=" + new Date().getTime();
//alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
//set the new src attribute
jQuery(".xyro_refresh").attr("src", new_source);
}
Put in head link to google styles
<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">
and in body something like this
<i class="material-icons-outlined">bookmarks</i>
I know this question is very old, but I came upon it because I needed something cross platform for linux, win32... I wrote the function below, it is a single function that can parse INI files, hopefully others will find it useful.
rules & caveats: buf to parse must be a NULL terminated string. Load your ini file into a char array string and call this function to parse it. section names must have [] brackets around them, such as this [MySection], also values and sections must begin on a line without leading spaces. It will parse files with Windows \r\n or with Linux \n line endings. Comments should use # or // and begin at the top of the file, no comments should be mixed with INI entry data. Quotes and ticks are trimmed from both ends of the return string. Spaces are only trimmed if they are outside of the quote. Strings are not required to have quotes, and whitespaces are trimmed if quotes are missing. You can also extract numbers or other data, for example if you have a float just perform a atof(ret) on the ret buffer.
// -----note: no escape is nessesary for inner quotes or ticks-----
// -----------------------------example----------------------------
// [Entry2]
// Alignment = 1
// LightLvl=128
// Library = 5555
// StrValA = Inner "quoted" or 'quoted' strings are ok to use
// StrValB = "This a "quoted" or 'quoted' String Value"
// StrValC = 'This a "tick" or 'tick' String Value'
// StrValD = "Missing quote at end will still work
// StrValE = This is another "quote" example
// StrValF = " Spaces inside the quote are preserved "
// StrValG = This works too and spaces are trimmed away
// StrValH =
// ----------------------------------------------------------------
//12oClocker super lean and mean INI file parser (with section support)
//set section to 0 to disable section support
//returns TRUE if we were able to extract a string into ret value
//NextSection is a char* pointer, will be set to zero if no next section is found
//will be set to pointer of next section if it was found.
//use it like this... char* NextSection = 0; GrabIniValue(X,X,X,X,X,&NextSection);
//buf is data to parse, ret is the user supplied return buffer
BOOL GrabIniValue(char* buf, const char* section, const char* valname, char* ret, int retbuflen, char** NextSection)
{
if(!buf){*ret=0; return FALSE;}
char* s = buf; //search starts at "s" pointer
char* e = 0; //end of section pointer
//find section
if(section)
{
int L = strlen(section);
SearchAgain1:
s = strstr(s,section); if(!s){*ret=0; return FALSE;} //find section
if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain1;} //section must be at begining of a line!
s+=L; //found section, skip past section name
while(*s!='\n'){s++;} s++; //spin until next line, s is now begining of section data
e = strstr(s,"\n["); //find begining of next section or end of file
if(e){*e=0;} //if we found begining of next section, null the \n so we don't search past section
if(NextSection) //user passed in a NextSection pointer
{ if(e){*NextSection=(e+1);}else{*NextSection=0;} } //set pointer to next section
}
//restore char at end of section, ret=empty_string, return FALSE
#define RESTORE_E if(e){*e='\n';}
#define SAFE_RETURN RESTORE_E; (*ret)=0; return FALSE
//find valname
int L = strlen(valname);
SearchAgain2:
s = strstr(s,valname); if(!s){SAFE_RETURN;} //find valname
if(s > buf && (*(s-1))!='\n'){s+=L; goto SearchAgain2;} //valname must be at begining of a line!
s+=L; //found valname match, skip past it
while(*s==' ' || *s == '\t'){s++;} //skip spaces and tabs
if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return
if(*s != '='){goto SearchAgain2;} //no equal sign found after valname, search again
s++; //skip past the equal sign
while(*s==' ' || *s=='\t'){s++;} //skip spaces and tabs
while(*s=='\"' || *s=='\''){s++;} //skip past quotes and ticks
if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return
char* E = s; //s is now the begining of the valname data
while(*E!='\r' && *E!='\n' && *E!=0){E++;} E--; //find end of line or end of string, then backup 1 char
while(E > s && (*E==' ' || *E=='\t')){E--;} //move backwards past spaces and tabs
while(E > s && (*E=='\"' || *E=='\'')){E--;} //move backwards past quotes and ticks
L = E-s+1; //length of string to extract NOT including NULL
if(L<1 || L+1 > retbuflen){SAFE_RETURN;} //empty string or buffer size too small
strncpy(ret,s,L); //copy the string
ret[L]=0; //null last char on return buffer
RESTORE_E;
return TRUE;
#undef RESTORE_E
#undef SAFE_RETURN
}
How to use... example....
char sFileData[] = "[MySection]\r\n"
"MyValue1 = 123\r\n"
"MyValue2 = 456\r\n"
"MyValue3 = 789\r\n"
"\r\n"
"[MySection]\r\n"
"MyValue1 = Hello1\r\n"
"MyValue2 = Hello2\r\n"
"MyValue3 = Hello3\r\n"
"\r\n";
char str[256];
char* sSec = sFileData;
char secName[] = "[MySection]"; //we support sections with same name
while(sSec)//while we have a valid sNextSec
{
//print values of the sections
char* next=0;//in case we dont have any sucessful grabs
if(GrabIniValue(sSec,secName,"MyValue1",str,sizeof(str),&next)) { printf("MyValue1 = [%s]\n",str); }
if(GrabIniValue(sSec,secName,"MyValue2",str,sizeof(str),0)) { printf("MyValue2 = [%s]\n",str); }
if(GrabIniValue(sSec,secName,"MyValue3",str,sizeof(str),0)) { printf("MyValue3 = [%s]\n",str); }
printf("\n");
sSec = next; //parse next section, next will be null if no more sections to parse
}
You can use Dispatcher.Invoke to update your GUI from a secondary thread.
Here is an example:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(DoSomething).Start();
}
public void DoSomething()
{
for (int i = 0; i < 100000000; i++)
{
this.Dispatcher.Invoke(()=>{
textbox.Text=i.ToString();
});
}
}
You dont have to
RUN mkdir -p /usr/src/app
This will be created automatically when you specifiy your WORKDIR
FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ]
I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).
Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:
<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />
And this worked!
It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?
Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.
i have used this and solved my
-webkit-appearance:none;
I think this is a very good chart describing the differences in short. A quick glance at it shows most of the differences.
One thing I would like to add is that, AngularJS can be made to follow the MVVM design pattern while jQuery does not follow any of the standard Object Oriented patterns.
Thanks to Java 8 you don't need to do the steps below to pass a function to a method, that's what lambdas are for, see Oracle's Lambda Expression tutorial. The rest of this post describes what we used to have to do in the bad old days in order to implement this functionality.
Typically you declare your method as taking some interface with a single method, then you pass in an object that implements that interface. An example is in commons-collections, where you have interfaces for Closure, Transformer, and Predicate, and methods that you pass implementations of those into. Guava is the new improved commons-collections, you can find equivalent interfaces there.
So for instance, commons-collections has org.apache.commons.collections.CollectionUtils, which has lots of static methods that take objects passed in, to pick one at random, there's one called exists with this signature:
static boolean exists(java.util.Collection collection, Predicate predicate)
It takes an object that implements the interface Predicate, which means it has to have a method on it that takes some Object and returns a boolean.
So I can call it like this:
CollectionUtils.exists(someCollection, new Predicate() {
public boolean evaluate(Object object) {
return ("a".equals(object.toString());
}
});
and it returns true or false depending on whether someCollection
contains an object that the predicate returns true for.
Anyway, this is just an example, and commons-collections is outdated. I just forget the equivalent in Guava.
import re
s = "many fancy word \nhello \thi"
re.split('\s+', s)
Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:
from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
<td width="580" valign="top">.......</td>\
<td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')
Using INSTR:
SELECT *
FROM TABLE a
JOIN TABLE b ON INSTR(b.column, a.column) > 0
Using LIKE:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'
Using LIKE, with CONCAT:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')
Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:
SELECT *
FROM (SELECT UPPER(a.column) 'ua'
TABLE a) a
JOIN (SELECT UPPER(b.column) 'ub'
TABLE b) b ON INSTR(b.ub, a.ua) > 0
The most efficient will depend ultimately on the EXPLAIN plan output.
JOIN
clauses are identical to writing WHERE
clauses. The JOIN
syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:
SELECT *
FROM TABLE a,
TABLE b
WHERE INSTR(b.column, a.column) > 0
I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE
clause.
CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
The leading ', '
and trailing ','
are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).
That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.
In addition: don't use 'single quotes'
as identifier delimiters; this syntax is deprecated. Use [square brackets]
(preferred) or "double quotes"
if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx
EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE
syntax variant or by using something like IN()
):
CASE
WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%'
WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%'
THEN 'BP Medication' ELSE '' END AS [BP Medication]
If you have more values, it might be worthwhile to use a split function, e.g.
USE tempdb;
GO
CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List,',', '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO
INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');
SELECT t.ID
FROM dbo.[Table] AS t
INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
GROUP BY t.ID;
GO
Results:
ID
----
1
2
4
Given you start with mapping.get("servers").getAsJsonArray()
, if you have access to Guava Streams
, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport
won't be able to work on JsonElement
type, so it is insufficient.
Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers
I have tested this method with content://com.adobe.scan.android.documents/document/
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
you may include bootstrap to your html file and you put it under the style file so if you do that bootstrap file will override the style file briefly like this
// style file
<link rel="stylesheet" href="css/style.css" />
// bootstrap file
<link rel="stylesheet" href="css/bootstrap.min.css" />
the right way is this
// bootstrap file
<link rel="stylesheet" href="css/bootstrap.min.css" />
// style file
<link rel="stylesheet" href="css/style.css" />
This one works in earlier versions of IE also.
function toogleClass(ele, class1) {_x000D_
var classes = ele.className;_x000D_
var regex = new RegExp('\\b' + class1 + '\\b');_x000D_
var hasOne = classes.match(regex);_x000D_
class1 = class1.replace(/\s+/g, '');_x000D_
if (hasOne)_x000D_
ele.className = classes.replace(regex, '');_x000D_
else_x000D_
ele.className = classes + class1;_x000D_
}
_x000D_
.red {_x000D_
background-color: red_x000D_
}_x000D_
div {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
margin-bottom: 10px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="does red redAnother " onclick="toogleClass(this, 'red')"></div>_x000D_
_x000D_
<div class="does collapse navbar-collapse " onclick="toogleClass(this, 'red')"></div>
_x000D_
Go to your java directory, Copy this path C:\Program Files\Java\jdk1.8.0_40\bin
Right click on my computer , click properties, then go to "Advanced system settings" click , Environment variables. go to "System variables" table, find an entry named "path". Double click it and go to the end, put a semicolon and paste your path, apply and ok. It should run now.
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
I know this question is old, but the solution to my application, was different to the already suggested answers. If anyone else like me still have this issue, and none of the above answers works, this might be the problem:
I used a Network Credentials object to parse a windows username+password to a third party SOAP webservice. I had set the username="domainname\username", password="password" and domain="domainname". Now this game me that strange Ntlm and not NTLM error. To solve the problems, make sure not to use the domain parameter on the NetworkCredentials object if the domain name is included in the username with the backslash. So either remove domain name from the username and parse in domain parameter, or leave out the domain parameter. This solved my issue.
This is a known bug with jQuery. The jQuery team has "no plans to support this in core and is better suited as a plugin." (See this comment). IE does not use the XMLHttpRequest, but an alternative object named XDomainRequest.
There is a plugin available to support this in jQuery, which can be found here: https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js
EDIT
The function $.ajaxTransport
registers a transporter factory. A transporter is used internally by $.ajax
to perform requests. Therefore, I assume you should be able to call $.ajax
as usual. Information on transporters and extending $.ajax
can be found here.
Also, a perhaps better version of this plugin can be found here.
Two other notes:
Edit 2: http to https problem
Requests must be targeted to the same scheme as the hosting page
This restriction means that if your AJAX page is at http://example.com, then your target URL must also begin with HTTP. Similarly, if your AJAX page is at https://example.com, then your target URL must also begin with HTTPS.
if you have Firebase included also, make them of same version as the error says.