In my case I had to remove the ngNoForm
attribute from my <form>
tag.
If you you want to import FormsModule in your application but want to skip a specific form, you can use the ngNoForm directive which will prevent ngForm from being added to the form
Reference: https://www.techiediaries.com/angular-ngform-ngnoform-template-reference-variable/
I put the absolute path of the virtual environment Python executable as well has the packages. I then restarted Visual Studio Code.
I am trying to get ${workspaceRoot} to avoid hardcoding absolute paths.
{
"editor.rulers": [80,100],
"python.pythonPath": "/home/jesvin/dev/ala/venv/bin/python",
"python.autoComplete.extraPaths": [
"/home/jesvin/dev/ala/venv/lib/python2.7",
"/home/jesvin/dev/ala/venv/lib/python2.7/site-packages"
]
}
Omit row if either of two specific columns contain <NA>
.
DF[!is.na(DF$x)&!is.na(DF$z),]
Create a delegate on class that need to send some data or provide some functionality to other classes
Like
protocol GetGameStatus {
var score: score { get }
func getPlayerDetails()
}
After that in the class that going to confirm to this delegate
class SnakesAndLadders: GetGameStatus {
func getPlayerDetails() {
}
}
Use "E"
See the section on Date and Time Patterns:
A bit late but I thought I'd share in case it helps anyone: what is most likely the problem is simply that your Debug Console (the command line window that opens when run your project if it is a Windows Console Application
) is still open from the last time you ran the code. Just close that window, then rebuild and run: Ctrl + B
and F5
, respectively.
A primitive int
cannot be null. If you need null, use Integer
instead.
There are many anwers in this question, probably all will give you the answer you are looking for. But as @TallGreenTree mentions, there is a function for this.
But the problem of the answer of @TallGreenTree is that it doesn't round up, it rounds to the nearest 10. To solve this, add +5
to your number in order to round up. If you want to round down, do -5
.
So in code:
round($num + 5, -1);
You can't use the round mode
for rounding up, because that only rounds up fractions and not whole numbers.
If you want to round up to the nearest 100
, you shoud use +50
.
Based on Tim Down's answer, but it checks for the last known "good" text row. It places the cursor at the very end.
Furthermore, I could also recursively/iteratively check the last child of each consecutive last child to find the absolute last "good" text node in the DOM.
function onClickHandler() {_x000D_
setCaret(document.getElementById("editable"));_x000D_
}_x000D_
_x000D_
function setCaret(el) {_x000D_
let range = document.createRange(),_x000D_
sel = window.getSelection(),_x000D_
lastKnownIndex = -1;_x000D_
for (let i = 0; i < el.childNodes.length; i++) {_x000D_
if (isTextNodeAndContentNoEmpty(el.childNodes[i])) {_x000D_
lastKnownIndex = i;_x000D_
}_x000D_
}_x000D_
if (lastKnownIndex === -1) {_x000D_
throw new Error('Could not find valid text content');_x000D_
}_x000D_
let row = el.childNodes[lastKnownIndex],_x000D_
col = row.textContent.length;_x000D_
range.setStart(row, col);_x000D_
range.collapse(true);_x000D_
sel.removeAllRanges();_x000D_
sel.addRange(range);_x000D_
el.focus();_x000D_
}_x000D_
_x000D_
function isTextNodeAndContentNoEmpty(node) {_x000D_
return node.nodeType == Node.TEXT_NODE && node.textContent.trim().length > 0_x000D_
}
_x000D_
<div id="editable" contenteditable="true">_x000D_
text text text<br>text text text<br>text text text<br>_x000D_
</div>_x000D_
<button id="button" onclick="onClickHandler()">focus</button>
_x000D_
The Array
and List<T>
classes already have ForEach
methods, though only this specific implementation. (Note that the former is static
, by the way).
Not sure it really offers a great advantage over a foreach
statement, but you could write an extension method to do the job for all IEnumerable<T>
objects.
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
This would allow the exact code you posted in your question to work just as you want.
During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>
In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}
System.Reflection.Assembly.GetEntryAssembly().Location;
This method checks if a String contains a special character (based on your definition).
/**
* Returns true if s contains any character other than
* letters, numbers, or spaces. Returns false otherwise.
*/
public boolean containsSpecialCharacter(String s) {
return (s == null) ? false : s.matches("[^A-Za-z0-9 ]");
}
You can use the same logic to count special characters in a string like this:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
theCount++;
}
}
return theCount;
}
Another approach is to put all the special chars in a String and use String.contains:
/**
* Counts the number of special characters in s.
*/
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
int theCount = 0;
String specialChars = "/*!@#$%^&*()\"{}_[]|\\?/<>,.";
for (int i = 0; i < s.length(); i++) {
if (specialChars.contains(s.substring(i, 1))) {
theCount++;
}
}
return theCount;
}
NOTE: You must escape the backslash and "
character with a backslashes.
The above are examples of how to approach this problem in general.
For your exact problem as stated in the question, the answer by @LanguagesNamedAfterCoffee is the most efficient approach.
Another option to get git
to work with multiple names / emails is by aliasing git
and using the -c
flag to override the global and repository-specific config.
For example, by defining an alias:
alias git='/usr/bin/git -c user.name="Your name" -c user.email="[email protected]"'
To see whether it works, simply type git config user.email
:
$ git config user.email
[email protected]
Instead of an alias, you could also put a custom git
executable within your $PATH
.
#!/bin/sh
/usr/bin/git -c user.name="Your name" -c user.email="[email protected]" "$@"
An advantage of these method over a repository-specific .git/config
is that it applies to every git
repository when the custom git
program is active. In this way, you can easily switch between users/names without modifying any (shared) configuration.
As the documentation clearly states, Character.getNumericValue()
returns the character's value as a digit.
It returns -1
if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character
object, you'll need to unbox it first:
int value = (int)c.charValue();
If running on minikube, don't forget to mention namespace if you are not using default.
minikube service << service_name >> --url --namespace=<< namespace_name >>
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
create table abc(emp_ID int, manager varchar(20) , manager_id int)
emp_ID manager manager_id
1 abc NULL
2 def 1
3 ghi 2
4 klm 3
5 def1 1
6 ghi1 2
7 klm1 3
select a.emp_ID , a.manager emp_name,b.manager manager_name
from abc a
left join abc b
on a.manager_id = b.emp_ID
Result:
emp_ID emp_name manager_name
1 abc NULL
2 def abc
3 ghi def
4 klm ghi
5 def1 abc
6 ghi1 def
7 klm1 ghi
Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="true">
<add verb="OPTIONS" allowed="false" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering
if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/
Piping output to xargs
will concatenate each line of output to a single line with spaces:
grep pattern file | xargs
Or any command, eg. ls | xargs
. The default limit of xargs
output is ~4096 characters, but can be increased with eg. xargs -s 8192
.
use RelativeLayout inside LinearLayout
example:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Status"/>
</RelativeLayout>
</LinearLayout>
I had the same problem.....the issu is in the version PHP SDK 5.6.2 and the fix was editing the following file:
facebook\src\Facebook\Helpers\FacebookRedirectLoginHelper.php
change this line
$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code']);
to
$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code','enforce_https']);
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
Use the zipfile
module. To extract a file from a URL, you'll need to wrap the result of a urlopen
call in a BytesIO
object. This is because the result of a web request returned by urlopen
doesn't support seeking:
from urllib.request import urlopen
from io import BytesIO
from zipfile import ZipFile
zip_url = 'http://example.com/my_file.zip'
with urlopen(zip_url) as f:
with BytesIO(f.read()) as b, ZipFile(b) as myzipfile:
foofile = myzipfile.open('foo.txt')
print(foofile.read())
If you already have the file downloaded locally, you don't need BytesIO
, just open it in binary mode and pass to ZipFile
directly:
from zipfile import ZipFile
zip_filename = 'my_file.zip'
with open(zip_filename, 'rb') as f:
with ZipFile(f) as myzipfile:
foofile = myzipfile.open('foo.txt')
print(foofile.read().decode('utf-8'))
Again, note that you have to open
the file in binary ('rb'
) mode, not as text or you'll get a zipfile.BadZipFile: File is not a zip file
error.
It's good practice to use all these things as context managers with the with
statement, so that they'll be closed properly.
For normal users. Open the inspect window of current page. And type in:
l = document.getElementsByTagName("a");
for (var i =0; i<l.length; i++) {
l[i].href = "";
}
Then you shall not see the url links in print preview.
You may need admin access to do it on your system.
C:\Program Files (x86)\Notepad++
themes
folder.
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.
Whereas Basic Authentication uses non-encrypted base64 encoding.
Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.
See RFC-2617 for all the gory details.
Create a BufferedImage from file and make it TYPE_INT_RGB
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
public static void main(String args[]){
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_RGB );
File f = new File("MyFile.png");
int r = 5;
int g = 25;
int b = 255;
int col = (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 300; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
}
}
This paints a big blue streak across the top.
If you want it ARGB, do it like this:
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_ARGB );
File f = new File("MyFile.png");
int r = 255;
int g = 10;
int b = 57;
int alpha = 255;
int col = (alpha << 24) | (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 30; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
Open up MyFile.png, it has a red streak across the top.
Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
<?php
// connect to database
$conn=mysqli_connect("localhost","user","password","database");
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// sql query
$sql =mysqli_query($conn,"TRUNCATE " . TABLE_NAME);
// Print message
if ($sql === TRUE) {
echo 'data delete successfully';
}
else {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
Here is code snippet which I use to clear a table. Just change $conn info and TABLE_NAME.
Just wanted to share a curiosity:
when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!
For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !
Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!
Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK
and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.
There is a numpy built-in function to help with that.
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
you can use reflect.TypeOf
.
int
, string
): it will return its name (e.g.: int
, string
) <package name>.<struct name>
(e.g.: main.test
)If you will divide by some large value you will get a huge amount of duplicates one after other. What you need to do is to take modulo of the %RANDOM% value:
@echo off
REM
SET maxvalue=10
SET minvalue=1
SETLOCAL
SET /A tmpRandom=((%RANDOM%)%%(%maxvalue%))+(%minvalue%)
echo "Tmp random: %tmpRandom%"
echo "Random: %RANDOM%"
ENDLOCAL
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
I would tentatively recommend using PDO for your SQL access.
Then it is only a case of changing the driver and ensuring the SQL works on the new backend. In theory. Data migration is a different issue.
Abstract database access is great.
I have difficulty in decrypting a long string that is encrypted in python. Here is the python encryption function:
def RSA_encrypt(public_key, msg, chunk_size=214):
"""
Encrypt the message by the provided RSA public key.
:param public_key: RSA public key in PEM format.
:type public_key: binary
:param msg: message that to be encrypted
:type msg: string
:param chunk_size: the chunk size used for PKCS1_OAEP decryption, it is determined by \
the private key length used in bytes - 42 bytes.
:type chunk_size: int
:return: Base 64 encryption of the encrypted message
:rtype: binray
"""
rsa_key = RSA.importKey(public_key)
rsa_key = PKCS1_OAEP.new(rsa_key)
encrypted = b''
offset = 0
end_loop = False
while not end_loop:
chunk = msg[offset:offset + chunk_size]
if len(chunk) % chunk_size != 0:
chunk += " " * (chunk_size - len(chunk))
end_loop = True
encrypted += rsa_key.encrypt(chunk.encode())
offset += chunk_size
return base64.b64encode(encrypted)
The decryption in PHP:
/**
* @param base64_encoded string holds the encrypted message.
* @param Resource your private key loaded using openssl_pkey_get_private
* @param integer Chunking by bytes to feed to the decryptor algorithm.
* @return String decrypted message.
*/
public function RSADecyrpt($encrypted_msg, $ppk, $chunk_size=256){
if(is_null($ppk))
throw new Exception("Returned message is encrypted while you did not provide private key!");
$encrypted_msg = base64_decode($encrypted_msg);
$offset = 0;
$chunk_size = 256;
$decrypted = "";
while($offset < strlen($encrypted_msg)){
$decrypted_chunk = "";
$chunk = substr($encrypted_msg, $offset, $chunk_size);
if(openssl_private_decrypt($chunk, $decrypted_chunk, $ppk, OPENSSL_PKCS1_OAEP_PADDING))
$decrypted .= $decrypted_chunk;
else
throw new exception("Problem decrypting the message");
$offset += $chunk_size;
}
return $decrypted;
}
First save your program as program.c
.
Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing ⌘Space and start typing App Store
and hit Enter when it guesses correctly.
App Store looks like this:
Xcode looks like this on App Store:
Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type ⌘Space and start typing Terminal
and hit Enter when it guesses Terminal
.
Now install the command-line tools like this:
xcode-select --install
Then you can compile your code with by simply running gcc
as in the next line without having to fire up the big, ugly software development GUI called Xcode
:
gcc -Wall -o program program.c
Note: On newer versions of OS X, you would use clang
instead of gcc
, like this:
clang program.c -o program
Then you can run it with:
./program
Hello, world!
If your program is C++, you'll probably want to use one of these commands:
clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp
I use one Factory
module that contains one (or more) constructor per class which calls the Init
member of each class.
For example a Point
class:
Class Point
Private X, Y
Sub Init(X, Y)
Me.X = X
Me.Y = Y
End Sub
A Line
class
Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
If P1 Is Nothing Then
Set Me.P1 = NewPoint(X1, Y1)
Set Me.P2 = NewPoint(X2, Y2)
Else
Set Me.P1 = P1
Set Me.P2 = P2
End If
End Sub
And a Factory
module:
Module Factory
Function NewPoint(X, Y)
Set NewPoint = New Point
NewPoint.Init X, Y
End Function
Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
Set NewLine = New Line
NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function
Function NewLinePt(P1, P2)
Set NewLinePt = New Line
NewLinePt.Init P1:=P1, P2:=P2
End Function
Function NewLineXY(X1, Y1, X2, Y2)
Set NewLineXY = New Line
NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function
One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:
D = Distance(NewPoint(10, 10), NewPoint(20, 20)
or:
D = NewPoint(10, 10).Distance(NewPoint(20, 20))
It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init
call on each creator.
And it's fairly object oriented: the Init
functions are defined inside the objects.
EDIT
I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):
NewLine.DeleteAllLinesShorterThan 10
Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.
When you really want to write an i-test for a spring data repository you can do it like this:
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {
@Autowired
private WebBookingRepository repository;
@Test
public void testSaveAndFindAll() {
WebBooking webBooking = new WebBooking();
webBooking.setUuid("some uuid");
webBooking.setItems(Arrays.asList(new WebBookingItem()));
repository.save(webBooking);
Iterable<WebBooking> findAll = repository.findAll();
assertThat(findAll).hasSize(1);
webBooking.setId(1L);
assertThat(findAll).containsOnly(webBooking);
}
}
To follow this example you have to use these dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
If you're new to Subversion you may want to check out this post on SmashingMagazine.com, appropriately titled Ultimate Round-Up for Version Control with SubVersion.
It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.
It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true
.
You can also add multiple hidden fields. Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
var request = [];_x000D_
var container = '';_x000D_
console.log(arguments);_x000D_
request = arguments[0].hidden;_x000D_
console.log(arguments[0].hasOwnProperty('form'));_x000D_
if(arguments[0].hasOwnProperty('form') == true)_x000D_
{_x000D_
if(arguments[0].form.status == 'true'){_x000D_
var parent = document.getElementById("container");_x000D_
container = document.createElement('form');_x000D_
parent.appendChild(container);_x000D_
Object.assign(container, {'id':arguments[0].form.formID});_x000D_
}_x000D_
}_x000D_
else{_x000D_
container = document.getElementById("container");_x000D_
}_x000D_
_x000D_
//var container = document.getElementById("container");_x000D_
Object.keys(request).forEach(function(elem)_x000D_
{_x000D_
if($('#'+elem).length <= 0){_x000D_
console.log("Hidden Field created");_x000D_
var input = document.createElement('input');_x000D_
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
container.appendChild(input);_x000D_
}else{_x000D_
console.log("Hidden Field Exists and value is below" );_x000D_
$('#'+elem).val(request[elem]);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
If you are using Google Play services, make sure you aren't using this in your Gradle build script:
compile 'com.google.android.gms:play-services:8.3.0'
Only use those Google APIs that your app is really using. If all you are using is Google Maps, you would use this:
com.google.android.gms:play-services-maps:8.3.0
When I did this, my compile time went from over 2 minutes to around 25 seconds. For a list of the Google apis that you can selectively compile against, see:
Just a cooler swift syntax for Nate's answer:
[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
self.view.addGestureRecognizer(swipe)
})
I prefer to solve this in the classic way, creating a new array of my desired data type:
List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));
Using jQuery: $('#gift-close').trigger('click');
Using JavaScript: document.getElementById('gift-close').click();
Orion Adrian, let me invert your post to see how unfounded your remarks are, because a lot can be said about C++ as well. And telling that Java/C# compiler optimize away empty functions does really make you sound like you are not my expert in optimization, because a) why should a real program contain empty functions, except for really bad legacy code, b) that is really not black and bleeding edge optimization.
Apart from that phrase, you ranted blatantly about pointers, but don't objects in Java and C# basically work like C++ pointers? May they not overlap? May they not be null? C (and most C++ implementations) has the restrict keyword, both have value types, C++ has reference-to-value with non-null guarantee. What do Java and C# offer?
Generally, C and C++ can be just as fast or faster because the AOT compiler -- a compiler that compiles your code before deployment, once and for all, on your high memory many core build server -- can make optimizations that a C# compiled program cannot because it has a ton of time to do so. The compiler can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc, and if your compiler does not support runtime dispatch, you can solve for that yourself by deploying a handful of specialized binaries.
A C# program is commonly compiled upon running it so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware), and it must spend some time first. Features like loop fission, loop inversion, automatic vectorization, whole program optimization, template expansion, IPO, and many more, are very hard to be solved all and completely in a way that does not annoy the end user.
Additionally certain language features allow the compiler in C++ or C to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the Java/C# compiler to do. When you don't have access to the full type id of generics or a guaranteed program flow there's a lot of optimizations that just aren't safe.
Also C++ and C do many stack allocations at once with just one register incrementation, which surely is more efficient than Javas and C# allocations as for the layer of abstraction between the garbage collector and your code.
Now I can't speak for Java on this next point, but I know that C++ compilers for example will actually remove methods and method calls when it knows the body of the method is empty, it will eliminate common subexpressions, it may try and retry to find optimal register usage, it does not enforce bounds checking, it will autovectorize loops and inner loops and will invert inner to outer, it moves conditionals out of loops, it splits and unsplits loops. It will expand std::vector into native zero overhead arrays as you'd do the C way. It will do inter procedural optimmizations. It will construct return values directly at the caller site. It will fold and propagate expressions. It will reorder data into a cache friendly manner. It will do jump threading. It lets you write compile time ray tracers with zero runtime overhead. It will make very expensive graph based optimizations. It will do strength reduction, were it replaces certain codes with syntactically totally unequal but semantically equivalent code (the old "xor foo, foo" is just the simplest, though outdated optimization of such kind). If you kindly ask it, you may omit IEEE floating point standards and enable even more optimizations like floating point operand re-ordering. After it has massaged and massacred your code, it might repeat the whole process, because often, certain optimizations lay the foundation for even certainer optimizations. It might also just retry with shuffled parameters and see how the other variant scores in its internal ranking. And it will use this kind of logic throughout your code.
So as you can see, there are lots of reasons why certain C++ or C implementations will be faster.
Now this all said, many optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the number crunching, realtime and close-to-metal realm, but not exclusively there. You don't even have to touch a single pointer to come a long way.
So depending on what you're writing I would go with one or the other. But if you're writing something that isn't hardware dependent (driver, video game, etc), I wouldn't worry about the performance of C# (again can't speak about Java). It'll do just fine.
Generally, certain generalized arguments might sound cool in specific posts, but don't generally sound certainly credible.
Anyways, to make peace: AOT is great, as is JIT. The only correct answer can be: It depends. And the real smart people know that you can use the best of both worlds anyways.
In fact, in R, this operation is very easy:
If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:
a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a
If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:
#for a data.frame:
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b
Note the difference is.nan
when it's a matrix vs. is.na
when it's a data frame.
Doing
#...
b[is.nan(b)] <- 0
#...
yields: Error in is.nan(b) : default method not implemented for type 'list'
because b is a data frame.
Note: Edited for small but confusing typos
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b
never evaluates b
if a
evaluates to true
.
You can use JSONPath
Doing something like this:
results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")
Note that JSONPath returns an array of results
(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)
Adding my two cents for those searching for "Ensure that the org.eclipse.core.runtime bundle is resolved and started":
Adding "arbitrary" bundles to the list of bundles just because it seems that they are missing is not always the best solution. Sometimes it can get quite frustrating, because those new plugins might depend on other missing bundles, which need even more bundles and so on...
So, before adding a new dependency to the list of required bundles, make sure you understand why the bundle is needed (the debugger is your friend!).
This question here doesn't provide enough information to make this a valid answer in all cases, but if you encounter the message that the org.eclipse.core.runtime is missing, try setting the eclipse.application.launchDefault system property to false, especially if you try to run an application which is not an "eclipse application" (but maybe just a headless runtime on top of equinox).
This link might come in handy: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html, look for the eclipse.application.launchDefault system property.
Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.
So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.
Instead another simple way, but really performance costing is to cast before in dynamic.
(int)(dynamic)myObject.
You can try it in the Interactive window of VS.
public class Test
{
public static implicit operator int(Test v)
{
return 12;
}
}
(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
The issue, I think, was with a CSS library starting with comments.
While in development, I do not minify files and I don't remove comments. This meant that the stylesheet started with some comments, causing it to be seen as something different from CSS.
Removing the library and putting it into a vendor file (which is ALWAYS minified without comments) solved the issue.
Again, I'm not 100% sure this is a fix, but it's still a win for me as it works as expected now.
Check if rotation had changed with: viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
With the coordinator.animateAlongsideTransition(nil) { (UIViewControllerTransitionCoordinatorContext)
you can check if the transition is finished.
See code below:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition(nil) { (UIViewControllerTransitionCoordinatorContext) in
// if you want to execute code after transition finished
print("Transition finished")
}
if size.height < size.width {
// Landscape
print("Landscape")
} else {
// Portrait
print("Portrait")
}
}
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.Number = 12;
MyDynamic.MyMethod = new Func<int>(() =>
{
return 55;
});
Console.WriteLine(MyDynamic.MyMethod());
Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.
You can try also a tidyverse
library(tidyverse)
dummyData %>%
as.tibble() %>%
count(value)
# A tibble: 2 x 2
value n
<dbl> <int>
1 1 25
2 2 75
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.
If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.
In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..
Use intersection
or intersection_update
intersection :
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
ans = sorted(set(a).intersection(set(xyz)))
intersection_update:
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
b = set(a)
b.intersection_update(xyz)
then b
is your answer
After you clone the master repository, you just can execute
git fetch && git checkout <branchname>
I set the delegate of the UITextField
to my ViewController
class.
In that class I implemented this method as following:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.
So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"
Here's a quick reference: http://www.regular-expressions.info/reference.html
If a function does not return anything, e.g.:
def test():
pass
it has an implicit return value of None
.
Thus, as your pick*
methods do not return anything, e.g.:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
the lines that call them, e.g.:
word = pickEasy()
set word
to None
, so wordInput
in getInput
is None
. This means that:
if guess in wordInput:
is the equivalent of:
if guess in None:
and None
is an instance of NoneType
which does not provide iterator/iteration functionality, so you get that type error.
The fix is to add the return type:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
ngKeypress
, ngKeydown
and ngKeyup
are now part of AngularJS.
<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">
<!-- or call a controller/directive method and pass $event as parameter.
With access to $event you can now do stuff like
finding which key was pressed -->
<input ng-keypress="changed($event)">
Read more here:
https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup
Earlier solutions:
Solution 1: Use ng-change
with ng-model
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController" ng-change="keydown()">
JS:
function RegisterDataController($scope) {
$scope.keydown = function() {
/* validate $scope.mobileNumber here*/
};
}
Solution 2. Use $watch
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController">
JS:
$scope.$watch("mobileNumber", function(newValue, oldValue) {
/* change noticed */
});
please go to .env file and change the value of AWS_DEFAULT_REGION to special area u want to...
AWS_DEFAULT_REGION = Asia/Dhaka
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).
#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''
import sys
[...]
This should handle missing python executable as well but has a dependency on grep. See here for background.
npm start --prefix path/to/your/app
& inside package.json add the following script
"scripts": {
"preinstall":"cd $(pwd)"
}
On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -
my expected:
http://localhost/api/v1/admin/logs/testLog.log
would be encoded to:
http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log
If you need to do a comparison, transforming the url using:
addcslashes($url, '/')
allowed for the proper output during my comparisons.
Yes - just do it this way:
WITH DependencedIncidents AS
(
....
),
lalala AS
(
....
)
You don't need to repeat the WITH
keyword
use the dynamic keyword as return type.
private dynamic getValuesD<T>()
{
if (typeof(T) == typeof(int))
{
return 0;
}
else if (typeof(T) == typeof(string))
{
return "";
}
else if (typeof(T) == typeof(double))
{
return 0;
}
else
{
return false;
}
}
int res = getValuesD<int>();
string res1 = getValuesD<string>();
double res2 = getValuesD<double>();
bool res3 = getValuesD<bool>();
// dynamic keyword is preferable to use in this case instead of an object type
// because dynamic keyword keeps the underlying structure and data type so that // you can directly inspect and view the value.
// in object type, you have to cast the object to a specific data type to view // the underlying value.
regards,
Abhijit
after passing the vector by reference
swap(vector[position],vector[otherPosition]);
will produce the expected result.
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
return true if internet is actually available
Make sure you have these two permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.
android:usesCleartextTraffic="true"
@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.
@invertedSpear's comment in that answer worked in firefox but not in any IE version.
So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)
var hasFlash = false;
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) {
hasFlash = true;
}
} catch (e) {
if (navigator.mimeTypes
&& navigator.mimeTypes['application/x-shockwave-flash'] != undefined
&& navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
hasFlash = true;
}
}
I encounterred the same problem, while print out the json string opened from a json file, found the json string starts with '', which by doing some reserach is due to the file is by default decoded with UTF-8, and by changing encoding to utf-8-sig, the mark out is stripped out and loads json no problem:
open('test.json', encoding='utf-8-sig')
I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.
Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString
The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.
Then you would be able to use this in your XAML code:
DataFormatString="{}{0:P}"
I came around the same problem as the OP, and trying some solutions from the top answers above didn't prove to work for my scenarios. See why at the end.
Instead, I found this helpful script, to avoid confusion let's call it html2text_roundcube
, available under GPL:
It's actually an updated version of an already mentioned script - http://www.chuggnutt.com/html2text.php
- updated by RoundCube mail.
Usage:
$h2t = new \Html2Text\Html2Text('Hello, "<b>world</b>"');
echo $h2t->getText(); // prints Hello, "WORLD"
Why html2text_roundcube
proved better than the others:
Script http://www.chuggnutt.com/html2text.php
didn't work out of the box for cases with special HTML codes/names (eg ä
), or unpaired quotes (eg <p>25" Monitor</p>
).
Script https://github.com/soundasleep/html2text
had no option to hide or group the links at the end of the text, making a usual HTML page look bloated with links when in text-plain format; customizing the code for special treatment of how the transformation is done is not as straight forward as simply editing an array in html2text_roundcube
.
Use --table
to tell pg_dump
what table it has to backup:
pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname
the question is already solved since quite a long time, but for future reference a possible solution is
b = a.slice(0);
Be careful, this works correctly only if a is a non-nested array of numbers and strings
jQuery's .bind() fires in the order it was bound:
When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.
Source: http://api.jquery.com/bind/
Because jQuery's other functions (ex. .click()
) are shortcuts for .bind('click', handler)
, I would guess that they are also triggered in the order they are bound.
hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]]
Enumerable#collect
takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.
The Enumerable
module is pretty awesome. Knowing it well can save you lots of time and lots of code.
String x = JComboBox.getSelectedItem().toString();
will convert any value weather it is Integer, Double, Long, Short into text on the other hand,
String x = String.valueOf(JComboBox.getSelectedItem());
will avoid null values, and convert the selected item from object to string
No, You cannot publish on Github pages. Try Heroku or something like that. You can only deploy static sites on github pages. You can't deploy a server on github pages.
Here is the correct SOLUTION! Since the button doesn't have a defined attribute type, angular maybe attempting to issue the keyup event as a submit request and triggers the click event on the button.
<button type="button" ...></button>
Big thanks to DeborahK!
Angular2 - Enter Key executes first (click) function present on the form
Last 3 months
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)
Today
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)
You would have to configure your webserver to utilize PHP as handler for .html
files. This is typically done by modifying your with AddHandler
to include .html
along with .php
.
Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php
extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.
You mean you want to add a new row and only put data in a certain column? Try the following:
var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);
As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value
instead of whatever data type you imagine it would be.
To answer the final question (the others seem thoroughly answered above), "Should I bubble up the exact exception or mask it using Exception?"
I am assuming you mean something like this:
public void myMethod() throws Exception {
// ... something that throws FileNotFoundException ...
}
No, always declare the most precise exception possible, or a list of such. The exceptions you declare your method as capable of throwing are a part of the contract between your method and the caller. Throwing "FileNotFoundException"
means that it is possible the file name isn't valid and the file will not be found; the caller will need to handle that intelligently. Throwing Exception
means "Hey, sh*t happens. Deal." Which is a very poor API
.
In the comments on the first article there are some examples where "throws Exception
" is a valid and reasonable declaration, but that's not the case for most "normal
" code you will ever write.
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
I realise this is an old question but for anyone who does come across it this can be done using contenteditable
as shown in this JSFiddle.
Kudos to Alex who mentioned this in the comments (I didn't see that until now!)
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
Static libraries are compiled as part of an application, whereas shared libraries are not. When you distribute an application that depends on shared libaries, the libraries, eg. dll's on MS Windows need to be installed.
The advantage of static libraries is that there are no dependencies required for the user running the application - e.g. they don't have to upgrade their DLL of whatever. The disadvantage is that your application is larger in size because you are shipping it with all the libraries it needs.
As well as leading to smaller applications, shared libraries offer the user the ability to use their own, perhaps better version of the libraries rather than relying on one that's part of the application
There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.
Given a class with this definition:
public class Class1
{
private int CallMe()
{
return 1;
}
}
You can invoke it using this code:
Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);
int result = (int)callMeMethod.Invoke(c, null);
Console.WriteLine(result);
If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."
I found a shortcut: File - Project Structure - Tab:Dependencies Click on the green + sign, select support-v4 (or any other you need), click OK.
now go to your gradle file and see that is been added
It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:
function validate() {
// ...
}
const element = document.querySelector('#element');
['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
element.addEventListener(eventName, validate);
});
In Debian Jessie, this works nice:
ls -lah --group-directories-first
# l=use a long listing format
# a=do not ignore entries starting with .
# h=human readable
# --group-directories-first=(obvious)
# Note: add -r for reverse alpha
# You might consider using lh by appending to ~/.bashrc as the alias:
~$ echo "alias lh='ls -lah --group-directories-first'" >>~/.bashrc
# -- restart your terminal before using lh command --
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
If you can get away with it, static const
has a lot of advantages. It obeys the normal scope principles, is visible in a debugger, and generally obeys the rules that variables obey.
However, at least in the original C standard, it isn't actually a constant. If you use #define var 5
, you can write int foo[var];
as a declaration, but you can't do that (except as a compiler extension" with static const int var = 5;
. This is not the case in C++, where the static const
version can be used anywhere the #define
version can, and I believe this is also the case with C99.
However, never name a #define
constant with a lowercase name. It will override any possible use of that name until the end of the translation unit. Macro constants should be in what is effectively their own namespace, which is traditionally all capital letters, perhaps with a prefix.
You can alias the same table to give you the id's you want to insert by (if you are doing a row-by-row update:
UPDATE table1 tab1, table1 tab2 -- alias references the same table
SET
col1 = 1
,col2 = 2
. . .
WHERE
tab1.id = tab2.id;
Additionally, It should seem obvious that you can also update from other tables as well. In this case, the update doubles as a "SELECT" statement, giving you the data from the table you are specifying. You are explicitly stating in your query the update values so, the second table is unaffected.
I was getting this error because my cpp files was not added in the CMakeLists.txt file
Stop using (HTTP 1.0) | Replaced with (HTTP 1.1 since 1999) |
---|---|
Expires: [date] | Cache-Control: max-age=[seconds] |
Pragma: no-cache | Cache-Control: no-cache |
If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.
I'm looking at you Stackoverflow:
200 OK Pragma: no-cache Content-Type: application/json X-Frame-Options: SAMEORIGIN X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824 Strict-Transport-Security: max-age=15552000 Content-Length: 54 Accept-Ranges: bytes Date: Tue, 03 Apr 2018 19:03:12 GMT Via: 1.1 varnish Connection: keep-alive X-Served-By: cache-yyz8333-YYZ X-Cache: MISS X-Cache-Hits: 0 X-Timer: S1522782193.766958,VS0,VE30 Vary: Fastly-SSL X-DNS-Prefetch-Control: off Cache-Control: private
tl;dr: Pragma
is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.
[date]
(deprecated - HTTP 1.0)[seconds]
And the conditional requests:
Etag: W/“1d2e7–1648e509289”
If-None-Match: W/“1d2e7–1648e509289”
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
304 Not Modified
last-modified: Thu, 09 May 2019 19:15:47 GMT
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
document.querySelector('input').addEventListener('change', function(){_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(){_x000D_
var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
console.log(arrayBuffer);_x000D_
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;_x000D_
}_x000D_
reader.readAsArrayBuffer(this.files[0]);_x000D_
}, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
Did you set the proper settings in pg_hba.conf?
See https://help.ubuntu.com/stable/serverguide/postgresql.html how to do it.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "[email protected]";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}
A checkbox has a linked cell, which contains the True/False representing the state of the checkbox. It is much easier to reference this cell's value than the value of the embedded object which is the checkbox.
Manually: Right click on the checkbox, choose Format, click in the Linked Cell box, and select the cell to contain the checkbox value.
In code:
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Value = xlOff ' = unchecked xlOn = checked
.LinkedCell = "$A$1"
End With
You should also be able to do:
apt install sudo
sudo -i -u tomcat
Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.
Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.
But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.
for UNIQUEIDENTIFIER datatype in sql server try this
Alter table table_name
add ID UNIQUEIDENTIFIER not null unique default(newid())
If you want to create primary key out of that column use this
ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (ID);
You were almost done without any changes besides how you spyOn
.
When you use the spy, you have two options: spyOn
the App.prototype
, or component component.instance()
.
const spy = jest.spyOn(Class.prototype, "method")
The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.
const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);
The App.prototype
bit on the first line there are what you needed to make things work. A JavaScript class
doesn't have any of its methods until you instantiate it with new MyClass()
, or you dip into the MyClass.prototype
. For your particular question, you just needed to spy on the App.prototype
method myClickFn
.
jest.spyOn(component.instance(), "method")
const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");
This method requires a shallow/render/mount
instance of a React.Component
to be available. Essentially spyOn
is just looking for something to hijack and shove into a jest.fn()
. It could be:
A plain object
:
const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");
A class
:
class Foo {
bar() {}
}
const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance
const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.
Or a React.Component instance
:
const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");
Or a React.Component.prototype
:
/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.
I've used and seen both methods. When I have a beforeEach()
or beforeAll()
block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.
EDIT:
If you want to check the side effects of your myClickFn
you can just invoke it in a separate test.
const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/
EDIT:
Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn()
as opposed to jest.spyOn
, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.
function Component({ myClickFn, items }) {
const handleClick = (id) => {
return () => myClickFn(id);
};
return (<>
{items.map(({id, name}) => (
<div key={id} onClick={handleClick(id)}>{name}</div>
))}
</>);
}
const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);
You can use the following URL as per the WhatsApp FAQ:
https://wa.me/PHONENUMBERHERE
Add the country code in front of the number and don't add any plus (+) sign or any dashes (-) or any other characters in the number. Only integrers/numeric values.
You can also predefine a text message to start with:
https://wa.me/PHONENUMBERHERE/?text=urlencodedtext
This gets the timezone code (e.g., GMT
) in older javascript (I'm using google app script with old engine):
function getTimezoneName() {
return new Date().toString().get(/\((.+)\)/);
}
I'm just putting this here in case someone needs it.
This worked for me:
Go to the file (in your project):
node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js
and change:
bson = require('../build/Release/bson');
to:
bson = require('bson');
With neuraxle, you can easily solve this :
p = Pipeline([
# expected outputs shape: (n, 1)
OutputTransformerWrapper(NumpyRavel()),
# expected outputs shape: (n, )
RandomForestRegressor(**RF_tuned_parameters)
])
p, outputs = p.fit_transform(data_inputs, expected_outputs)
Neuraxle is a sklearn-like framework for hyperparameter tuning and AutoML in deep learning projects !
aggregate(speed~dive,data=df,FUN=mean)
dive speed
1 dive1 0.7059729
2 dive2 0.5473777
The error is not refering to myfunction
but to start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function_x000D_
const myfunction = async function(x, y) {_x000D_
return [_x000D_
x,_x000D_
y,_x000D_
];_x000D_
}_x000D_
_x000D_
// Start function_x000D_
const start = async function(a, b) {_x000D_
const result = await myfunction('test', 'test');_x000D_
_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// Call start_x000D_
start();
_x000D_
I use the opportunity of this question to advise you about an known anti pattern using await
which is : return await
.
WRONG
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// useless async here_x000D_
async function start() {_x000D_
// useless await here_x000D_
return await myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
CORRECT
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// Also point that we don't use async keyword on the function because_x000D_
// we can simply returns the promise returned by myfunction_x000D_
function start() {_x000D_
return myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
Also, know that there is a special case where return await
is correct and important : (using try/catch)
Simple you can use bellow class.
.nopadmar {_x000D_
padding: 0 !important;_x000D_
margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
<div class="row">_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
</div>_x000D_
</div>
_x000D_
Simple:
public static String decToHex(int dec)
{
return Integer.toHexString(dec);
}
As mentioned here: Java Convert integer to hex integer
For Unix systems command time
(/usr/bin/time) gives you that info if you pass -v. See Maximum resident set size
below, which is the maximum (peak) real (not virtual) memory that was used during program execution:
$ /usr/bin/time -v ls /
Command being timed: "ls /"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 250%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 315
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
Looking for solution to this problem as well. see something here: http://developer.android.com/training/volley/request.html
is it a good idea to directly use ImageRequest instead of ImageLoader? Seems ImageLoader uses it internally anyway. Does it miss anything important other than ImageLoader's cache support?
ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...
// Retrieves an image specified by the URL, displays it in the UI.
mRequestQueue = Volley.newRequestQueue(context);;
ImageRequest request = new ImageRequest(url,
new Response.Listener() {
@Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new Map<String, String>();
params.put("User-Agent", "one");
params.put("header22", "two");
return params;
};
mRequestQueue.add(request);
For those actually wanting to do a JOIN
you can also use:
UPDATE a
SET price = b_alias.unit_price
FROM a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value'
AND a.id = a_alias.id;
You can use the a_alias in the SET
section on the right of the equals sign if needed.
The fields on the left of the equals sign don't require a table reference as they are deemed to be from the original "a" table.
This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.
<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">
web
I guess the better option is to just use Curl or similar.
Here are the difference between POST, PUT and PATCH methods of a HTTP protocol.
POST
A HTTP.POST method always creates a new resource on the server. Its a non-idempotent request i.e. if user hits same requests 2 times it would create another new resource if there is no constraint.
http post method is like a INSERT query in SQL which always creates a new record in database.
Example: Use POST method to save new user, order etc where backend server decides the resource id for new resource.
PUT
In HTTP.PUT method the resource is first identified from the URL and if it exists then it is updated otherwise a new resource is created. When the target resource exists it overwrites that resource with a complete new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.
http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.
PUT request is idempotent i.e. hitting the same requests twice would update the existing recording (No new record created). In PUT method the resource id is decided by the client and provided in the request url.
Example: Use PUT method to update existing user or order.
PATCH
A HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.
http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.
Example: You could use PATCH method to update order status.
PATCH /api/users/40450236/order/10234557
Request Body: {status: 'Delivered'}
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
textview.setTypeface(Typeface.DEFAULT_BOLD);
setTypeface is the Attribute textStyle.
As Shankar V added, to preserve the previously set typeface attributes you can use:
textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
It looks like you are entering a blank line after the body of the if
statement. This is a cue to the interactive compiler that you are done with the block entirely, so it is not expecting any elif
/else
blocks. Try entering the code exactly like this, and only hit enter once after each line:
if guess == number:
print('Congratulations! You guessed it.')
elif guess < number:
pass # Your code here
else:
pass # Your code here
In addition, if you want to refer to the root directory, you can use:
/
Which will refer to the root. So, let's say we're in a file that's nested within a few levels of folders and you want to go back to the main index.html:
<a href="/index.html">My Index Page</a>
Robert is spot-on with further relative path explanations.
I like your answers a lot. It made working from cygwin / linux
hosts a lot easier. I combined start and end functions to make it secure.
SSH_ENV="$HOME/.ssh/.agent_env"
function start_agent {
echo "Initialising new SSH agent..."
eval `/usr/bin/ssh-agent`
echo 'export SSH_AUTH_SOCK'=$SSH_AUTH_SOCK >> ${SSH_ENV}
echo 'export SSH_AGENT_PID'=$SSH_AGENT_PID >> ${SSH_ENV}
echo succeeded
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
/usr/bin/ssh-add;
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
#ps ${SSH_AGENT_PID} doesn't work under cywgin
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
# create our own hardlink to the socket (with random name)
MYSOCK=/tmp/ssh_agent.${RANDOM}.sock
ln -T $SSH_AUTH_SOCK $MYSOCK
export SSH_AUTH_SOCK=$MYSOCK
end_agent()
{
# if we are the last holder of a hardlink, then kill the agent
nhard=`ls -l $SSH_AUTH_SOCK | awk '{print $2}'`
if [[ "$nhard" -eq 2 ]]; then
rm ${SSH_ENV}
/usr/bin/ssh-agent -k
fi
rm $SSH_AUTH_SOCK
}
trap end_agent EXIT
set +x
Try these steps: 1- click on Import project (Eclipse, ADT, ...)
2- Choose main directory of your Eclipse project
3- Keep the defaults. The first two options is for changing jar files into remote libraries (dependencies). It mean while building Android studio try to find library in local system or remote repositories. The last option is for showing only one folder as app after importing.
4- Then, you will see the summary of changes
5- Then, if you see Gradle project sync failed, you should go to project view (top left corner). Then, you should go to your project-> app and open build.gradle.
6- Then, you should change your compilesdkVersion and targetsdkVersion to your current version that you see in buildToolsVersion (mine is 23). For example, in my project I should change 17 to 23 in two places
7- If you see an error in your dependencies, you should change the version of it. For example, in my project I need to check which version of android support library I am using. So, I open the SDK manager and go to bottom to see the version. Then, I should replace my Android studio version with my current version and click try again from top right corner
I hope it helps.
You want matplotlib.pcolor
:
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)
plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()
This gives:
If you wanted to pass a dynamic param through to a function, inside a dynamic input::
<Input
onKeyPress={(event) => {
if (event.key === "Enter") {
this.doSearch(data.searchParam)
}
}}
placeholder={data.placeholderText} />
/>
Hope this helps someone. :)
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
See it in action:
matchObj = re.search("^(?!OK|\\.).*", item)
Don't forget to put .*
after negative look-ahead, otherwise you couldn't get any match ;-)
Just stick the img tag inside the h1 tag as part of the content.
If you're developing, and you're developing with a Windows machine, simply add localhost
as a Trusted Site.
And yes, per DarrylGriffiths' comment, although it may look like you're adding an Internet Explorer setting...
I believe those are Windows rather than IE settings. Although MS tend to assume that they're only IE (hence the alert next to "Enable Protected Mode" that it requries restarted IE)...
I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.
The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?
Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.
How to Find a Stored Procedure Containing Text or String
Many time we need to find the text or string in the stored procedure. Here is the query to find the containing text.
SELECT OBJECT_NAME(id)
FROM SYSCOMMENTS
WHERE [text] LIKE '%Text%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
For more information please check the given URL given below.
http://www.freshcodehub.com/Article/34/how-to-find-a-stored-procedure-containing-text-or-string
When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while
loop:
while(!cond) { ... }
If you need it at the end, use a do
... while
loop and negate the condition:
do { ... } while(!cond);
You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.
You can however have cells span multiple columns, such as:
<table>
<tr>
<td>25</td>
<td>50</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">75</td>
<td>20</td>
</tr>
</table>
As an aside, you should avoid using style attributes like border
and bgcolor
and prefer CSS for those.
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
Assuming your WebSocket server is listening on the same port as from which the page is being requested, I would suggest:
function createWebSocket(path) {
var protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
return new WebSocket(protocolPrefix + '//' + location.host + path);
}
Then, for your case, call it as follows:
var socket = createWebSocket(location.pathname + '/to/ws');
Download grade files from this url and extract all in a folder:? https://gradle.org/releases
Open file -> Setting in windows OS or Preferences in mac OS and in "Build, Execution, Deployment"
Click on "Gradle"
Check “Use local cradle distribution” and give that extracted folder path.
Run gradle.bat for Windows OS and gradle file for mac OS in that folder.
Then check “Offline work”.
"your extracted folder path"/gradle-4.10.2/bin/.gradle (for version 4.1.2 you can set your version)
Press OK and enjoy it.
Many ways to skin a cat... here's the way I just posted about:
:%s/[A-Z]/\L&/g
Likewise for upper case:
:%s/[a-z]/\U&/g
I prefer this way because I am using this construct (:%s/[pattern]/replace/g
) all the time so it's more natural.
The easiest way i tired in xcode 4.52 was to create an additional view and connect them by using segue modal(control drag the button from view one to the second view, chose Modal). Then drag in a button to second view or the modal view that you created. Control and drag this button to the header file and use action connection. This will create an IBaction in your controller.m file. Find your button action type in the code.
[self dismissViewControllerAnimated:YES completion:nil];
You can always try this:
/home/user/anaconda3/bin/pip install -r requirements.txt
This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command
conda install pip
Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>
getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.
There's a few more options discussed in the answer to this question
You could also invoke the new command feature of Terminal by pressing the Shift + ? + N
key combination. The command you put into the box will be run in a new Terminal window.
A linq-to-sql query isn't executed as code, but rather translated into SQL. Sometimes this is a "leaky abstraction" that yields unexpected behaviour.
One such case is null handling, where there can be unexpected nulls in different places. ...DefaultIfEmpty(0).Sum(0)
can help in this (quite simple) case, where there might be no elements and sql's SUM
returns null
whereas c# expect 0.
A more general approach is to use ??
which will be translated to COALESCE
whenever there is a risk that the generated SQL returns an unexpected null:
var creditsSum = (from u in context.User
join ch in context.CreditHistory on u.ID equals ch.UserID
where u.ID == userID
select (int?)ch.Amount).Sum() ?? 0;
This first casts to int?
to tell the C# compiler that this expression can indeed return null
, even though Sum()
returns an int
. Then we use the normal ??
operator to handle the null
case.
Based on this answer, I wrote a blog post with details for both LINQ to SQL and LINQ to Entities.
Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
It has to do with how the public members of the base class are exposed from the derived class.
As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
code:
class Main
{
public static void main(String[] args)
{
int a=10, b=20;
System.out.println(a + " " + b);
}
}
Input: none
Output: 10 20
Some of the columns in MySQL have an "on update" clause, see:
mysql> SHOW COLUMNS FROM your_table_name;
I'm not sure how to update this but will post an edit when I find out.
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
constructor(private sanitizer:DomSanitizer) {
this.name = 'Angular!'
this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
}
<div [style.background-image]="backgroundImg"></div>
See also
You can access elements of parent window from within an iframe by using window.parent
like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top
like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
I think you create a new workspace and import all project properly with his lib and also add external jar android-support-v4.jar
in adb bundle in sdk extra files. I think its work for you. Hope all the best
And also use the android support lib it may be help you and also update your adt bundle
SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:
--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX
--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC
There is no decent way to get that setting, at least not something browser independent.
But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader
You can also find a copy of the nuspec.xsd here as it seems to no longer be available:
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
For Mac ,
For AVD with 5.1.1 and 6.0 I used next script in windows:
set adb=adb -s emulator-5558
set arch=x64
set pie=
adb start-server
%adb% root
%adb% remount
rem %adb% shell mount -o remount,rw /system
%adb% shell setenforce 0
%adb% install common/Superuser.apk
%adb% push %arch%/su%pie% /system/bin/su
%adb% shell chmod 0755 /system/bin/su
%adb% push %arch%/su%pie% /system/xbin/su
%adb% shell chmod 0755 /system/xbin/su
%adb% shell su --install
%adb% shell "su --daemon&"
rem %adb% shell mount -o remount,ro /system
exit /b
Need UPDATE.zip from SuperSU. Unpacked them to any folder. Create bat file with content above. Do not forget specify necessary architecture and device: set adb=adb -s emulator-5558
and set arch=x64
. If you run Android above or equal 5.0, change set pie=
to set pie=.pie
. Run it. You get temporary root for current run.
If you got error on remount system partition then you need start AVD from command line. See below first step for Android 7.
If you want make it persistent - update binary in SuperSU and store system.img from temp folder as replace of default system.img.
How to convert the resulting temporary root on a permanent
First - it goes to SuperSu. It offers a binary upgrade. Update in the normal way. Reboot reject.
Second - only relevant for emulators. The same AVD. The bottom line is that changes in the system image will not be saved. You need to keep them for themselves.
There are already instructions vary for different emulators.
For AVD you can try to find a temporary file system.img, save it somewhere and use when you start the emulator.
In Windows it is located in the %LOCALAPPDATA%\Temp\AndroidEmulator
and has a name something like TMP4980.tmp
.
You copy it to a folder avd device (%HOMEPATH%\.android\avd\%AVD_NAME%.avd\
), and renamed to the system.img
.
Now it will be used at the start, instead of the usual. True if the image in the SDK is updated, it will have the old one.
In this case, you will need to remove this system.img
, and repeat the operation on its creation.
More detailed manual in Russian: http://4pda.ru/forum/index.php?showtopic=318487&view=findpost&p=45421931
For android 7 you need run additional steps:
1. Need run emulator manually.
Go to sdk folder sdk\tools\lib64\qt\lib
.
Run from this folder emulator with options -writable-system -selinux disabled
Like this:
F:\android\sdk\tools\lib64\qt\lib>F:\android\sdk\tools\emulator.exe -avd 7.0_x86 -verbose -writable-system -selinux disabled
You need restart adbd
from root:
adb -s emulator-5554 root
And remount system:
adb -s emulator-5554 remount
It can be doned only once per run emulator. And any another remount can break write mode. Because of this you not need run of any other commands with remount, like mount -o remount,rw /system
.
Another steps stay same - upload binary, run binary as daemon and so on.
Picture from AVD Android 7 x86 with root:
If you see error about PIE on execute su
binary - then you upload to emulator wrong binary. You must upload binary named su.pie
inside archive, but on emulator it must be named as su
, not su.pie
.
I was able to get past this by using the Array keyword instead of empty brackets:
const enhancers: Array<any> = [];
Use:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
That's my way to bind to code behind (see property DataTemplateSelector
)
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataTemplateSelector = new MyDataTemplateSelector();
InitializeComponent();
// ... more initializations ...
}
public DataTemplateSelector DataTemplateSelector { get; }
// ... more code stuff ...
}
In XAML will referenced by RelativeSource
via Ancestors up to containing Window
, so I'm at my Window
class and use the property via Path
declaration:
<GridViewColumn Header="Value(s)"
CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>
Setting of property DataTemplateSelector
before call InitializeComponent
depends on missing implementation of IPropertyChanged
or use of implementation with DependencyProperty
so no communication run on change of property DataTemplateSelector
.
Hit the following ssh restart
command in linux
prayag@prayag:~/backup/NoisyNeighbour$ service ssh restart
stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.75" (uid=1417676764 pid=5933 comm="stop ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
start: Rejected send message, 1 matched rules; type="method_call", sender=":1.76" (uid=1417676764 pid=5930 comm="start ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
The answers above pointed me in the right direction. Here is a generic version of what I got working:
var script = document.createElement('script');
script.src = 'http://' + location.hostname + '/module';
script.addEventListener('load', postLoadFunction);
document.head.appendChild(script);
function postLoadFunction() {
// add module dependent code here
}
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
If you're using Bootstrap 3, this works quite well
<a href="#" class="btn btn-primary btn-lg active" role="button">Primary link</a>
<a href="#" class="btn btn-default btn-lg active" role="button">Link</a>
function listAllItems(){
for (i=0; i<localStorage.length; i++)
{
key = localStorage.key(i);
alert(localStorage.getItem(key));
}
}
You may try to make the folder which include jsp-s become the source folder of eclipse, that solved the same problem of mine. As below:
- open project's properties.(right click project, then choose the Properties)
- choose Java Build Path, select the Source tab, click Add Folder and choose the folder including your jsp-s, OK
Can't you use simply display: none;
like this
HTML
<div id="web-title">
<a href="http://website.com" title="Website" rel="home">
<span class="webname">Website Name</span>
</a>
</div>
CSS
.webname {
display: none;
}
Or how about playing with visibility if you are concerned to reserve the space
.webname {
visibility: hidden;
}
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
Here's how I handle that:
$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
$error = error_get_last();
$error = explode(': ', $error['message']);
$error = trim($error[2]) . PHP_EOL;
fprintf(STDERR, 'Error: '. $error);
die();
}
After making configurations, you can check by writing this command on terminal
sysctl -a | grep file
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
try FocusManager.SetFocusedElement
FocusManager.SetFocusedElement(parentElement, txtCompanyID)
The differences are mentioned quite clearly in the documentation of array
and asarray
. The differences lie in the argument list and hence the action of the function depending on those parameters.
The function definitions are :
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
and
numpy.asarray(a, dtype=None, order=None)
The following arguments are those that may be passed to array
and not asarray
as mentioned in the documentation :
copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if
__array__
returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):
Set-Location -Path 'E:\FOLDER NAME'
Use Sql Server Profiler (tools menu) to monitor executing queries and use activity monitor in Management studio to see how is connected and if their connection is blocking other connections.
VueJs deep watch in child objects
new Vue({
el: "#myElement",
data: {
entity: {
properties: []
}
},
watch: {
'entity.properties': {
handler: function (after, before) {
// Changes detected. Do work...
},
deep: true
}
}
});
float s = sin(angle); // angle is in radians
float c = cos(angle); // angle is in radians
For clockwise rotation :
float xnew = p.x * c + p.y * s;
float ynew = -p.x * s + p.y * c;
For counter clockwise rotation :
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
If your're going the regex route, there's an error in tghw's example above.
<!-- WON'T WORK - item[0] is an index, not an item -->
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g,">"], [/"/g,
"""]]
for(var item in findReplace) {
escaped = escaped.replace(item[0], item[1]);
}
<!-- WORKS - findReplace[item[]] correctly references contents -->
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace) {
escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);
}
None of those worked for me. Try this.
console.log($(canvasjQueryElement)[0].width)
I am working on a multi-module Gradle project.
Modules are:
- core,
- service,
- geo,
- report,
- util and
- some other modules.
So primarily we have prepared a Component[locationRecommendHttpClientBuilder] in geo module.
import org.springframework.stereotype.Component
@Component("locationRecommendHttpClientBuilder")
class LocationRecommendHttpClientBuilder extends PanaromaHttpClientBuilder {
@Override
PanaromaHttpClient buildFromConfiguration() {
this.setURL(PanaromaConf.getInstance().getString("locationrecommend.url"))
this.setMethod(PanaromaConf.getInstance().getString("locationrecommend.method"))
this.setProxyHost(PanaromaConf.getInstance().getString("locationrecommend.proxy.host"))
this.setProxyPort(PanaromaConf.getInstance().getInt("locationrecommend.proxy.port", 0))
return super.build()
}
}
<bean id="locationRecommendHttpClient"
class="au.co.google.panaroma.platform.logic.impl.PanaromaHttpClient"
scope="singleton" factory-bean="locationRecommendHttpClientBuilder"
factory-method="buildFromConfiguration" />
Then it is decided to add this component in core module.
One engineer has previous code for geo module and then he has taken the latest module of core but he forgot to take the latest geo module.
So the component[locationRecommendHttpClientBuilder] is double times in his project and he was getting the following error.
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'LocationRecommendHttpClientBuilder' for bean class [au.co.google.app.locationrecommendation.builder.LocationRecommendHttpClientBuilder] conflicts with existing, non-compatible bean definition of same name and class [au.co.google.panaroma.platform.logic.impl.locationRecommendHttpClientBuilder]
After removal the component from geo module, component[locationRecommendHttpClientBuilder] is only available in core module. So there is no conflicting situation. Issue is solved by this way.
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
Since the problem is the non-trivial destructor so if the destructor is removed from the std::string
, it's possible to define a constexpr
instance of that type. Like this
struct constexpr_str {
char const* str;
std::size_t size;
// can only construct from a char[] literal
template <std::size_t N>
constexpr constexpr_str(char const (&s)[N])
: str(s)
, size(N - 1) // not count the trailing nul
{}
};
int main()
{
constexpr constexpr_str s("constString");
// its .size is a constexpr
std::array<int, s.size> a;
return 0;
}