here you go
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
If you limit yourself to repeating either a 0 or a space you can do:
For spaces:
printf("%*s", count, "");
For zeros:
printf("%0*d", count, 0);
I use the following, it also tests the extension which means it can be used for testing if the path supplied is a file but a file that doesn't exist.
private static bool isDirectory(string path)
{
bool result = true;
System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
if (fileTest.Exists == true)
{
result = false;
}
else
{
if (fileTest.Extension != "")
{
result = false;
}
}
return result;
}
This works for me:
$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages
--no-index
- Ignore package index (only looking at --find-links
URLs instead).
-f, --find-links <URL>
- If a URL or path to an HTML file, then parse for links to archives.
If a local path or file://
URL that's a directory, then look for archives in the directory listing.
This Python script has GUI to select with explorer a Ipython Notebook you want to convert to pdf. The approach with wkhtmltopdf is the only approach I found works well and provides high quality pdfs. Other approaches described here are problematic, syntax highlighting does not work or graphs are messed up.
You'll need to install wkhtmltopdf: http://wkhtmltopdf.org/downloads.html
and Nbconvert
pip install nbconvert
# OR
conda install nbconvert
Python script
# Script adapted from CloudCray
# Original Source: https://gist.github.com/CloudCray/994dd361dece0463f64a
# 2016--06-29
# This will create both an HTML and a PDF file
import subprocess
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename
WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf" # or wherever you keep it
def export_to_html(filename):
cmd = 'ipython nbconvert --to html "{0}"'
subprocess.call(cmd.format(filename), shell=True)
return filename.replace(".ipynb", ".html")
def convert_to_pdf(filename):
cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
subprocess.call(cmd, shell=True)
return filename.replace(".html", ".pdf")
def export_to_pdf(filename):
fn = export_to_html(filename)
return convert_to_pdf(fn)
def main():
print("Export IPython notebook to PDF")
print(" Please select a notebook:")
Tk().withdraw() # Starts in folder from which it is started, keep the root window from appearing
x = askopenfilename() # show an "Open" dialog box and return the path to the selected file
x = str(x.split("/")[-1])
print(x)
if not x:
print("No notebook selected.")
return 0
else:
fn = export_to_pdf(x)
print("File exported as:\n\t{0}".format(fn))
return 1
main()
ifdef $(HAVE_CLIENT) libtest_LIBS = \ $(top_builddir)/libclient.la else ifdef $(HAVE_SERVER) libtest_LIBS = \ $(top_builddir)/libserver.la else libtest_LIBS = endif endif
NOTE: DO NOT indent the if then it don't work!
One way of doing this would be by using ngClass directive and the $location service. In your template you could do:
ng-class="{active:isActive('/dashboard')}"
where isActive
would be a function in a scope defined like this:
myApp.controller('MyCtrl', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
}
});
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/KzAfG/
Repeating ng-class="{active:isActive('/dashboard')}"
on each navigation tab might be tedious (if you've got many tabs) so this logic might be a candidate for a very simple directive.
It is a simple 3 Step Process :
1) Go to your private repo and click on settings
2) To the left of the screen click on Manage access
3) Then Click on Invite Collaborator
This would be the Unicode solution
String s = "A função, Ãugent";
String r = s.replaceAll("\\P{InBasic_Latin}", "");
\p{InBasic_Latin}
is the Unicode block that contains all letters in the Unicode range U+0000..U+007F (see regular-expression.info)
\P{InBasic_Latin}
is the negated \p{InBasic_Latin}
per @dantheta's comment:
As of npm 1.1.65, Github URL can be more concise user/project. npmjs.org/doc/files/package.json.html You can attach the branch like user/project#branch
So
"babel-eslint": "babel/babel-eslint",
Or for tag v1.12.0 on jscs:
"jscs": "jscs-dev/node-jscs#v1.12.0",
Note, if you use npm --save, you'll get the longer git
From https://docs.npmjs.com/cli/v6/configuring-npm/package-json#git-urls-as-dependencies
Git URLs as Dependencies
Git urls are of the form:
git+ssh://[email protected]:npm/cli.git#v1.0.27
git+ssh://[email protected]:npm/cli#semver:^5.0
git+https://[email protected]/npm/cli.git
git://github.com/npm/cli.git#v1.0.27
If
#<commit-ish>
is provided, it will be used to clone exactly that commit. If > the commit-ish has the format#semver:<semver>
,<semver>
can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither#<commit-ish>
or#semver:<semver>
is specified, then master is used.
GitHub URLs
As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:
{ "name": "foo", "version": "0.0.0", "dependencies": { "express": "expressjs/express", "mocha": "mochajs/mocha#4727d357ea", "module": "user/repo#feature\/branch" } }```
I generated the "ssh" key again and added to my git account. This worked for me.
Please find following commands to generate the "ssh-key":
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
-> This creates a new ssh key, using the provided email as a label.
Generating public/private rsa key pair.
-> When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.
Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]
-> At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases"
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
-> Your key is generated, to copy the key:
$ sudo cat /root/.ssh/id_rsa-pub
Hope this works!
One gotcha I ran into today I think is worth pointing out related to this problem: if the url for the ajax call is redirected then the header for content-type: 'multipart/form-data' can be lost.
For example, I was posting to http://server.com/context?param=x
In the network tab of Chrome I saw the correct multipart header for this request but then a 302 redirect to http://server.com/context/?param=x (note the slash after context)
During the redirect the multipart header was lost. Ensure requests are not being redirected if these solutions are not working for you.
You should use UNION if you want to combine different resultsets. Try the following:
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A)
UNION
(SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id)
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
If you have new project on GitHub which has .travis.yml, but was never tested, you can run tests without commit this way:
In a SSL handshake the purpose of trustStore is to verify credentials and the purpose of keyStore is to provide credential.
keyStore
keyStore in Java stores private key and certificates corresponding to their public keys and require if you are SSL Server or SSL requires client authentication.
TrustStore
TrustStore stores certificates from third party, your Java application communicate or certificates signed by CA(certificate authorities like Verisign, Thawte, Geotrust or GoDaddy) which can be used to identify third party.
TrustManager
TrustManager determines whether remote connection should be trusted or not i.e. whether remote party is who it claims to and KeyManager decides which authentication credentials should be sent to the remote host for authentication during SSL handshake.
If you are an SSL Server you will use private key during key exchange algorithm and send certificates corresponding to your public keys to client, this certificate is acquired from keyStore. On SSL client side, if its written in Java, it will use certificates stored in trustStore to verify identity of Server. SSL certificates are most commonly comes as .cer file which is added into keyStore or trustStore by using any key management utility e.g. keytool.
Source: http://javarevisited.blogspot.ch
val saveButton:Button = findViewById(R.id.button_save)
saveButton.setOnClickListener{
// write code for click event
}
with view object
saveButton.setOnClickListener{
view -> // write code for click event
}
I didn't have a lot of success with the provided answers but I did find a really simple work around. In your storyboard, you can click on your UIViewController's Navigation Item and set the back button text. I set it to a single ' ' space and it gave me the behavior I was looking for.
Another cause for this might be case-insensitive file systems. If you have multiple folders in your repo on the same level whose names only differ by case, you will get hit by this. Browse the source repository using its web interface (e.g. GitHub or VSTS) to make sure.
For more information: https://stackoverflow.com/a/2016426/67824
Those who are facing this problem: Don't panic.
Short answer:
Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)
Long answer: Let's learn how to restart the router.
telnet 192.168.1.1
Run these commands:
mount_root ## this remounts your partitions from read-only to read/write mode
firstboot ## This will reset your router after reboot
reboot -f ## And force reboot
Log in the web interface using web browser.
link to see the official failsafe mode.
open the command prompt Go to project directory
type git remote add origin your git hub repository location with.git
If not work, try
1. clean the project.
2. deleted derived data.
if you don't know how to delete derived data go here
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
Another modification:
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.
Also, if the server fails to respond, it won't keep trying.
I've used a similar method in the past using .ajax to handle even more complex behaviour:
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.
This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
One difference is that:
:map
does nvo
== normal + (visual + select) + operator pending:map!
does ic
== insert + command-line modeas stated on help map-modes
tables.
So: map
does not map to all modes.
To map to all modes you need both :map
and :map!
.
In an elevated Command Prompt write this :
To disable:
bcdedit /set hypervisorlaunchtype off
To enable:
bcdedit /set hypervisorlaunchtype auto
(From comments - restart to take effect)
Running ALTER COLUMN
without mentioning attribute NOT NULL
will result in the column being changed to nullable, if it is already not. Therefore, you need to first check if the column is nullable and if not, specify attribute NOT NULL
. Alternatively, you can use the following statement which checks the nullability of column beforehand and runs the command with the right attribute.
IF COLUMNPROPERTY(OBJECT_ID('Employee', 'U'), 'Salary', 'AllowsNull')=0
ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL
ELSE
ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NULL
If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME
environment variable value for each build. Instead execute Maven like:
JAVA_HOME=/path/to/your/jdk mvn clean install
It will build using the specified JDK, but it won't change your environment variable.
Demo:
$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
if you are using SQLiteDatabase then there is a delete method
Definition of Delete
int delete (String table, String whereClause, String[] whereArgs)
Example Implementation
Now we can write a method called delete with argument as name
public void delete(String value) {
db.delete(DATABASE_TABLE, KEY_NAME + "=?", new String[]{String.valueOf(value)});
}
if you want to delete all records then just pass null to the above method,
public void delete() {
db.delete(DATABASE_TABLE, null, null);
}
You can get the week number directly from datetime as string.
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get different "types" of the week number of the year changing the strftime
parameter for:
%U
- Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53
%W
- Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53[...]
(Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the
strftime()
method.[...]
%V
- ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53from: datetime — Basic date and time types — Python 3.7.3 documentation
I've found out about it from here. It worked for me in Python 2.7.6
Assuming that the values in the dict are unique:
dict((v, k) for k, v in my_map.iteritems())
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
Templates are all about the compiler generating code at compile-time. Virtual functions are all about the run-time system figuring out which function to call at run-time.
Once the run-time system figured out it would need to call a templatized virtual function, compilation is all done and the compiler cannot generate the appropriate instance anymore. Therefore you cannot have virtual member function templates.
However, there are a few powerful and interesting techniques stemming from combining polymorphism and templates, notably so-called type erasure.
I want to point a different view on this general naming convention, e.g.:
see java.util.Set: boolean add?(E e)
where the rationale is:
do some processing then report whether it succeeded or not.
While the return
is indeed a boolean
the method's name should point the processing to complete instead of the result type (boolean for this example).
Your createFreshSnapshot
example seems for me more related to this point of view because seems to mean this: create a fresh-snapshot then report whether the create-operation succeeded. Considering this reasoning the name createFreshSnapshot
seems to be the best one for your situation.
All HIVE
managed tables are stored in the below HDFS
location.
hadoop fs -ls /user/hive/warehouse/databasename.db/tablename
With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share
set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf
My solution to this problem was to use the $() sub-expression block.
Add-Type -Language CSharp @"
public class Thing{
public string Name;
}
"@;
$x = New-Object Thing
$x.Name = "Bill"
Write-Output "My name is $($x.Name)"
Write-Output "This won't work right: $x.Name"
Gives:
My name is Bill
This won't work right: Thing.Name
String onevalue;
if(request.getParameterMap().containsKey("one")!=false)
{
onevalue=request.getParameter("one").toString();
}
Proper way (as of Go 1.13) (provided by answer below):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}
Original Answer:
Here's a way to do it without losing the default settings of the DefaultTransport
, and without needing the fake request as per user comment.
defaultTransport := http.DefaultTransport.(*http.Transport)
// Create new Transport that ignores self-signed SSL
customTransport := &http.Transport{
Proxy: defaultTransport.Proxy,
DialContext: defaultTransport.DialContext,
MaxIdleConns: defaultTransport.MaxIdleConns,
IdleConnTimeout: defaultTransport.IdleConnTimeout,
ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,
TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: customTransport}
Shorter way:
customTransport := &(*http.DefaultTransport.(*http.Transport)) // make shallow copy
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}
Warning: For testing/development purposes only. Anything else, proceed at your own risk!!!
I had a hard time solving this issue. If none of the above work you can try this instead. I am using the create-react-app
Requirements
react-router-dom": "^4.3.1"
Solution
At the location where router is specified
<Route path="some/path" ..../>
Add the parameter name that you would want to pass in like this
<Route path="some/path/:id" .../>
At the page where you are rendering some/path you can specify this to view the parameter name call id like this
componentDidMount(){
console.log(this.props);
console.log(this.props.match.params.id);
}
At the end where you export default
export default withRouter(Component);
Remember to include import
import { withRouter } from 'react-router-dom'
When console.log(this.props) you would be able what has been passed down. Have fun!
Then provided your button is showing and the click event is being fired you can call the following in your click event:
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag");
ft.commit();
and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.
ft.addToBackStack(null);
Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.
Your program is still running. You have to kill it by closing the command line window. If you press control alt delete, task manager, process`s (kill the ones that match your filename).
0123456789 is not a valid integer (usually zeros will be stripped)
I think something like this regexp would be better to use:
^[1-9]([0-9]*)$
(does not support signed numbers)
Easiest way:
byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
buffer = new byte[stream.Length - 1];
stream.Read(buffer, 0, buffer.Length);
}
using (Stream stream = new IO.FileStream("newFile.pdf"))
{
stream.Write(buffer, 0, buffer.Length);
}
Or something along these lines...
Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:
[x[1] for x in L]
[]
's around the line of code. These are what define a list. This tells you that this code returns a list, so it's of the list
type. Hence, this technique is called a "list comprehension."L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
prior to executing the above code.x
is a variable that only exists in the comprehension - try to access x
outside of the comprehension, or type type(x)
after executing the above line and it will tell you NameError: name 'x' is not defined
, whereas type(L)
returns <class 'list'>
.x[1]
points to the second item in each of the tuples whereas x[0]
would point to each of the first items.It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.
I was having similar problem. It was just inserting one from the list of arrays. It worked after making the below changes.
Hope this helps. I am using mysql npm.
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
Dim iPos = -1
Dim iFound = 0
Do
iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
If iPos <> -1 Then
iFound += 1
End If<br/>
Loop Until iPos = -1
Return iFound
End Function
Code Usage:
Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")
Also you can have it as an extension:
<Extension()> _
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
Dim iPos = -1
Dim iFound = 0
Do
iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
If iPos <> -1 Then
iFound += 1
End If
Loop Until iPos = -1
Return iFound
End Function
Code Usage:
Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")
$.get("/folder_name/filename.xml", function (xml) {_x000D_
var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
});
_x000D_
Encountered this issue and changing the debug port helped. For some reason, the debug port had to be greater than the app port.
My modified support library supports using both View animations (i.e. <translate>, <rotate>
) and Object Animators (i.e. <objectAnimator>
) for Fragment Transitions. It is implemented with NineOldAndroids. Refer to my documentation on github for details.
Not saying this is the best approach, but it seems to work for me.
The full code may be found at: Example code at: https://github.com/dbleicher/recyclerview-grid-quickreturn
First off, add the expanded area to your cell/item layout, and make the enclosing cell layout animateLayoutChanges="true". This will ensure that the expand/collapse is animated:
<LinearLayout
android:id="@+id/llCardBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:animateLayoutChanges="true"
android:padding="4dp"
android:orientation="vertical">
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|fill_horizontal"
android:padding="10dp"
android:gravity="center"
android:background="@android:color/holo_green_dark"
android:text="This is a long title to show wrapping of text in the view."
android:textColor="@android:color/white"
android:textSize="16sp" />
<TextView
android:id="@+id/tvSubTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|fill_horizontal"
android:background="@android:color/holo_purple"
android:padding="6dp"
android:text="My subtitle..."
android:textColor="@android:color/white"
android:textSize="12sp" />
<LinearLayout
android:id="@+id/llExpandArea"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:text="Item One" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:text="Item Two" />
</LinearLayout>
</LinearLayout>
Then, make your RV Adapter class implement View.OnClickListener so that you can act on the item being clicked. Add an int field to hold the position of the one expanded view, and initialize it to a negative value:
private int expandedPosition = -1;
Finally, implement your ViewHolder, onBindViewHolder() methods and override the onClick() method. You will expand the view in onBindViewHolder if it's position is equal to "expandedPosition", and hide it if not. You set the value of expandedPosition in the onClick listener:
@Override
public void onBindViewHolder(RVAdapter.ViewHolder holder, int position) {
int colorIndex = randy.nextInt(bgColors.length);
holder.tvTitle.setText(mDataset.get(position));
holder.tvTitle.setBackgroundColor(bgColors[colorIndex]);
holder.tvSubTitle.setBackgroundColor(sbgColors[colorIndex]);
if (position == expandedPosition) {
holder.llExpandArea.setVisibility(View.VISIBLE);
} else {
holder.llExpandArea.setVisibility(View.GONE);
}
}
@Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
String theString = mDataset.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(mContext, "Clicked: "+theString, Toast.LENGTH_SHORT).show();
}
/**
* Create a ViewHolder to represent your cell layout
* and data element structure
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvSubTitle;
LinearLayout llExpandArea;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
llExpandArea = (LinearLayout) itemView.findViewById(R.id.llExpandArea);
}
}
This should expand only one item at a time, using the system-default animation for the layout change. At least it works for me. Hope it helps.
refinement on moylop260's answer:
import serial.tools.list_ports
comlist = serial.tools.list_ports.comports()
connected = []
for element in comlist:
connected.append(element.device)
print("Connected COM ports: " + str(connected))
This lists the ports that exist in hardware, including ones that are in use. A whole lot more information exists in the list, per the pyserial tools documentation
I think the best approach is just add ".passive"
v-on:scroll.passive='handleScroll'
try this:
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
Then you can add a base controller.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
In you controller, you would do:
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}
More information about how you'll be working with your data before transferring it would help a ton. The json module provides dump(s) and load(s) methods that'll help if you're using 2.6 or newer: http://docs.python.org/library/json.html.
-- EDITED --
Without knowing which libraries you're using I can't tell you for sure if you'll find a method like that. Normally, I'll process query results like this (examples with kinterbasdb because it's what we're currently working with):
qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
# Assumes conn is a database connection.
cursor = conn.cursor()
cursor.execute(qry)
rows = [x for x in cursor]
cols = [x[0] for x in cursor.description]
songs = []
for row in rows:
song = {}
for prop, val in zip(cols, row):
song[prop] = val
songs.append(song)
# Create a string representation of your array of songs.
songsJSON = json.dumps(songs)
There are undoubtedly better experts out there who'll have list comprehensions to eliminate the need for written out loops, but this works and should be something you could adapt to whatever library you're retrieving records with.
<script>
function SetBack(dir) {
document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>
With debounce
you need to keep the original synthetic event around with event.persist()
. Here is working example tested with React 16+
.
import React, { Component } from 'react';
import debounce from 'lodash/debounce'
class ItemType extends Component {
evntHandler = debounce((e) => {
console.log(e)
}, 500);
render() {
return (
<div className="form-field-wrap"
onClick={e => {
e.persist()
this.evntHandler(e)
}}>
...
</div>
);
}
}
export default ItemType;
With functional component, you can do this -
const Search = ({ getBooks, query }) => {
const handleOnSubmit = (e) => {
e.preventDefault();
}
const debouncedGetBooks = debounce(query => {
getBooks(query);
}, 700);
const onInputChange = e => {
debouncedGetBooks(e.target.value)
}
return (
<div className="search-books">
<Form className="search-books--form" onSubmit={handleOnSubmit}>
<Form.Group controlId="formBasicEmail">
<Form.Control type="text" onChange={onInputChange} placeholder="Harry Potter" />
<Form.Text className="text-muted">
Search the world's most comprehensive index of full-text books.
</Form.Text>
</Form.Group>
<Button variant="primary" type="submit">
Search
</Button>
</Form>
</div>
)
}
References - - https://gist.github.com/elijahmanor/08fc6c8468c994c844213e4a4344a709 - https://blog.revathskumar.com/2016/02/reactjs-using-debounce-in-react-components.html
If you don't want to use absolute positioning and all that jazz, here's a fix I like to use:
your html:
<body>
<div id="header"></div>
<div id="wrapper"></div>
</body>
your css:
body {
height:100%;
padding-top:60px;
}
#header {
margin-top:60px;
height:60px;
}
#wrapper {
height:100%;
}
Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.
Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.
The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
Try this with SQL join statements
CREATE PROCEDURE [dbo].[deleteItem]
@ItemId int = 0
AS
Begin
DECLARE @cnt int;
SET NOCOUNT ON
SELECT @cnt =COUNT(ttm.Id)
from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium
ON itr.Id = ium.ItemTransactionId INNER JOIN ItemMaster im
ON itr.ItemId = im.Id INNER JOIN TransactionTypeMaster ttm
ON itr.TransactionTypeMasterId = ttm.Id
where im.Id = @ItemId
if(@cnt = 1)
Begin
DECLARE @transactionType varchar(255);
DECLARE @mesurementAmount float;
DECLARE @itemTransactionId int;
DECLARE @itemUnitMeasurementId int;
SELECT @transactionType = ttm.TransactionType, @mesurementAmount = ium.Amount, @itemTransactionId = itr.Id, @itemUnitMeasurementId = ium.Id
from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium
ON itr.Id = ium.ItemTransactionId INNER JOIN TransactionTypeMaster ttm
ON itr.TransactionTypeMasterId = ttm.Id
where itr.ItemId = @ItemId
if(@transactionType = 'Close' and @mesurementAmount = 0)
Begin
delete from ItemUnitMeasurement where Id = @itemUnitMeasurementId;
End
else
Begin
delete from ItemTransaction where Id = @itemTransactionId;
End
End
else
Begin
delete from ItemMaster where Id = @ItemId;
End
END
inner join with scala
val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
I know the OP is asking about international country codes but for North America, you could use the following:
<a href="tel:+1-847-555-5555">1-847-555-5555</a>
<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
This might help you.
I realize this is an old question, but the same issue happened to me, but for a completely different reason.
It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.
You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.
You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.
Just download the jar and import it into your classpath, or add it as a maven dependency:
<dependency>
<groupId>com.jtattoo</groupId>
<artifactId>JTattoo</artifactId>
<version>1.6.11</version>
</dependency>
Here is a list of some of the cool themes they have available:
Regards
Added below
JAVA_TOOL_OPTIONS=-DadditionalJOption=-Xdoclint:none
Into Jenkins job :
Configuration > Build Environment > Inject environment variables to the build process > Properties Content
Solved my problem of code building through Jenkins Maven :-)
The question is about matplotlib
, but for the sake of any R users that end up here given the language-agnostic title:
If you're using an R kernel, just use:
options(repr.plot.width=4, repr.plot.height=3)
Only using class names is not sufficient in your case.
By.cssSelector(".ban")
has 15 matching nodesBy.cssSelector(".hot")
has 11 matching nodesBy.cssSelector(".ban.hot")
has 5 matching nodesTherefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.
Option 1: Using list items' index (CssSelector or XPath)
Limitations
Example:
driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));
Option 2: Using Selenium's FindElements
, then index them. (CssSelector or XPath)
Limitations
Example:
// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];
Option 3: Using text (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));
Option 4: Index the grouped selector (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));
Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)
Limitations
Example:
driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notation
for matrix multiplication: if a and b are matrices, then a*b
is their matrix
product.
import numpy as np
a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
# [2 1]]
print(b)
# [[1 2]
# [3 4]]
print(a*b)
# [[13 20]
# [ 5 8]]
On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @
operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.
import numpy as np
a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
# [ 5 8]]
Both matrix objects and ndarrays have .T
to return the transpose, but matrix
objects also have .H
for the conjugate transpose, and .I
for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are
applied element-wise (except for the new @
operator). Thus, if a
and b
are numpy arrays, then a*b
is the array
formed by multiplying the components element-wise:
c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
# [6 4]]
To obtain the result of matrix multiplication, you use np.dot
(or @
in Python >= 3.5, as shown above):
print(np.dot(c,d))
# [[13 20]
# [ 5 8]]
The **
operator also behaves differently:
print(a**2)
# [[22 15]
# [10 7]]
print(c**2)
# [[16 9]
# [ 4 1]]
Since a
is a matrix, a**2
returns the matrix product a*a
.
Since c
is an ndarray, c**2
returns an ndarray with each component squared
element-wise.
There are other technical differences between matrix objects and ndarrays
(having to do with np.ravel
, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.
Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.
If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,
since np.asmatrix
and np.asarray
allow you to convert one to the other (as
long as the array is 2-dimensional).
There is a synopsis of the differences between NumPy arrays
vs NumPy matrix
es here.
Try using ,
$('#points').val(request.responseText);
It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.
It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:
string = string.replace("to", "xyz");
or
String newString = string.replace("to", "xyz");
API Docs
public String replace (CharSequence target, CharSequence replacement)
Since: API Level 1
Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.
Parameters
target
the sequence to replace.replacement
the replacement
sequence.Returns the resulting string.
Throws NullPointerException
if target or replacement is null.
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Use this:
List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);
The following code will replace all non ASCII characters with question marks.
"".join([x if ord(x) < 128 else '?' for x in s])
This will keep the right aspect ratio.
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
Use the value attribute of the button element to pass the id, as
<button onClick={this.handleRemove} value={id}>Remove</button>
and then in handleRemove, read the value from event as:
handleRemove(event) {
...
remove(event.target.value);
...
}
This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.
Styling the infowindow is fairly straightforward with vanilla javascript. I used some of the info from this thread when writing this. I also took into account the possible problems with earlier versions of ie (although I have not tested it with them).
var infowindow = new google.maps.InfoWindow({
content: '<div id="gm_content">'+contentString+'</div>'
});
google.maps.event.addListener(infowindow,'domready',function(){
var el = document.getElementById('gm_content').parentNode.parentNode.parentNode;
el.firstChild.setAttribute('class','closeInfoWindow');
el.firstChild.setAttribute('title','Close Info Window');
el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
el.setAttribute('class','infoWindowContainer');
for(var i=0; i<11; i++){
el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
el.style.display = 'none';
}
});
The code creates the infowindow as usual (no need for plugins, custom overlays or huge code), using a div with an id to hold the content. This gives a hook in the system that we can use to get the correct elements to manipulate with a simple external stylesheet.
There are a couple of extra pieces (that are not strictly needed) which handle things like giving a hook into the div with the close info window image in it.
The final loop hides all the pieces of the pointer arrow. I needed this myself as I wanted to have transparency on the infowindow and the arrow got in the way. Of course, with the hook, changing the code to replace the arrow image with a png of your choice should be fairly simple too.
If you want to change it to jquery (no idea why you would) then that should be fairly simple.
I'm not usually a javascript developer so any thoughts, comments, criticisms welcome :)
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
I know this is not typical alert box, but I hope it may help someone.
There is this expansion that enables you to show notifications inside HTML page using bootstrap.
It is very easy to implement and it works fine. Here is a github page for the project including some demo images.
a "wrapper" is just a term for some element that encapsulates all other visual elements on the page. The body
tag seems to fit the bill, but you would be at the mercy of the browser to determine what displays beneath that if you adjust the max-width
.
Instead, we use div
because it acts as a simple container that does not break. the main
, header
, footer
, and section
tags in HTML5 are just div
elements named appropriately. It seems that there could (or should) be a wrapper
tag because of this trend, but you may use whichever method of wrapping you find most suitable for your situation. through classes, ids and css, you can use a span
tag in a very similar way.
There are a lot of HTML element tags that we do not use often or possibly even know about. Doing some research would show you what can be done with pure HTML.
Based on Ali's and Champitoad's answer:
If you want to try different palettes for the same, you can do this in a few lines:
cmap=plt.cm.get_cmap(plt.cm.viridis,143)
^143 being the number of colours you're sampling
I picked 143 because the entire range of colours on the colormap comes into play here. What you can do is sample the nth colour every iteration to get the colormap effect.
n=20
for i,(x,y) in enumerate(points):
plt.scatter(x,y,c=cmap(n*i))
I think why you want to zoom-in and zoom-out the image view is because your image view is small and zooming in the image there will not let the image come out of the image view. Instead, image starts disappearing from the boundaries while zooming in. So letting the image come out of the image while we zoom in is what you want I guess.
So there are two tricks (according to me) to achieve this-
Trick no.1 does not work when the image View is nested very much inside other views (like in nested recycler view)
Trick no.2 works always :-)
Here is the implementation of trick no.2 -
public class ZoomOnTouchListener extends AppCompatActivity implements View.OnTouchListener {
private Matrix matrix = new Matrix();
private boolean isfullImgViewActive = false;
// above boolean gets true when when we firstly move 2 fingers on the smallImgView and in this case smallImgView gets invisible and fullImgView gets visible
// and false if smallImgView is visible and fullImgView is gone
private float[] matrixArray = new float[9];
private float orgScale;
private PointF start = new PointF();
private PointF prevP1 = new PointF();
private PointF prevP2 = new PointF();
private PointF mid = new PointF();
private float oldDist = 1f;
private ImageView mfullImgView;
private ImageView smallImgView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfullImgView = (ImageView)findViewById(R.id.imgView2);
mfullImgView.setVisibility(View.GONE);
smallImgView = (ImageView)findViewById(R.id.imgView);
smallImgView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
//Log.i("0", "OnTouch()");
if(v instanceof ImageView) {
ImageView imgView = (ImageView) v;
boolean isImgViewSmall = (imgView == smallImgView);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
//Log.i("T", "Motion Event: ACTION_DOWN");
if(isImgViewSmall)
start.set(event.getX(), event.getY());
prevP1.set(event.getX(), event.getY());
return true;
case MotionEvent.ACTION_POINTER_DOWN: //second finger and other fingers down
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
oldDist = spacing(event);
midPoint(mid, event);
break;
case MotionEvent.ACTION_MOVE: //it doesn't mean fingers are moved. In this case, all pointers which are active are batched together
// this case occurs after action_down or action_pointer_down
//Log.i("Tag", event.getX()+","+event.getY());
if(event.getPointerCount() == 2) {
PointF newMid = new PointF();
midPoint(newMid,event);
float newDist = spacing(event);
float scale = newDist/oldDist;
if( !isfullImgViewActive){ // is smallImgView is visible and mfullImgView is gone
Log.i("tag", "true");
isfullImgViewActive = true;
matrix.set(imgView.getImageMatrix()); //note:- do not write matrix = imgView.getImageMatrix() because it gives the smallImgView's matrix reference to the matrix variable and changes on matrix will reflect on smallImgView
matrix.getValues(matrixArray);
orgScale = matrixArray[0];
smallImgView.setVisibility(View.INVISIBLE);
mfullImgView.setImageDrawable(smallImgView.getDrawable());
mfullImgView.setScaleType(ImageView.ScaleType.MATRIX);
mfullImgView.setVisibility(View.VISIBLE);
//To map the image of mFullImgView to that of smallImgView we have to
// translate the mFullImgView's image
matrix.postTranslate(tx, ty);
/////////////NOTE///////////////
//here (tx,ty) are coordinates of top-left corner of smallimgView and
// they MUST be relative to the origin of Outermost view or view group
// where fullImgView is placed. So find tx,ty in your case by yourself
mfullImgView.setImageMatrix(matrix);
}
if(isImgViewSmall) {
matrix.postScale(scale, scale, mid.x + tx, mid.y + ty);
}
else{
matrix.postScale(scale, scale, mid.x, mid.y);
}
oldDist = newDist;
matrix.postTranslate(newMid.x - mid.x, newMid.y - mid.y);
matrix.getValues(matrixArray);
mid.set(newMid);
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
}
else if(event.getPointerCount() == 1 ){
if(isfullImgViewActive) {
matrix.postTranslate(event.getX() - prevP1.x, event.getY() - prevP1.y);
matrix.getValues(matrixArray);
}
prevP1.set(event.getX(0), event.getY(0));
}
break;
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
//Now if pointer of index 0 is lifted then pointer of index 1 will get index 0;
if(event.getActionIndex() == 0 && isfullImgViewActive){
Log.i("TAg", event.getActionIndex()+"");
prevP1.set(prevP2);
}
break;
case MotionEvent.ACTION_UP: // first finger lifted or all fingers are lifted
if(isImgViewSmall && !isfullImgViewActive) {
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
int xDiff = (int) Math.abs(event.getX() - start.x);
int yDiff = (int) Math.abs(event.getY() - start.y);
if (xDiff == 0 && yDiff == 0) {
imgView.performClick();
return true;
}
}
if(isfullImgViewActive){
if(matrixArray[0] <= orgScale){ //matrixArray[0] is Scale.X value
mfullImgView.setOnTouchListener(null);
mfullImgView.setImageDrawable(null);
mfullImgView.setVisibility(View.GONE);
smallImgView.setOnTouchListener(this);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.VISIBLE);
isfullImgViewActive = false;
}
else if(matrixArray[0] > orgScale && isImgViewSmall){ //if the imgView was smallImgView
smallImgView.setOnTouchListener(null);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.GONE); // or View.INVISIBLE
mfullImgView.setOnTouchListener(this);
}
}
return true;
}
//end of Switch statement
if(isfullImgViewActive) { //active means visible
mfullImgView.setImageMatrix(matrix); // display the transformation on screen
}
return true; // indicate event was handled
}
else
return false;
}
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event)
{
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
}
NOTE:- Don't set OnClickListener to mfullImgView before setting onTouchListener to it. Setting that will let the fullImageView(if it is visible) steal the touch event of putting second finger down after lifting it for the first time because we want to let the smallImgView take all the touch events until all the fingers are lifted up for the first time.
Another reason projects use simplejson is that the builtin json did not originally include its C speedups, so the performance difference was noticeable.
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
maybe u want to provide the same width and height for 2 container
Container(
width: size.width * 0.30, height: size.height * 0.4,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6)
),
child: Center(
child: Text(categoryName, textAlign: TextAlign.center, style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17,
color: Colors.white,
),),
),
The mysql
deamon should be running.
If not try this:
#/etc/init.d/mysql start
Or this:
#service mysqld start
And if you want to add mysql on boot:
# chkconfig --add mysqld
# chkconfig -- level 235 mysqld on
If yes, and it is still not working try this:
Uncomment the following lines in /etc/php/php.ini
extension=mysqli.so
extension=mysql.so
And please check your post above '/usr/lib64/php/modules/msql.so'. It should be mysql.so (if it's mistyped ignore it...)
why not pull the data directly out of the data source.
DataBinder.Eval(e.Row.DataItem, "ColumnName")
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
Ternary operator example.If the value of isFemale boolean variable is YES, print "GENDER IS FEMALE" otherwise "GENDER IS MALE"
? means = execute the codes before the : if the condition is true.
: means = execute the codes after the : if the condition is false.
Objective-C
BOOL isFemale = YES; NSString *valueToPrint = (isFemale == YES) ? @"GENDER IS FEMALE" : @"GENDER IS MALE"; NSLog(valueToPrint); //Result will be "GENDER IS FEMALE" because the value of isFemale was set to YES.
For Swift
let isFemale = false let valueToPrint:String = (isFemale == true) ? "GENDER IS FEMALE" : "GENDER IS MALE" print(valueToPrint) //Result will be "GENDER IS MALE" because the isFemale value was set to false.
For the above code to function; you need to make sure the following directories exist (mine didn't). Just add the following to a bat and run it:
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Startup
mkdir C:\Windows\System32\GroupPolicy\User\Scripts\Shutdown
It's just that GP needs those directories to exist for:
Group Policy\Local Computer Policy\Windows Settings\Scripts (Startup/Shutdown)
to function properly.
I made following changes in web.config
to get the SOAP (Request/Response) Envelope. This will output all of the raw SOAP information to the file trace.log
.
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="System.Net" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
<source name="System.Net.Sockets" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log"/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Sockets" value="Verbose"/>
</switches>
</system.diagnostics>
Late to the party, but might be of interest...
I find a combination of labs
and guides
specification useful in many cases:
You want nothing but a grid and a background:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
labs(x = NULL, y = NULL) +
guides(x = "none", y = "none")
You want to only suppress the tick-mark label of one or both axes:
ggplot(diamonds, mapping = aes(x = clarity)) +
geom_bar(aes(fill = cut)) +
guides(x = "none", y = "none")
Edit: WARNING - seems this doesn't work in all cases, but works well on many public scripts.
If you have a bash script called "control" and inside it you have a function called "build":
function build() {
...
}
Then you can call it like this (from the directory where it is):
./control build
If it's inside another folder, that would make it:
another_folder/control build
If your file is called "control.sh", that would accordingly make the function callable like this:
./control.sh build
Depending on where you are in the kestrel pipeline - if you have access to IConfiguration
(Startup.cs
constructor) or IWebHostEnvironment
(formerly IHostingEnvironment
) you can either inject the IWebHostEnvironment
into your constructor or just request the key from the configuration.
IWebHostEnvironment
in Startup.cs
Constructorpublic Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var contentRoot = env.ContentRootPath;
}
public Startup(IConfiguration configuration)
{
var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
}
It should be like this :
<string name="game_settings_dragNDropMove_checkBox">Move by Drag&Drop</string>
If you need to change the bottom position of the modal, you need to modify the max-height of the modal-body:
.modal-body {
max-height: 75vh;
}
As other answers have said, you can adjust the right and top on the modal-dialog :
.modal-dialog {
top: 10vh;
right: 5vw;
}
console.log
takes multiple arguments, so just use:
console.log("story", name, "story");
If name is an object
or an array
then using multiple arguments is better than concatenation. If you concatenate an object
or array
into a string you simply log the type rather than the content of the variable.
But if name is just a primitive type then multiple arguments works the same as concatenation.
Did you try?
protect_from_forgery with: :null_session, if: Proc.new {|c| c.request.format.json? }
Use css @keyframes
.elementToFadeInAndOut {
opacity: 1;
animation: fade 2s linear;
}
@keyframes fade {
0%,100% { opacity: 0 }
50% { opacity: 1 }
}
here is a DEMO
.elementToFadeInAndOut {_x000D_
width:200px;_x000D_
height: 200px;_x000D_
background: red;_x000D_
-webkit-animation: fadeinout 4s linear forwards;_x000D_
animation: fadeinout 4s linear forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
0%,100% { opacity: 0; }_x000D_
50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
0%,100% { opacity: 0; }_x000D_
50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
Reading: Using CSS animations
You can clean the code by doing this:
.elementToFadeInAndOut {_x000D_
width:200px;_x000D_
height: 200px;_x000D_
background: red;_x000D_
-webkit-animation: fadeinout 4s linear forwards;_x000D_
animation: fadeinout 4s linear forwards;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
This works best for me, especially when using dotnet core single file publish.
Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
.
i think in the svn browser in tortoisesvn you can just drag it from one place to another.
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
Use stripTrailingZeros()
.
This article should help you.
Right click on the ribbon and choose Customize the ribbon
. From the Choose commands from:
drop down, select Commands not in the ribbon
.
That is where I found the Document location
command.
As some of the other answers have pointed out, the a
element requires an href
attribute and the #
is used as a placeholder, but it is also a historical artifact.
From Mozilla Developer Network:
href
This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5. Omitting this attribute creates a placeholder link. The href attribute indicates the link target, either a URL or a URL fragment. A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID) within the current document.
Also, per the HTML5 spec:
If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
I was able to use Joey's Answer to create a function:
Use it as:
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!
GOTO:EOF
And these Functions to the bottom of your Batch File.
:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B
:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse Result
::Example
::SET "MYTEXT=jump over the chair"
:: echo !MYTEXT!
:: call:ReplaceText "!MYTEXT!" chair table RESULT
:: echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF
And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.
SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
I am trying to do that in jQuery 2.1, and with the "$().click() -> $(element).data("events").click;
" method it doesn't work.
I realized that only the $._data() functions works in my case :
$(document).ready(function(){_x000D_
_x000D_
var node = $('body');_x000D_
_x000D_
// Bind 3 events to body click_x000D_
node.click(function(e) { alert('hello'); })_x000D_
.click(function(e) { alert('bye'); })_x000D_
.click(fun_1);_x000D_
_x000D_
// Inspect the events of body_x000D_
var events = $._data(node[0], "events").click;_x000D_
var ev1 = events[0].handler // -> function(e) { alert('hello')_x000D_
var ev2 = events[1].handler // -> function(e) { alert('bye')_x000D_
var ev3 = events[2].handler // -> function fun_1()_x000D_
_x000D_
$('body')_x000D_
.append('<p> Event1 = ' + eval(ev1).toString() + '</p>')_x000D_
.append('<p> Event2 = ' + eval(ev2).toString() + '</p>')_x000D_
.append('<p> Event3 = ' + eval(ev3).toString() + '</p>'); _x000D_
_x000D_
});_x000D_
_x000D_
function fun_1() {_x000D_
var txt = 'text del missatge'; _x000D_
alert(txt);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
</body>
_x000D_
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.
https://github.com/marcj/css-element-queries
It contains a ResizeSensor class you can use for that purpose.
new ResizeSensor(jQuery('#mainContent'), function(){
console.log('main content dimension changed');
});
Disclaimer: I wrote this library
I would use matplotlib's pcolor/pcolormesh function since it allows nonuniform spacing of the data.
Example taken from matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
plt.show()
UIView's also have a center
property. If you just want to move the position rather than resize, you can just change that - eg:
aView.center = CGPointMake(50, 200);
Otherwise you would do it the way you posted.
I noticed that the emulator defaults to only Core 0, where most Windows applications will default to "any" core. Also, if you put it on another core (like the last core), it may make the emulator go crazy. If you can, you can try putting your heavy-CPU usage applications on the other CPU cores for a boost in speed.
Hardware-wise, get the fastest CPU you can get that works for single-core applications. More than 2 cores might not experience a huge difference in terms of emulator performance.
Eclipse + the Android emulator together eat up a ton of RAM. I would recommend 3 gigs of RAM at least because I used a system with 2 gigs of RAM, and it slowed down because the system ran out of RAM and started to use the page file.
I feel that the best CPUs for it will probably have a high clock (only use clock as a measure for CPUs in the same series btw), handle non-SIMD operations well, and have a turbo boost mechanism. There aren't many Java-based benchmarks, but overall look for application benchmarks like compression and office. Don't look at gaming or media since those are affected greatly by SIMD. If you find a Java one, even better.
document.documentElement.classList.add('myCssClass');
classList
is supported since ie10: https://caniuse.com/#search=classlist
I can't remember where I got this from that I used in my assignment (I usually copy paste the URL where I found it as an easy form of citation) and I cannot decipher what the trailing (file) = 0
is although my best guess is that it is redundancy to set any references to file to 0.
#define fclose(file) ((file) ? fclose(file) : 0, (file) = 0)
file
if a pointer declared as:
FILE *file=NULL;
I am a little suprised to not see Floyd Warshall's algorithm mentioned here. This algorithm work's very much like Dijkstra's. It also has one very nice feature which is it allows you to compute as long as you would like to continue allowing more intermediate vertices. So it will naturally find the routes which use interstates or highways fairly quickly.
General case, not just for value types:
static class ExtensionsThatWillAppearOnEverything
{
public static T IfDefaultGiveMe<T>(this T value, T alternate)
{
if (value.Equals(default(T))) return alternate;
return value;
}
}
var result = query.FirstOrDefault().IfDefaultGiveMe(otherDefaultValue);
Again, this can't really tell if there was anything in your sequence, or if the first value was the default.
If you care about this, you could do something like
static class ExtensionsThatWillAppearOnIEnumerables
{
public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
{
foreach(T t in source)
return t;
return alternate;
}
}
and use as
var result = query.FirstOr(otherDefaultValue);
although as Mr. Steak points out this could be done just as well by .DefaultIfEmpty(...).First()
.
Have you tried using:
(status,output) = commands.getstatusoutput("ps aux")
I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..
After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2
My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.
I found that python was leaking file descriptors by just keeping an eye on it:
watch "ls /proc/$PYTHONPID/fd | wc -l"
Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...
It is impossible to do it in Eclipse in generic way right now, but it can be changed given with basic Java knowledge and some free time to add basic support for this https://bugs.eclipse.org/bugs/show_bug.cgi?id=180349
The dependent issue: https://bugs.eclipse.org/bugs/show_bug.cgi?id=311173
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
My use case was only to set the value of a local variable.
Personally I found the try and except style cleaner to read
items = [10, 20]
try: first_item = items[0]
except IndexError: first_item = None
print first_item
than slicing a list.
items = [10, 20]
first_item = (items[:1] or [None, ])[0]
print first_item
Assuming popup
is the ID of your "description box":
HTML
<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>
JavaScript
var e = document.getElementById('parent');
e.onmouseover = function() {
document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
document.getElementById('popup').style.display = 'none';
}
Alternatively you can get rid of JavaScript entirely and do it just with CSS:
CSS
#parent #popup {
display: none;
}
#parent:hover #popup {
display: block;
}
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/
is here to delimit your pattern so you have one to start and one to end[]
indicates the pattern your are looking for on one specific character^
indicates that you want every character NOT corresponding to what followsa-z
matches any character between 'a' and 'z' included0-9
matches any digit between '0' and '9' included (meaning any digit)-
the '-' characterg
at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole stringThen your expression is delimited by /
before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
You can use the following query for MYSQL:
SHOW `columns` FROM `your-table`;
Below is the example code which shows How to implement above syntax in php to list the names of columns:
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
For Details about output of SHOW COLUMNS FROM TABLE
visit: MySQL Refrence.
I had one console application and class library. In class library I created Entity Data Model (right click to Class Library > Add > New Item > Data > ADO.NET Entity Data Model 6.0) and put reference inside console application. So, you have console application which has reference to class library and inside class library you have EF model. I had the same error when I tried to get some records from the table.
I resolved this issue by following these steps:
That's all I had to do and everything worked perfect.
I hope it helped.
Getting the MAC address through WifiInfo.getMacAddress()
won't work on Marshmallow and above, it has been disabled and will return the constant value of 02:00:00:00:00:00
.
The following output illustrates results of using copy constructor and Collections.copy():
Copy [1, 2, 3] to [1, 2, 3] using copy constructor.
Copy [1, 2, 3] to (smaller) [4, 5]
java.lang.IndexOutOfBoundsException: Source does not fit in dest
at java.util.Collections.copy(Collections.java:556)
at com.farenda.java.CollectionsCopy.copySourceToSmallerDest(CollectionsCopy.java:36)
at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:14)
Copy [1, 2] to (same size) [3, 4]
source: [1, 2]
destination: [1, 2]
Copy [1, 2] to (bigger) [3, 4, 5]
source: [1, 2]
destination: [1, 2, 5]
Copy [1, 2] to (unmodifiable) [4, 5]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1311)
at java.util.Collections.copy(Collections.java:561)
at com.farenda.java.CollectionsCopy.copyToUnmodifiableDest(CollectionsCopy.java:68)
at com.farenda.java.CollectionsCopy.main(CollectionsCopy.java:20)
The source of full program is here: Java List copy. But the output is enough to see how java.util.Collections.copy() behaves.
Do not we have an app which can stream the digital movie from iOS devices like iPhone or iPad to be played on a high definition LED or Plasma TV?
I know of an app air video server which can be used to display content played on computer or laptop on iOS device. But is there any app that can do the reverse & play the digital content from iphone to LED tv .
You can tell ESLint to ignore specific files and directories by creating an .eslintignore
file in your project’s root directory:
.eslintignore
build/*.js
config/*.js
bower_components/foo/*.js
The ignore patterns behave according to the .gitignore
specification.
(Don't forget to restart your editor.)
The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.
Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.
Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.
I did this.
double g = 1.0/3.0;
System.out.printf("%gf", g);
Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.
Try this! If you want to find the maximum duplicated element with their how many time is it has duplicated then should try
def get_maximum_duplicated_element_with_count(input_array)
a = input_array
max_duplicated_val = max_duplicated_val_count = 0
a.each do |n|
max_duplicated_val, max_duplicated_val_count = n, a.count(n) if a.count(n) > max_duplicated_val_count
end
puts "Maximun Duplicated element Is => #{max_duplicated_val}"
puts "#{max_duplicated_val} is Duplicated #{max_duplicated_val_count} times"
end
get_maximum_duplicated_element_with_count([1, 4, 4, 5, 6, 6, 2, 6])
Output will be
Maximun Duplicated element Is => 6
6 is Duplicated 3 times
The two really aren't similar. static
fields are fields that do not belong to any particular instance of a class.
class C {
public static int n = 42;
}
Here, the static
field n
isn't associated with any particular instance of C
but with the entire class in general (which is why C.n
can be used to access it). Can you still use an instance of C
to access n
? Yes - but it isn't considered particularly good practice.
final
on the other hand indicates that a particular variable cannot change after it is initialized.
class C {
public final int n = 42;
}
Here, n
cannot be re-assigned because it is final
. One other difference is that any variable can be declared final
, while not every variable can be declared static.
Also, classes can be declared final
which indicates that they cannot be extended:
final class C {}
class B extends C {} // error!
Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:
class C {
public final void foo() {}
}
class B extends C {
public void foo() {} // error!
}
i think you should use hidden better.
activityIndicator.hidden = YES
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
If you think that there is a conflict you can use jQuery.noConflict()
in your code. Details are in the docs.
REFERENCING MAGIC - SHORTCUTS FOR JQUERY
If you don't like typing the full "jQuery" all the time, there are some alternative shortcuts:
Reassign jQuery to another shortcut
var $j = jQuery;
(This might be the best approach if you wish to use different libraries) Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:
(function($) { /* some code that uses $ */ })(jQuery)
Note: If you use this technique, you will not be able to use Prototype methods inside this capsuled function that expect $ to be Prototype's $, so you're making a choice to use only jQuery in that block. Use the argument to the DOM ready event:
jQuery(function($) { /*some code that uses $ */ });
Note: Again, inside that block you can't use Prototype methods
Thats from the end of the docs and might be useful to you
The error you quote has nothing to do with pg_hba.conf
; it's failing to connect, not failing to authorize the connection.
Do what the error message says:
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
You haven't shown the command that produces the error. Assuming you're connecting on localhost
port 5432
(the defaults for a standard PostgreSQL install), then either:
PostgreSQL isn't running
PostgreSQL isn't listening for TCP/IP connections (listen_addresses
in postgresql.conf
)
PostgreSQL is only listening on IPv4 (0.0.0.0
or 127.0.0.1
) and you're connecting on IPv6 (::1
) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.
PostgreSQL is listening on a different port to the one you're connecting on
(unlikely) there's an iptables
rule blocking loopback connections
(If you are not connecting on localhost
, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).
So ... check those:
ps -f -u postgres
should list postgres
processes
sudo lsof -n -u postgres |grep LISTEN
or sudo netstat -ltnp | grep postgres
should show the TCP/IP addresses and ports PostgreSQL is listening on
BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:
$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
Try to start path\to\cygwin\bin\bash.exe
(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None]
notation:
n_lists = np.append(n_list_converted, n_last[:, None], axis=1)
Alternatively, when extracting n_last
you can use
n_last = n_list_converted[:, -1:]
to get a (20, 1)
array.
There isn't any EditorFor
override that lets you pass in an anonymous object whose properties would somehow get added as attributes on some tag, especially for the built-in editor templates. You would need to write your own custom editor template and pass the value you want as additional viewdata.
Using command prompt in windows you can use below command to get class files.
wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl
if you want to generate source code you should be using below commnad.
wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl
Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
You mean something like IPhone checkboxes? Try Thomas Reynolds' iOS Checkboxes script:
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() { $(':checkbox').iphoneStyle(); });
Results:
The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value
Example:
If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico
NICE REFERENCE: http://es5.github.io/x7.html#x7.8.4
You need to update Anaconda using:
conda update
and
conda update anaconda-navigator
Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:
anaconda-navigator
If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.
you should configure something like as follows in build.gradle
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
Normally the dot matches any character except newlines.
So if .*
isn't working, set the "dot matches newlines, too" option (or use (?s).*
).
If you're using JavaScript, which doesn't have a "dotall" option, try [\s\S]*
. This means "match any number of characters that are either whitespace or non-whitespace" - effectively "match any string".
Another option that only works for JavaScript (and is not recognized by any other regex flavor) is [^]*
which also matches any string. But [\s\S]*
seems to be more widely used, perhaps because it's more portable.
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
You can assign structs in C. a = b;
is valid syntax.
You simply left off part of the type -- the struct tag -- in your line that doesn't work.
Its easy, just wrap it in a relative box like so:
<div class="relative">
<div class="absolute">LOGO</div>
</div>
The relative box has a margin: 0 Auto; and, important, a width...
var Test = (from row in Dataset1.Tables[0].AsEnumerable()
select row.Field<string>("attribute1_name") + row.Field<int>("attribute2_name")).Distinct();
I think most of the important stuff has been said, but I just thought I'd add one thing: If you compile as Any CPU and run on an x64 platform, then you won't be able to load 32-bit DLL files, because your application wasn't started in WoW64, but those DLL files need to run there.
If you compile as x86, then the x64 system will run your application in WoW64, and you'll be able to load 32-bit DLL files.
So I think you should choose "Any CPU" if your dependencies can run in either environment, but choose x86 if you have 32-bit dependencies. This article from Microsoft explains this a bit:
/CLRIMAGETYPE (Specify Type of CLR Image)
Incidentally, this other Microsoft documentation agrees that x86 is usually a more portable choice:
Choosing x86 is generally the safest configuration for an app package since it will run on nearly every device. On some devices, an app package with the x86 configuration won't run, such as the Xbox or some IoT Core devices. However, for a PC, an x86 package is the safest choice and has the largest reach for device deployment. A substantial portion of Windows 10 devices continue to run the x86 version of Windows.
It works in Python too:
>>> 1+\
2+\
3
6
>>> (1+
2+
3)
6
We had exactly the same challenge some time ago. We wanted to go with CEF3 open source library which is WPF-based and supports .NET 3.5.
Firstly, the author of CEF himself listed binding for different languages here.
Secondly, we went ahead with open source .NET CEF3 binding which is called Xilium.CefGlue and had a good success with it. In cases where something is not working as you'd expect, author usually very responsive to the issues opened in build-in bitbucket tracker
So far it has served us well. Author updates his library to support latest CEF3 releases and bug fixes on regular bases.
I suffered this problem while developing an application for a client. Working on my machine the code/forms etc worked perfectly but when loaded on to the client's system this error occurred at some point within my application.
My workaround for this error was to strip apart the workbook from the forms and code by removing the VBA modules and forms. After doing this my client copied the 'bare' workbook and the modules and forms. Importing the forms and code into the macro-enabled workbook enabled the application to work again.
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
var map = arr.reduce(function(prev, cur) {_x000D_
prev[cur] = (prev[cur] || 0) + 1;_x000D_
return prev;_x000D_
}, {});_x000D_
_x000D_
// map is an associative array mapping the elements to their frequency:_x000D_
document.write(JSON.stringify(map));_x000D_
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
_x000D_
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
If you are using ubuntu, check weather subversion is installed or not.
If not then install through command line as
sudo apt-get install subversion
and check following configurations are selected
Another idea is using letter-spacing
li, a { display: inline-block; }_x000D_
a {_x000D_
font-size: 14px;_x000D_
padding-left: 10px;_x000D_
padding-right: 10px;_x000D_
letter-spacing: 0.235px_x000D_
}_x000D_
_x000D_
a:hover, a:focus {_x000D_
font-weight: bold;_x000D_
letter-spacing: 0_x000D_
}
_x000D_
<ul>_x000D_
<li><a href="#">item 1</a></li>_x000D_
<li><a href="#">item 2</a></li>_x000D_
<li><a href="#">item 3</a></li>_x000D_
</ul>
_x000D_
For Spring 4 I use the following
(I am posting it as the question is 4 years old and more people use Spring 4 than Spring 3.1):
@Configuration
@ComponentScan(basePackages = "com.example",
excludeFilters = @Filter(type=FilterType.REGEX,pattern="com\\.example\\.ignore\\..*"))
public class RootConfig {
// ...
}
One might consider using MessagePack which is endorsed by redis.
import msgpack
data = {
'one': 'one',
'two': 2,
'three': [1, 2, 3]
}
await redis.set('my-key', msgpack.packb(data))
val = await redis.get('my-key')
print(msgpack.unpackb(val))
# {'one': 'one', 'two': 2, 'three': [1, 2, 3]}
Using msgpack-python and aioredis
After six days I find the answer which make me crazy! The answer is disable proxy at web.config file:
<system.net>
<defaultProxy>
<proxy usesystemdefault="False"/>
</defaultProxy>
</system.net>
Not exactly a Windows version, however you can use Cygwin's crontab. For install instructions, see here: here.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Graphiic
{
public Graphics GClass;
public Graphics2D G2D;
public void Draw_Circle(JFrame jf,int radius , int xLocation, int yLocation)
{
GClass = jf.getGraphics();
GClass.setPaintMode();
GClass.setColor(Color.MAGENTA);
GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360);
GClass.drawLine(100, 100, 200, 200);
}
}
You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:
RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
rm -f treeio.zip && cd treeio && pip install -r requirements.pip
Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.
In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.
Peculiarly, none of these answers produce a regex where the returned match is the text inside the quotes, which is what is asked for. MA-Madden tries but only gets the inside match as a captured group rather than the whole match. One way to actually do it would be :
(?<=(["']\b))(?:(?=(\\?))\2.)*?(?=\1)
Examples for this can be seen in this demo https://regex101.com/r/Hbj8aP/1
The key here is the the positive lookbehind at the start (the ?<=
) and the positive lookahead at the end (the ?=
). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the ["']
) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead (?=\1)
to make sure it only stops when it finds the corresponding quote.
The only other complication is that because the lookahead doesn't actually consume the end quote, it will be found again by the starting lookbehind which causes text between ending and starting quotes on the same line to be matched. Putting a word boundary on the opening quote (["']\b
) helps with this, though ideally I'd like to move past the lookahead but I don't think that is possible. The bit allowing escaped characters in the middle I've taken directly from Adam's answer.
You can do this using jQuery:
This method gets a list of its children then counts the length of that list, as simple as that.
$("ul").find("*").length;
The find() method traverses DOM downwards along descendants, all the way down to the last descendant.
Note: children() method traverses a single level down the DOM tree.
I had this issue with laravel 5.8 and i fixed this code, as shown here in Laravel documentation, to where ever i am adding a foreign key.
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
then i ran $ php artisan migrate:refresh
Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');
});
The blame command is a Git feature, designed to help you determine who made changes to a file.
Despite its negative-sounding name, git blame is actually pretty innocuous; its primary function is to point out who changed which lines in a file, and why. It can be a useful tool to identify changes in your code.
Basically, git-blame
is used to show what revision and author last modified each line of a file. It's like checking the history of the development of a file.
A many to many relationship normally has a linking table. Consider this "link" as an entity in its own right and give it a unique id, then send that id in the delete request.
You would have a a REST resource URL like /user/role to handle operations on a user-role "link" entity.
Node Package Manager does not install devDependencies, whenever you run npm install
. Rather what it does is that it installs all the dependencies. So you just have to copy the contents of DevDependencies to Dependencies in package.json, which will force the manager to install those libraries. After copying all the DevDependencies to Dependencies, just run the command npm install
, then proceed with ng serve
and BOOM its up and running!!!
I hope it helps.
Thank you
The following solution seems more accurate to me than combine JavaScript with Razor. Check this out: https://github.com/brooklynDev/NGon
You can add almost any complex data to ViewBag.Ngon and access it in JavaScript
In the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var person = new Person { FirstName = "John", LastName = "Doe", Age = 30 };
ViewBag.NGon.Person = person;
return View();
}
}
In JavaScript:
<script type="text/javascript">
$(function () {
$("#button").click(function () {
var person = ngon.Person;
var div = $("#output");
div.html('');
div.append("FirstName: " + person.FirstName);
div.append(", LastName: " + person.LastName);
div.append(", Age: " + person.Age);
});
});
</script>
It's allows any plain old CLR objects (POCOs) that can be serialized using the default JavascriptSerializer
.
SQL*Plus uses &1, &2... &n to access the parameters.
Suppose you have the following script test.sql
:
SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off
you could call this script like this for example:
$ sqlplus login/pw @test Hello World!
In a UNIX script you would usually call a SQL script like this:
sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF
so that your login/password won't be visible with another session's ps
Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.
Please rewrite your query like
select /*+ MAX_EXECUTION_TIME(1000) */ * from table
this statement will kill your query after the specified time
extension Array where Element: Encodable {
func asArrayDictionary() throws -> [[String: Any]] {
var data: [[String: Any]] = []
for element in self {
data.append(try element.asDictionary())
}
return data
}
}
extension Encodable {
func asDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw NSError()
}
return dictionary
}
}
If you're using Codable protocols in your models these extensions might be helpful for getting dictionary representation (Swift 4)
@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.
The below examples are based on a domain in the range of 20,000 account objects.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds : 16
Milliseconds : 208
measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds : 3
Milliseconds : 496
In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).
Note that if I include the where
clause per your suggestion to prune to the actually desired results, it's even more expensive.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds : 17
Milliseconds : 876
Indexed attributes seem to have similar performance (I tried just returning displayName
).
Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).
measure-command {$userlist | get-aduser -Properties *}
...
Seconds : 12
Milliseconds : 75
I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01
When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).
As far as I know, if an exception is not caught by your script, it will be interrupted.
If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****
ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:
A version without error-handling:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
What solved my problem was just using the below two lines in ipython notebook at the top
%matplotib inline
%pylab inline
And it worked. I'm using Ubuntu16.04 and ipython-5.1
My main query looked like this in the model:
@NamedQuery(name = "getAllCentralFinancialAgencyAccountCd",
query = "select distinct i from CentralFinancialAgencyAccountCd i")
And I was still not getting what I considered "distinct" results. They were just distinct based on a primary key combination on the table.
So in the DaoImpl
I added an one line change and ended up getting the "distinct" return I wanted. An example would be instead of seeing 00 four times I now just see it once. Here is the code I added to the DaoImpl
:
@SuppressWarnings("unchecked")
public List<CacheModelBase> getAllCodes() {
Session session = (Session) entityManager.getDelegate();
org.hibernate.Query q = session.getNamedQuery("getAllCentralFinancialAgencyAccountCd");
q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // This is the one line I had to add to make it do a more distinct query.
List<CacheModelBase> codes;
codes = q.list();
return codes;
}
I hope this helped! Once again, this might only work if you are following coding practices that implement the service, dao, and model type of project.
In iOS 10 beta 4.The right code in HTML5 is
<video src="file.mp4" webkit-playsinline="true" playsinline="true">
webkit-playsinline
is for iOS < 10, and playsinline
is for iOS >= 10
See details via https://webkit.org/blog/6784/new-video-policies-for-ios/
I wrote an ES6 version based on @Halcyon answer
const array = [
{
id: '12',
parentId: '0',
text: 'one-1'
},
{
id: '6',
parentId: '12',
text: 'one-1-6'
},
{
id: '7',
parentId: '12',
text: 'one-1-7'
},
{
id: '9',
parentId: '0',
text: 'one-2'
},
{
id: '11',
parentId: '9',
text: 'one-2-11'
}
];
// Prevent changes to the original data
const arrayCopy = array.map(item => ({ ...item }));
const listToTree = list => {
const map = {};
const roots = [];
list.forEach((v, i) => {
map[v.id] = i;
list[i].children = [];
});
list.forEach(v => (v.parentId !== '0' ? list[map[v.parentId]].children.push(v) : roots.push(v)));
return roots;
};
console.log(listToTree(arrayCopy));
The principle of this algorithm is to use "map" to establish an index relationship. It is easy to find "item" in the list by "parentId", and add "children" to each "item", because "list" is a reference relationship, so "roots" will Build relationships with the entire tree.
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
You can use
If-then-else: (if) ? (then) : (else)
Example:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
It could be useful for the new people asking the same question.
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
FFTW is the 'fastest fourier transform in the west', and has some Java wrappers:
Hope that helps!
See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
1. You might also use EXIT_ON_CLOSE
, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.
The 'button' to invoke this operation is already on a frame.
DISPOSE_ON_CLOSE
functionality.This should be enough to answer your question: http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
The
equals()
method compares two objects for equality and returnstrue
if they are equal. Theequals()
method provided in theObject
class uses the identity operator (==
) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. Theequals()
method provided byObject
tests whether the object references are equal—that is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the
equals()
method.
(Partial quote - click through to read examples.)
You could do the following:
.interrupt
the working threads if they wait for data in some blocking call)writeBatch
in your case) to finish, by calling the Thread.join()
method on the working threads.Some sketchy code:
static volatile boolean keepRunning = true;
In run() you change to
for (int i = 0; i < N && keepRunning; ++i)
writeBatch(pw, i);
In main() you add:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
mainThread.join();
}
});
That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.
From the docs:
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.
Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.
Start with a subset of the original data:
datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200,
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600,
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000,
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct",
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44,
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18,
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88,
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73,
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97,
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75,
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01,
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax",
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")
You can get the desired effect by (and this also cleans up the original plotting code):
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
breaks = c("TempMax", "TempMedia", "TempMin"),
values = c("red", "green", "blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
The idea is that each line is given a color by mapping the colour
aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y
variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes
call; you are creating a mapping to this "variable".
scale_colour_manual
can now map these strings to the appropriate colors. The result is
In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
values = c("TempMedia"="green", "TempMax"="red",
"TempMin"="blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
breaks = c("TempMedia", "TempMax", "TempMin"),
values = c("TempMedia"="green", "TempMax"="red",
"TempMin"="blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
So you're trying to grab numeric values that are preceded by the token "%download%#"?
Try this pattern:
(?<=%download%#)\d+
That should work. I don't think #
or %
are special characters in .NET Regex, but you'll have to either escape the backslash like \\
or use a verbatim string for the whole pattern:
var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);
Tested here: http://rextester.com/BLYCC16700
NOTE: The lookbehind assertion (?<=...)
is important because you don't want to include %download%#
in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.