I wanted to create a MarkdownPreviewer in react as part of a project in freecodecamp. So I was desperately searching for newline characters for markdown. After trying many suggestions. I finally used \n and it worked.
You can use "Visual studio installer project" and its free...
This is very easy to create installer and has GUI.(Most of the freeware MSI creation tool does not have a GUI part)
You will find many tutorials to create an installer easily on the internet
To install. just search Visual Studio Installer Project in your Visual Studio
Visual Studio-> Tools-> Extensions&updates ->search Visual Studio Installer Project. Download it and enjoy...
To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict
is immutable.
>>> the_form.data = {**f.data.dict(), 'some_field': 47}
>>> the_form['some_field'].as_widget()
'<input type="hidden" name="some_field" value="47"
class="field-some_field" id="id_some_field">'
Use this
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"
Note
You need to declare the following 'uses-permission' in the android manifest xml file
... answer by @Squonk here
And also check this answer
You can use
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"
These are attached property of wpf. For more information
http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html
An application when installed on a device or on an emulator will install at:
/data/data/APP_PACKAGE_NAME
The APK itself is placed in the /data/app/
folder.
These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab
By the way, it only shows the package name that is defined in your Manifest.XML
under the package="APP_PACKAGE_NAME"
attribute. Any other packages you may have created in your project in Eclipse do not show up here.
I think you ought to use a regex:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String neg = "-123abc";
String pos = "123abc";
String non = "abc123";
/* I'm not sure if this regex is too verbose, but it should be
* clear. It checks that the string starts with either a series
* of one or more digits... OR a negative sign followed by 1 or
* more digits. Anything can follow the digits. Update as you need
* for things that should not follow the digits or for floating
* point numbers.
*/
Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
Matcher matcher = pattern.matcher(neg);
if(matcher.matches()) {
System.out.println("matches negative number");
}
matcher = pattern.matcher(pos);
if (matcher.matches()) {
System.out.println("positive matches");
}
matcher = pattern.matcher(non);
if (!matcher.matches()) {
System.out.println("letters don't match :-)!!!");
}
}
}
You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
In case you're not in the specified directory (i.e. direct), you should use (in linux):
x_file = open('path/to/direct/filename.txt')
Note the quotes and the relative path to the directory.
This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.
Here is the code using JavaScript to click the button in WebDriver:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('gbqfb').click();");
You're not including the C file that contains main()
when compiling, so the linker isn't seeing it.
You need to add it:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
The previous remarks about deleting or removing a connection are absolutely a possibility. But you can also get this error when you attempt to invoke a package that uses project level connections (instead of package level connections).
If you are using project level connections and still want to use dtexec, never fear there is a way. I would not recommend converting them to package level connections (assuming you created them as project level connections for a good reason).
You will need to deploy your SSIS project. Your SSIS server will need to have a catalog created (https://msdn.microsoft.com/en-us/library/gg471509.aspx). Once you have the catalog, in your SSIS project select Project->Deploy and follow the wizard. The result will be a *.ispac file generated in your SSIS solution folder/bin/Development
Now for the money command, instead of invoking your package with a simple: dtexec.exe /f "package.dtsx"
instead call it this way: dtexec.exe /project "<...>/project.ispac" /package "<...>/package.dtsx"
The ispac file has the project level connection info that is needed to execute your package and you should be set!
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
I think that in order to get the request data, bound and validated by the form object, you must use :
$form->getClientData();
Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.
In my experience OpenCV writes a black image when SaveImage
is given a matrix with bit depth different from 8 bit. In fact, this is sort of documented:
Only 8-bit single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use
cvCvtScale
andcvCvtColor
to convert it before saving, or use universalcvSave
to save the image to XML or YAML format.
In your case you may first investigate what kind of image is captured, change capture properties (I suppose CV_CAP_PROP_CONVERT_RGB
might be important) or convert it manually afterwards.
This is an example how to convert to 8-bit representation with OpenCV. cc
here is an original matrix of type CV_32FC1
, cc8u
is its scaled version which is actually written by SaveImage
:
# I want to save cc here
cc8u = CreateMat(cc.rows, cc.cols, CV_8U)
ccmin,ccmax,minij,maxij = MinMaxLoc(cc)
ccscale, ccshift = 255.0/(ccmax-ccmin), -ccmin
CvtScale(cc, cc8u, ccscale, ccshift)
SaveImage("cc.png", cc8u)
(sorry, this is Python code, but it should be easy to translate it to C/C++)
(3) Collection myCollection = new ArrayList<?>();
I am using this typically. And only if I need List methods, I will use List. Same with ArrayList. You always can switch to more "narrow" interface, but you can't switch to more "wide".
You can use the x
descriptor of the srcset
attribute as such:
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />
<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />
<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
Currently supported by all browsers except IE. (caniuse)
Seems like it's quite a popular question, so I will try to make my humble contribution.
The code below is Swift 4 solution for no-storyboard setup. It utilizes some approaches from previous answers, therefore it prevents Auto Layout warning caused on device rotation.
I am sorry if code samples are a bit long. I want to provide an "easy-to-use" solution fully hosted by StackOverflow. If you have any suggestions to the post - please, share the idea and I will update it accordingly.
Two classes: ViewController.swift
and MultilineLabelCell.swift
- Cell containing single UILabel
.
MultilineLabelCell.swift
import UIKit
class MultilineLabelCell: UICollectionViewCell {
static let reuseId = "MultilineLabelCellReuseId"
private let label: UILabel = UILabel(frame: .zero)
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 1.0
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
let labelInset = UIEdgeInsets(top: 10, left: 10, bottom: -10, right: -10)
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: labelInset.top).isActive = true
label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: labelInset.left).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: labelInset.right).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: labelInset.bottom).isActive = true
label.layer.borderColor = UIColor.black.cgColor
label.layer.borderWidth = 1.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("Storyboards are quicker, easier, more seductive. Not stronger then Code.")
}
func configure(text: String?) {
label.text = text
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.left
layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
}
ViewController.swift
import UIKit
let samuelQuotes = [
"Samuel says",
"Add different length strings here for better testing"
]
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private(set) var collectionView: UICollectionView
// Initializers
init() {
// Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
// Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Dynamic size sample"
// Register Cells
collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)
// Add `coolectionView` to display hierarchy and setup its appearance
view.addSubview(collectionView)
collectionView.backgroundColor = .white
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
// Setup Autolayout constraints
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
// Setup `dataSource` and `delegate`
collectionView.dataSource = self
collectionView.delegate = self
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionInsetReference = .fromLayoutMargins
}
// MARK: - UICollectionViewDataSource -
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
cell.configure(text: samuelQuotes[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return samuelQuotes.count
}
// MARK: - UICollectionViewDelegateFlowLayout -
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
let referenceHeight: CGFloat = 100 // Approximate height of your cell
let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
- sectionInset.left
- sectionInset.right
- collectionView.contentInset.left
- collectionView.contentInset.right
return CGSize(width: referenceWidth, height: referenceHeight)
}
}
To run this sample create new Xcode project, create corresponding files and replace AppDelegate
contents with the following code:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
let vc = ViewController()
navigationController = UINavigationController(rootViewController: vc)
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
return true
}
}
As mentioned in the other answers, previous versions of openssl used a weak key derivation function to derive an AES encryption key from the password. However, openssl v1.1.1 supports a stronger key derivation function, where the key is derived from the password using pbkdf2
with a randomly generated salt, and multiple iterations of sha256 hashing (10,000 by default).
To encrypt a file:
openssl aes-256-cbc -e -salt -pbkdf2 -iter 10000 -in plaintextfilename -out encryptedfilename
To decrypt a file:
openssl aes-256-cbc -d -salt -pbkdf2 -iter 10000 -in encryptedfilename -out plaintextfilename
Yes, you will need to specify the width for each cell, otherwise they will try to be "intelligent" about it and divide the 100% between whichever cells think they need it most. Cells with more content will take up more width than those with less.
To make sure you get equal width for each cell you need to make it clear. Either do it as you already have, or use CSS.
table.className td { width: 25%; }
Before I go on, I have the latest version (v5.0.15) of OS X Server (yes, horrible, I know...however, the web server seems to work A-OK). I searched high and low for days trying to update (or at least get Apache to point to) a new version of PHP. My mcrypt
did not work, along with other extensions and I installed and reinstalled PHP countless times from http://php-osx.liip.ch/ and other tutorials until I finally noticed a tid-bit of information written in a comment in one of the many different .conf
files OS X Server keeps which was that OS X Server loads it's own custom .conf
file before it loads the Apache httpd.conf
(located at /etc/apache2/httpd.conf
). The server file is located:
/Library/Server/Web/Config/apache2/httpd_server_app.conf
When you open this file, you have to comment out this line like so:
#LoadModule php5_module libexec/apache2/libphp5.so
Then add in the correct path (which should already be installed if you have installed via the http://php-osx.liip.ch/ link):
LoadModule php5_module /usr/local/php5/libphp5.so
After this modification, my PHP finally loaded the correct PHP installation. That being said, if things go wonky, it may be because OS X is made to work off the native installation of PHP at the time of OS X installation. To revert, just undo the change above.
Anyway, hopefully this is helpful for anyone else spending countless hours on this.
Xcode 8, Swift 3:
let gAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let gAppBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"
Dependency
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
//Java Code for Image Loading into imageView
Picasso.get().load(werURL).into(imageView);
Keep an index of the first "live" element of the array. Removing (pretending to remove) the first element then becomes an O(1)
time complexity operation.
as others said Calendar.MONTH returns int and is zero indexed.
to get the current month as a String
use SimpleDateFormat.format()
method
Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
returns NOV
The following code might be useful for web application using JavaScript.
var newURL = window.location.protocol + "//" + window.location.host + "" + window.location.pathname;
newURL = newURL.substring(0,newURL.indexOf(""));
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");
This is a great topic on the issue, however I found that one important detail (which was essential at least in my case) that was not posted here or anywhere else (I apologize if I just missed it) was that the P3P line must be passed in header of EVERY file sent from the 3rd party server, even files not setting or using the cookies such as Javascript files or images. Otherwise the cookies will be blocked. I have more on this in a post here: http://posheika.net/?p=110
What you are looking for is probably this:
ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"
int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);
Let me know if this was helpful :)
You can filter by multiple columns (more than two) by using the np.logical_and
operator to replace &
(or np.logical_or
to replace |
)
Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:
def filter_df(df, filter_values):
"""Filter df by matching targets for multiple columns.
Args:
df (pd.DataFrame): dataframe
filter_values (None or dict): Dictionary of the form:
`{<field>: <target_values_list>}`
used to filter columns data.
"""
import numpy as np
if filter_values is None or not filter_values:
return df
return df[
np.logical_and.reduce([
df[column].isin(target_values)
for column, target_values in filter_values.items()
])
]
Usage:
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})
filter_df(df, {
'a': [1, 2, 3],
'b': [1, 2, 4]
})
On mac the answers above unfortunately didn't work causing a ERROR 1045 (28000): Access denied for user 'root'@'localhost'
Doing the following worked for me:
sudo su
mysql -uroot
set password = password("password");
Took me embarassingly long to figure out hope it helps someone else.
You can use Jquery's on method and listen for the scroll
event.
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
indeed, all of these datetime types can be difficult, and potentially problematic (must keep careful track of timezone information). here's what i have done, though i admit that i am concerned that at least part of it is "not by design". also, this can be made a bit more compact as needed. starting with a numpy.datetime64 dt_a:
dt_a
numpy.datetime64('2015-04-24T23:11:26.270000-0700')
dt_a1 = dt_a.tolist() # yields a datetime object in UTC, but without tzinfo
dt_a1
datetime.datetime(2015, 4, 25, 6, 11, 26, 270000)
# now, make your "aware" datetime:
dt_a2=datetime.datetime(*list(dt_a1.timetuple()[:6]) + [dt_a1.microsecond], tzinfo=pytz.timezone('UTC'))
... and of course, that can be compressed into one line as needed.
I tested this method to be much faster than ORDER BY RAND()
, hence it runs in O(n) time, and does so impressively fast.
From http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx:
Non-MSSQL version -- I did not test this
SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= RAND()
MSSQL version:
SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)
This will select ~1% of records. So if you need exact # of percents or records to be selected, estimate your percentage with some safety margin, then randomly pluck excess records from resulting set, using the more expensive ORDER BY RAND()
method.
I was able to improve upon this method even further because I had a well-known indexed column value range.
For example, if you have an indexed column with uniformly distributed integers [0..max], you can use that to randomly select N small intervals. Do this dynamically in your program to get a different set for each query run. This subset selection will be O(N), which can many orders of magnitude smaller than your full data set.
In my test I reduced the time needed to get 20 (out 20 mil) sample records from 3 mins using ORDER BY RAND() down to 0.0 seconds!
nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))
I created an extension method to the ObservableCollection
public static void MySort<TSource,TKey>(this ObservableCollection<TSource> observableCollection, Func<TSource, TKey> keySelector)
{
var a = observableCollection.OrderBy(keySelector).ToList();
observableCollection.Clear();
foreach(var b in a)
{
observableCollection.Add(b);
}
}
It seems to work and you don't need to implement IComparable
See the manual on Type Juggling on possible casts.
The casts allowed are:
You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.
Or, if you are in a hackish mood, you could adapt the following code:
function arrayToObject(array $array, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(serialize($array), ':')
));
}
which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.
For object to object, the code would be
function objectToObject($instance, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
Firstly your approach is inefficient because the appending to the list on a row by basis will be slow as it has to periodically grow the list when there is insufficient space for the new entry, list comprehensions are better in this respect as the size is determined up front and allocated once.
However, I think fundamentally your approach is a little wasteful as you have a dataframe already so why create a new one for each of these users?
I would sort the dataframe by column 'name'
, set the index to be this and if required not drop the column.
Then generate a list of all the unique entries and then you can perform a lookup using these entries and crucially if you only querying the data, use the selection criteria to return a view on the dataframe without incurring a costly data copy.
Use pandas.DataFrame.sort_values
and pandas.DataFrame.set_index
:
# sort the dataframe
df.sort_values(by='name', axis=1, inplace=True)
# set the index to be this and don't drop
df.set_index(keys=['name'], drop=False,inplace=True)
# get a list of names
names=df['name'].unique().tolist()
# now we can perform a lookup on a 'view' of the dataframe
joe = df.loc[df.name=='joe']
# now you can query all 'joes'
Restarting the adb server, Eclipse, and device did the trick for me.
C:\Android\android-sdk\platform-tools>adb kill-server
C:\Android\android-sdk\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
I had the same problem as mentioned on this question.
You need to add a vertical-align
property to your two child div's.
If .small
is always shorter, you need only apply the property to .small
.
However, if either could be tallest then you should apply the property to both .small
and .big
.
.container{
border: 1px black solid;
width: 320px;
height: 120px;
}
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align: top;
}
.big {
display: inline-block;
border: 1px black solid;
width: 40%;
height: 50%;
background: beige;
vertical-align: top;
}
Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.
Update:
You might need to edit your ~/.netrc file:
Original answer:
Why did you disable ssl? I think this might have to do with you not being able to push via https. I'd set it back and try to push again:
git config –global http.sslVerify true
I think a better solution for this problem is to use maven-install-plugin to automatically install the files at install time. This is how I set it up for my project.
First, add the path (where you store the local .jars) as a property.
<properties>
<local.sdk>/path/to/jar</local.sdk>
</properties>
Then, under plugins
add a plugin to install the jars when compiling.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<executions>
<execution>
<id>1</id>
<phase>initialize</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<groupId>com.local.jar</groupId>
<artifactId>appengine-api</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<file>${local.sdk}/lib/impl/appengine-api.jar</file>
</configuration>
</execution>
<execution>
<id>appengine-api-stubs</id>
<phase>initialize</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<groupId>com.local.jar</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<file>${local.sdk}/lib/impl/appengine-api-stubs.jar</file>
</configuration>
</execution>
</executions>
</plugin>
Finally, in dependencies, you can add the jars
<dependency>
<groupId>com.local.jar</groupId>
<artifactId>appengine-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.local.jar</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
By Setting up your project like this, the project will continue to build even when you take it to another computer (given that it has all the jar files in the path specified by the property local.sdk
).
For groupId
use a unique name just to make sure that there are no conflicts.
Now when you mvn install
or mvn test
local jars will be added automatically.
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");
If you're asking this because you want to speed up your web site, check out Yahoo's page on Best Practices for Speeding Up Your Web Site. It has a lot of best practices for speeding up your web site.
The postition:absolute;
tag positions the element relative to it's immediate parent.
I noticed that even in the examples, there isn't room for scrolling, and when i tried it out, it didn't work.
Therefore, to pull off the facebook floating menu, the position:fixed;
tag should be used instead. It displaces/keeps the element at the given/specified location, and the rest of the page can scroll smoothly - even with the responsive ones.
Please see CSS postion attribute documentation when you can :)
You can. Try something like this:
@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
@PathParam("varY") String varY) {
Todo todo = new Todo();
todo.setSummary(varX);
todo.setDescription(varY);
return todo;
}
Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description
I wanted this to work with selects that I added dynamically to the page, so after a lot of experimentation, I ended up giving all the selects that I wanted to do this with the class "fixedwidth", and then added the following CSS:
table#System_table select.fixedwidth { width: 10em; }
table#System_table select.fixedwidth.clicked { width: auto; }
and this code
<!--[if lt IE 9]>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).on(
{
'mouseenter': function(event) {
jQuery(this).addClass('clicked');
},
'focusout change blur': function() {
jQuery(this).removeClass('clicked');
}
}, 'select.fixedwidth');
});
</script>
<![endif]-->
A couple of things to note:
jQuery(document).on
instead of to jQuery('table#System_table').on
mouseleave
" instead of "blur
", I found that in IE7 when I moved the mouse down the drop down list, it would get a mouseleave
event but not a blur
.An easy solution to center text horizontally and vertically in SVG:
Set the position of the text to the absolute center of the element in which you want to center it:
x="50%" y ="50%"
.x
would be the x
of that element + half its width (and similar for y
but with the height).Use the text-anchor
property to center the text horizontally with the value middle
:
middle
The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.
Use the dominant-baseline
property to center the text vertically with the value middle
(or depending on how you want it to look like, you may want to do central
)
Here is a simple demo:
<svg width="200" height="100">_x000D_
<rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>_x000D_
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text> _x000D_
</svg>
_x000D_
You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.
If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.
To answer some of your comments...
To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.
The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.
As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.
As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.
Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851
Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.
If you want to specify the operations to be made on top of the source
contents, then use a closure. It would be something like this:
def copyAndReplaceText(source, dest, closure){
dest.write(closure( source.text ))
}
// And you can keep your usage as:
copyAndReplaceText(source, dest){
it.replaceAll('Visa', 'Passport!!!!')
}
If you will always swap strings, pass both, as your method signature already states:
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')
ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.
Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.
Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:
"Features" >
Unfortunately changing it through the UI means that the changes don't persist between logins.
Try this,
.success { background-color: #ccffcc; float:left;}
Have you taken a look at put.py? I've used it in the past. You can also just hack up your own request with urllib.
It might be worth writing your own tree wrapper based on an acyclic directed graph using the networkx library.
Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static
operation
SELECT * FROM `orders` WHERE `order_date_time` BETWEEN 1534809600 AND 1536718364
I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini lib for PHP allows you to easily transform MySQL databases into web accessible JSON APIs.
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
For the correct and efficient computation of the hash value of a file (in Python 3):
'b'
to the filemode) to avoid character encoding and line-ending conversion issues.readinto()
to avoid buffer churning.Example:
import hashlib
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
well looking for a simpler variation I found this:
it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.
demo and credit => http://codepen.io/Ahrengot/pen/bKdLC
@keyframes fadeIn { _x000D_
from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
You can assign, but not declare, inside an if
:
Try this:
int v; // separate declaration
if((v = someMethod()) != 0) return true;
Maybe this will satisfy you -
something.xml
<CheckBox
android:text="Custom CheckBox"
android:button="@drawable/checkbox_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/star_down" />
<item android:state_checked="false" android:drawable="@drawable/star" />
</selector>
For, the reference just refer here
For the SQL Server 2019 (Express Edition) installation, I did the following:
SQL Server Installation Center
Installation
New SQL Server stand-alone installation or add features to
an existing installation
C:\SQL2019\Express_ENU
and click OK
You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.
CSS:
p {
color: red;
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom,
from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)
See a demo with a solid background, but you can change this to whatever you want.
Notice also that all the usual image properties are available for mask-image
p {_x000D_
color: red;_x000D_
font-size: 30px;_x000D_
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
-webkit-mask-size: 100% 50%;_x000D_
-webkit-mask-repeat: no-repeat;_x000D_
-webkit-mask-position: left top, left bottom;_x000D_
}_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.
The idea is to use
mix-blend-mode: hard-light;
that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency
div {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 200px;_x000D_
mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: linear-gradient(transparent, gray);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
For Microsoft Azure, it's slightly different.
Azure has a special CORS setting that needs to be set. It's essentially the same thing behind the scenes, but simply setting the header joshuarh mentions will not work. The Azure documentation for enabling cross domain can be found here:
https://docs.microsoft.com/en-us/azure/app-service-api/app-service-api-cors-consume-javascript
I fiddled around with this for a few hours before realizing my hosting platform had this special setting.
Take a look at this example. This query should work:
var leftFinal = from left in lefts
join right in rights on left equals right.Left into leftRights
from leftRight in leftRights.DefaultIfEmpty()
select new { LeftId = left.Id, RightId = left.Key==leftRight.Key ? leftRight.Id : 0 };
You can create a boolean field and check it inside run:
public class Task implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
//do work
}
}
public void kill() {
isRunning = false;
}
}
To stop it just call
task.kill();
This should work.
useStyles
is a React hook which are meant to be used in functional components and can not be used in class components.
Hooks let you use state and other React features without writing a class.
Also you should call useStyles
hook inside your function like;
function Welcome() {
const classes = useStyles();
...
If you want to use hooks, here is your brief class component changed into functional component;
import React from "react";
import { Container, makeStyles } from "@material-ui/core";
const useStyles = makeStyles({
root: {
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
border: 0,
borderRadius: 3,
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
color: "white",
height: 48,
padding: "0 30px"
}
});
function Welcome() {
const classes = useStyles();
return (
<Container className={classes.root}>
<h1>Welcome</h1>
</Container>
);
}
export default Welcome;
on ↓ CodeSandBox ↓
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
Here are a variety of ways to do this in base R
including an alternative aggregate
approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:
Using ave
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))
my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data
Using by
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)
my.data <- merge(my.data, by.month, by = 'Month')
my.data
Using lapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)
my.data <- merge(my.data, ly.mean, by = 'Month')
my.data
Using sapply
and split
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data
sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data
Using aggregate
:
my.data <- read.table(text = '
Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month),
FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))
my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary
my.data <- merge(my.data, my.summary, by = 'Month')
my.data
EDIT: June 28, 2020
Here I use aggregate
to obtain the column means
of an entire matrix
by group where group is defined in an external vector
:
my.group <- c(1,2,1,2,2,3,1,2,3,3)
my.data <- matrix(c( 1, 2, 3, 4, 5,
10, 20, 30, 40, 50,
2, 4, 6, 8, 10,
20, 30, 40, 50, 60,
20, 18, 16, 14, 12,
1000, 1100, 1200, 1300, 1400,
2, 3, 4, 3, 2,
50, 40, 30, 20, 10,
1001, 2001, 3001, 4001, 5001,
1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data
my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
# Group.1 X1 X2 X3 X4 X5
#1 1 1.666667 3.000 4.333333 5.000 5.666667
#2 2 25.000000 27.000 29.000000 31.000 33.000000
#3 3 1000.333333 1700.333 2400.333333 3100.333 3800.333333
You can just append
track by version.id
to your ng-options.
I had to add set noundofile
to ~_gvimrc
The "~" directory can be identified by changing the directory with the cd ~
command
You can also tell MySQL what database to use (if you have it created already):
mysql -u example_user -p --database=example < ./example.sql
If you are not able to add a property to system.net
class library.
Then, add in Global.asax file:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768; //TLS 1.1
And you can use it in a function, at the starting line:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
And, it's being useful for STRIPE
payment gateway, which only supports TLS 1.1, TLS 1.2.
EDIT:
After so many questions on .NET 4.5 is installed on my server or not... here is the screenshot of Registry
on my production server:
I have only .NET framework 4.0 installed.
Ensure Script Debugging is disabled
I was getting this intermittently despite having tried several of the above suggestions. As soon as I disabled this, my debugging my site worked like a dream. (Think I'd only turned it on by accident, or perhaps in a previous life).
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
I'm surprised to see all answers stating the use of alt
attribute in a
tag is not valid. This is absolutely wrong.
Html does not block you using any attributes:
<a your-custom-attribute="value">Any attribute can be used</a>
If you ask if it is semantically correct to use alt
attribute in a
then I will say:
NO. It is used to set image description <img alt="image description" />
.
It is a matter of what you'd do with the attributes. Here's an example:
a::after {_x000D_
content: attr(color); /* attr can be used as content */_x000D_
display: block;_x000D_
color: white;_x000D_
background-color: blue;_x000D_
background-color: attr(color); /* This won't work */_x000D_
display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
display: block;_x000D_
}_x000D_
[hidden] {_x000D_
display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
Again, if you ask if it is semantically correct to use custom attribute then I will say:
No. Use data-*
attributes for its semantic use.
Oops, question was asked in 2013.
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
Updated with Swift 5 Generally we use three type of Local Notifications
Where you can send simple text notification or with action button and attachment.
Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.
AppDelegate
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Confirm Delegete and request for permission
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
//MARK: Local Notification Methods Starts here
//Prepare New Notificaion with deatils and trigger
func scheduleNotification(notificationType: String) {
//Compose New Notificaion
let content = UNMutableNotificationContent()
let categoryIdentifire = "Delete Notification Type"
content.sound = UNNotificationSound.default
content.body = "This is example how to send " + notificationType
content.badge = 1
content.categoryIdentifier = categoryIdentifire
//Add attachment for Notification with more content
if (notificationType == "Local Notification with Content")
{
let imageName = "Apple"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
//Add Action button the Notification
if (notificationType == "Local Notification with Action")
{
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
//Handle Notification Center Delegate methods
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
}
and ViewController
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var appDelegate = UIApplication.shared.delegate as? AppDelegate
let notifications = ["Simple Local Notification",
"Local Notification with Action",
"Local Notification with Content",]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notifications.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = notifications[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notificationType = notifications[indexPath.row]
let alert = UIAlertController(title: "",
message: "After 5 seconds " + notificationType + " will appear",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional use of fully qualified names is not an undue burden (unless the library really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language change.
So I guess we will not see this feature in Java anytime soon :-P
Using standard Unix tools available on most distro's. Also works well with backslashes (\) and quotes (")
WARNING: this doesn't come close to the power of jq and will only work with very simple JSON objects. It's an attempt to answer to the original question and in situations where you can't install additional tools.
function parse_json()
{
echo $1 | \
sed -e 's/[{}]/''/g' | \
sed -e 's/", "/'\",\"'/g' | \
sed -e 's/" ,"/'\",\"'/g' | \
sed -e 's/" , "/'\",\"'/g' | \
sed -e 's/","/'\"---SEPERATOR---\"'/g' | \
awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}" | \
sed -e "s/\"$2\"://" | \
tr -d "\n\t" | \
sed -e 's/\\"/"/g' | \
sed -e 's/\\\\/\\/g' | \
sed -e 's/^[ \t]*//g' | \
sed -e 's/^"//' -e 's/"$//'
}
parse_json '{"username":"john, doe","email":"[email protected]"}' username
parse_json '{"username":"john doe","email":"[email protected]"}' email
--- outputs ---
john, doe
[email protected]
With AppCompat 22, the FAB is supported for older devices.
Add the new support library in your build.gradle(app):
compile 'com.android.support:design:22.2.0'
Then you can use it in your xml:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:src="@android:drawable/ic_menu_more"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
To use elevation
and pressedTranslationZ
properties, namespace app
is needed, so add this namespace to your layout:
xmlns:app="http://schemas.android.com/apk/res-auto"
just Disable the Firewall and start again. it worked for me
You can now use Lambda Layers for this matters. Simply add a layer containing the package you need and it will run perfectly.
Follow this post: https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e
Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)
It contains the source code that you need.
Hope it helps.
Concat gives the flexibility to join based on the axis( all rows or all columns)
Append is the specific case(axis=0, join='outer') of concat
Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']
Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'
MS-SQL has a setting to prevent recursive trigger firing. This is confirgured via the sp_configure stored proceedure, where you can turn recursive or nested triggers on or off.
In this case, it would be possible, if you turn off recursive triggers to link the record from the inserted table via the primary key, and make changes to the record.
In the specific case in the question, it is not really a problem, because the result is to delete the record, which won't refire this particular trigger, but in general that could be a valid approach. We implemented optimistic concurrency this way.
The code for your trigger that could be used in this way would be:
ALTER TRIGGER myTrigger
ON someTable
AFTER INSERT
AS BEGIN
DELETE FROM someTable
INNER JOIN inserted on inserted.primarykey = someTable.primarykey
WHERE ISNUMERIC(inserted.someField) = 1
END
Here's a slightly different solution. Instead of multi-line, I focused on just the last line, and instead of a constant block size, I have a dynamic (doubling) block size. See comments for more info.
# Get last line of a text file using seek method. Works with non-constant block size.
# IDK if that speed things up, but it's good enough for us,
# especially with constant line lengths in the file (provided by len_guess),
# in which case the block size doubling is not performed much if at all. Currently,
# we're using this on a textfile format with constant line lengths.
# Requires that the file is opened up in binary mode. No nonzero end-rel seeks in text mode.
REL_FILE_END = 2
def lastTextFileLine(file, len_guess=1):
file.seek(-1, REL_FILE_END) # 1 => go back to position 0; -1 => 1 char back from end of file
text = file.read(1)
tot_sz = 1 # store total size so we know where to seek to next rel file end
if text != b'\n': # if newline is the last character, we want the text right before it
file.seek(0, REL_FILE_END) # else, consider the text all the way at the end (after last newline)
tot_sz = 0
blocks = [] # For storing succesive search blocks, so that we don't end up searching in the already searched
j = file.tell() # j = end pos
not_done = True
block_sz = len_guess
while not_done:
if j < block_sz: # in case our block doubling takes us past the start of the file (here j also = length of file remainder)
block_sz = j
not_done = False
tot_sz += block_sz
file.seek(-tot_sz, REL_FILE_END) # Yes, seek() works with negative numbers for seeking backward from file end
text = file.read(block_sz)
i = text.rfind(b'\n')
if i != -1:
text = text[i+1:].join(reversed(blocks))
return str(text)
else:
blocks.append(text)
block_sz <<= 1 # double block size (converge with open ended binary search-like strategy)
j = j - block_sz # if this doesn't work, try using tmp j1 = file.tell() above
return str(b''.join(reversed(blocks))) # if newline was never found, return everything read
Ideally, you'd wrap this in a class LastTextFileLine and keep track of a moving average of line lengths. This would give you a good len_guess maybe.
I ran into same problem. I have two projects in the solution. which
- API
- Services and repo, which hold context models
Initially, API project was set as Startup project.
I changed the Startup project to the one which holds context classes. if you are using Visual Studio you can set a project as Startup project by:
open solution explorer >> right-click on context project >> select Set as Startup project
Since you're writing a calculator that would presumably also accept floats (1.5, 0.03
), a more robust way would be to use this simple helper function:
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s)
return ret
That way if the int conversion doesn't work, you'll get a float returned.
Edit: Your division
function might also result in some sad faces if you aren't fully aware of how python 2.x handles integer division.
In short, if you want 10/2
to equal 2.5
and not 2
, you'll need to do from __future__ import division
or cast one or both of the arguments to float, like so:
def division(a, b):
return float(a) / float(b)
File-> Settings -> Keymap-> Complete Current Statement
I added ;
key in there. When typing ';' at the end of the line, it is auto-formatting.
UPDATE
I realized that this will cause some problems in some situations. Use Ctrl
+Shift
+Enter
instead. This key can be used in any position of cursor in a line. It will add ;
at the end of the line. Also this shortcut have some other useful features.
like:
public void someMethod()
after shortcut:
public void someMethod() {
// The cursor is here
}
so formatting on inserting ;
is not necessary.
/*
If your delimiters are slash-based, escape it:
\/*
*
means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.
This question is already answered, but for the benefit of others looking at this question I'd like to add the following suggestion: Instead of doing the slicing yourself as suggested above you might also use strptime()
which is (IMHO) easier to read and perhaps the preferred way to do this conversion.
import datetime
s = "20120213"
s_datetime = datetime.datetime.strptime(s, '%Y%m%d')
try using the Date
property on the DateTime
Object...
if(dtOne.Date == dtTwo.Date)
....
Presumably, since you're not providing a value for the DB_ID
column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.
Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID
that is currently in the table leading to the error.
You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a
SELECT <<sequence name>>.nextval
FROM dual
and comparing that to
SELECT MAX(db_id)
FROM cmdb_db
If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT
to something very large, get the nextval once, and set the INCREMENT
back to 1.
Perhaps you can try adding this in your imports:
import 'rxjs/add/operator/catch';
You can also do:
return this.http.request(request)
.map(res => res.json())
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay')
);
Per comments:
EXCEPTION: TypeError: Observable_1.Observable.throw is not a function
Similarly, for that, you can use:
import 'rxjs/add/observable/throw';
The params object is included in $stateParams, but won't be part of the url.
1) In the route configuration:
$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" }, //default value
paramTwo: "defaultValueTwo"
}
});
2) In the controller:
.controller('editUserCtrl', function ($stateParams, $scope) {
$scope.paramOne = $stateParams.paramOne;
$scope.paramTwo = $stateParams.paramTwo;
});
3A) Changing the State from a controller
$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
3B) Changing the State in html
<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
if you don't export default in A, B, C but just export {} then it's possible to do so
// things/A.js
export function A() {}
// things/B.js
export function B() {}
// things/C.js
export function C() {}
// foo.js
import * as Foo from ./thing
Foo.A()
Foo.B()
Foo.C()
mysqld --help --verbose is dangerous. You can easily overwrite pidfile for running instance! use it with --pid-file=XYZ
Oh, and you can't really use it if you have more than 1 instance running. It will only show you default value.
Really good article about it:
I didn't see it mentioned above but you will also see some people use left and right shift for arithmetic operations. A left shift by x is equivalent to multiplying by 2^x (as long as it doesn't overflow) and a right shift is equivalent to dividing by 2^x.
Recently I've seen people using x << 1 and x >> 1 for doubling and halving, although I'm not sure if they are just trying to be clever or if there really is a distinct advantage over the normal operators.
Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.
Happened the same to me. It turns out that
var data = $("#myObject").data();
gives you a non-writable object. I solved it using:
var data = $.extend({}, $("#myObject").data());
And from then on, data
was a standard, writable JS object.
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.
I don't think I saw anyone suggest this and the OP just said "script" so...
I needed to solve the same problem and my most comfortable language is Python.
I used the paramiko library. Furthermore, I also needed to issue commands for which I would need escalated permissions using sudo
. It turns out sudo can accept its password via stdin via the "-S" flag! See below:
import paramiko
ssh_client = paramiko.SSHClient()
# To avoid an "unknown hosts" error. Solve this differently if you must...
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# This mechanism uses a private key.
pkey = paramiko.RSAKey.from_private_key_file(PKEY_PATH)
# This mechanism uses a password.
# Get it from cli args or a file or hard code it, whatever works best for you
password = "password"
ssh_client.connect(hostname="my.host.name.com",
username="username",
# Uncomment one of the following...
# password=password
# pkey=pkey
)
# do something restricted
# If you don't need escalated permissions, omit everything before "mkdir"
command = "echo {} | sudo -S mkdir /var/log/test_dir 2>/dev/null".format(password)
# In order to inspect the exit code
# you need go under paramiko's hood a bit
# rather than just using "ssh_client.exec_command()"
chan = ssh_client.get_transport().open_session()
chan.exec_command(command)
exit_status = chan.recv_exit_status()
if exit_status != 0:
stderr = chan.recv_stderr(5000)
# Note that sudo's "-S" flag will send the password prompt to stderr
# so you will see that string here too, as well as the actual error.
# It was because of this behavior that we needed access to the exit code
# to assert success.
logger.error("Uh oh")
logger.error(stderr)
else:
logger.info("Successful!")
Hope this helps someone. My use case was creating directories, sending and untarring files and starting programs on ~300 servers as a time. As such, automation was paramount. I tried sshpass
, expect
, and then came up with this.
Please note that --tests
option may not work if you have different build types/flavors
(fails with Unknown command-line option '--tests'
). In this case, it's necessary to specify the particular test task (e.g. testProdReleaseUnitTest
instead of just test
)
A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.
But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.
My two cents: came across the same error message in RHEL7.3 while running the openssl command with root CA certificate. The reason being, while downloading the certificate from AD server, Encoding was selected as DER instead of Base64. Once the proper version of encoding was selected for the new certificate download, error was resolved
Hope this helps for new users :-)
I know of enabling or disabling wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true
or false
as per requirement.
Edit:
You also need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
You can make a generic class like this:
public class MyProp<T>
{
private T _value;
public T Value
{
get
{
// insert desired logic here
return _value;
}
set
{
// insert desired logic here
_value = value;
}
}
public static implicit operator T(MyProp<T> value)
{
return value.Value;
}
public static implicit operator MyProp<T>(T value)
{
return new MyProp<T> { Value = value };
}
}
...then use it in a class like so:
class SomeClass
{
public MyProp<int> SomeProperty { get; set; }
}
The implicit operators means that you do not need to explicitly set or get the Value
property of MyProp
, but can write code to access the value in a more "natural" way:
SomeClass instance = new SomeClass();
instance.SomeProperty = 32;
int someInt = instance.SomeProperty;
This problem started when I did 'Remove Unused References'. The website still worked on my local machine, but did not worked on the server after publishing.
I fixed this problem by doing the following,
Your current code:
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
is telling ggplot
to construct one histogram using all the values in f0
and then color the bars of this single histogram according to the variable utt
.
What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram
, where each one gets it's own data frame and fill:
ggplot(histogram, aes(f0)) +
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) +
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2) +
Here's a concrete example with some output:
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
which produces something like this:
Edited to fix typos; you wanted fill, not colour.
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:
<img data-src="path/to/image">
<script>
$('img').imageCaching();
</script>
I found a particular edge case where I was using the tini init in an alpine container, but since I was not using the statically linked version, and Alpine uses musl libc rather than GNU LibC library installed by default, it was crashing with the very same error message.
Had I understood this and also taken time to read the documentation properly, I would have found Tini Static, which upon changing to, resolved my problem.
The technical limitations with using PUT and DELETE requests does not lie with PHP or Apache2; it is instead on the burden of the browser to sent those types of requests.
Simply putting <form action="" method="PUT"> will not work because there are no browsers that support that method (and they would simply default to GET, treating PUT the same as it would treat gibberish like FDSFGS). Sadly those HTTP verbs are limited to the realm of non-desktop application browsers (ie: web service consumers).
Spring Boot seems had changed the way of reading the VM options as it evolves. Here's some way to try when you launch an application in Intellij and want to active some profile:
Open "Edit configuration" in "Run", and in "VM options", add: -Dspring.profiles.active=local
It actually works with one project of mine with Spring Boot v2.0.3.RELEASE
and Spring v5.0.7.RELEASE
, but not with another project with Spring Boot v2.1.1.RELEASE
and Spring v5.1.3.RELEASE
.
Also, when running with Maven or JAR, people mentioned this:
mvn spring-boot:run -Drun.profiles=dev
or
java -jar -Dspring.profiles.active=dev XXX.jar
(See here: how to use Spring Boot profiles)
It is mentioned somewhere, that Spring changes the way of launching the process of applications if you specify some JVM options; it forks another process and will not pass the arg it received so this does not work. The only way to pass args to it, is:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="..."
Again, this is for Maven. https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html
What works for me for the second project, was setting the environment variable, as mentioned in some answer above: "Edit configuration" - "Environment variable", and:
SPRING_PROFILES_ACTIVE=local
Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53
Just define width of the table and width for each table cell
something like
table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}
It works like a charm :o)
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.
Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
f = open('file.txt','r')
for line in f:
myNames.append(line.strip()) # We don't want newlines in our list, do we?
I had a similar issue when I wanted to change the box title and button title of the default confirm box. I have gone for the Jquery Ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation
When I had the following:
function testConfirm() {
if (confirm("Are you sure you want to delete?")) {
//some stuff
}
}
I have changed it to:
function testConfirm() {
var $dialog = $('<div></div>')
.html("Are you sure you want to delete?")
.dialog({
resizable: false,
title: "Confirm Deletion",
modal: true,
buttons: {
Cancel: function() {
$(this).dialog("close");
},
"Delete": function() {
//some stuff
$(this).dialog("close");
}
}
});
$dialog.dialog('open');
}
Can be seen working here https://jsfiddle.net/5aua4wss/2/
Hope that helps.
the following implements A friend's suggestion
#!/bin/bash
rcut(){
nu="$( echo $1 | cut -d"$DELIM" -f 2- )"
if [ "$nu" != "$1" ]
then
rcut "$nu"
else
echo "$nu"
fi
}
$ export DELIM=.
$ rcut a.b.c.d
d
I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8;
I used System.nanoTime()
for measurements.
I got the same time on both cases - around 1.564 seconds.
So, it looks like Netbeans has bad performance on print to console.
After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println
command), demonstrated by this code:
for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
And so on..
Idk if you guys solved it but I recommend another way to do it, and it works :)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.
Refresh the Object Browser view To confirm the changes
Done
you can simply use your own code but add name for the select tag
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
then you can access it like this
String agent=request.getparameter("agent_id");
<div id="412412412" class="input-group date">
<div class="input-group-prepend">
<button class="btn btn-danger" type="button">Button Click</button>
<input type="text" class="form-control" value="">
</div>
</div>
In my situation, i use this code:
$(this).parent().closest('.date').attr('id')
Hope this help someone.
String mystring = new String(mychararray);
You can center a fixed
or absolute
positioned element setting right
and left
to 0
, and then margin-left
& margin-right
to auto
as if you were centering a static
positioned element.
#example {
position: fixed;
/* center the element */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
/* give it dimensions */
min-height: 10em;
width: 90%;
}
This works in May 2020 using PDFminer six in Python3.
$ pip install pdfminer.six
from pdfminer.high_level import extract_text
text = extract_text('report.pdf')
Or alternatively:
with open('report.pdf','rb') as f:
text = extract_text(f)
If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io
library:
import io
response = requests.get(url)
text = extract_text(io.BytesIO(response.content))
PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7
However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.
I timed text extraction with timeit
on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:
PDFminer.six: 2.88 sec
PyPDF2: 0.45 sec
pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.
I was trying to use a Nexus 10 to debug through eclipse. I've been struggling to get eclipse to recognize it. Finally I tried 'adb kill server' / 'adb start server' command, which at least got Eclipse to show the device, although still only offline.
Then I tried switching USB connection to one in the back of the PC, and it worked!
Note: after I switched to rear USB port, I was prompted on the Nexus to allow debugging from my PC, once I allowed, the app popped up.
<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>
Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
Sven Marnach's answer is pretty much it, but has one generality issue... It will fail if the list being printed doesn't just contain strings.
So, the more general answer to "How to print out a list with elements separated by newlines"...
print '\n'.join([ str(myelement) for myelement in mylist ])
Then again, the print function approach JBernardo points out is superior. If you can, using the print function instead of the print statement is almost always a good idea.
Samuel Liew is right. sometimes jquery conflict with the other jqueries. to solve this problem you need to put them in such a order that they may not conflict with each other. do one thing: open your application in google chrome and inspect bottom right corner with red marked errors. which kind of error that is?
I was also wondering about print order. Consider this case, for example:
For a priority queue:
PriorityQueue<String> pq3 = new PriorityQueue<String>();
This code:
pq3.offer("a");
pq3.offer("A");
may print differently than:
String[] sa = {"a", "A"};
for(String s : sa)
pq3.offer(s);
I found the answer from a discussion on another forum, where a user said, "the offer()/add() methods only insert the element into the queue. If you want a predictable order you should use peek/poll which return the head of the queue."
Run apt-get install build-essential
on your system.
This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.
See this page for more info.
I tried a few solutions but at the end used replace
. My data set is part numbers and I fairly know what to expect. But just for sanity, I used PHP to build the long query:
$dirty = array(' ', '-', '.', ',', ':', '?', '/', '!', '&', '@');
$query = 'part_no';
foreach ($dirty as $dirt) {
$query = "replace($query,'$dirt','')";
}
echo $query;
This outputs something I used to get a headache from:
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(part_no,' ',''),'-',''),'.',''),',',''),':',''),'?',''),'/',''),'!',''),'&',''),'@','')
public static byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
Use Massif: http://valgrind.org/docs/manual/ms-manual.html
The console.log
should be wrapped in a function , the "default" function for every class is its constructor
so it should be declared there.
import { Component } from '@angular/core';
console.log("Hello1");
@Component({
selector: 'hello-console',
})
export class App {
s: string = "Hello2";
constructor(){
console.log(s);
}
}
Please try below code :
public T? GetParsedOrDefaultValue<T>(string valueToParse) where T : struct, IComparable
{
if(string.EmptyOrNull(valueToParse))return null;
try
{
// return parsed value
return (T) Convert.ChangeType(valueToParse, typeof(T));
}
catch(Exception)
{
//default as null value
return null;
}
return null;
}
First store the table in a view, then select columns from that view into a new table.
// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
table.Columns.Add("col" + i.ToString());
// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
System.Data.DataRow row = table.NewRow();
for (int j = 0; j < 11; j++)
row[j] = i.ToString() + ", " + j.ToString();
table.Rows.Add(row);
}
// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");
Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.
(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)
Edit: rewrote it as a jQuery plugin.
(function($) {
$.fn.normalkeypress = function(onNormal, onSpecial) {
this.bind('keydown keypress keyup', (function() {
var keyDown = {}, // keep track of which buttons have been pressed
lastKeyDown;
return function(event) {
if (event.type == 'keydown') {
keyDown[lastKeyDown = event.keyCode] = false;
return;
}
if (event.type == 'keypress') {
keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
return;
}
// 'keyup' event
var keyPress = keyDown[event.keyCode];
if ( keyPress &&
( ( ( keyPress.which >= 32 // not a control character
//|| keyPress.which == 8 || // \b
//|| keyPress.which == 9 || // \t
//|| keyPress.which == 10 || // \n
//|| keyPress.which == 13 // \r
) &&
!( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
!( keyPress.which == 63273 ) && //
!( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
!( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
( keyPress.which == 35 || // End
keyPress.which == 36 || // Home
keyPress.which == 45 || // Insert
keyPress.which == 46 || // Delete
keyPress.which == 144 // Num Lock
)
)
) ||
keyPress.which === undefined // normal character in IE < 9.0
) &&
keyPress.charCode !== 0 // not special character in Konqueror 4.3
) {
// Normal character
if (onNormal) onNormal.call(this, keyPress, event);
} else {
// Special character
if (onSpecial) onSpecial.call(this, event);
}
delete keyDown[event.keyCode];
};
})());
};
})(jQuery);
For normal form you can do
class MyModelForm(forms.ModelForm):
slug = forms.CharField(widget=forms.HiddenInput())
If you have model form you can do the following
class MyModelForm(forms.ModelForm):
class Meta:
model = TagStatus
fields = ('slug', 'ext')
widgets = {'slug': forms.HiddenInput()}
You can also override __init__
method
class Myform(forms.Form):
def __init__(self, *args, **kwargs):
super(Myform, self).__init__(*args, **kwargs)
self.fields['slug'].widget = forms.HiddenInput()
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.
@NgModule({
imports: [
...
],
bootstrap: [
AppComponent
],
declarations: [
AppComponent,
],
providers: [
SharedService,
...
]
});
Then you can directly provide it to your components,
constructor(private sharedService: SharedService)
With Shared Service you can either use functions or you can create a Subject to update multiple places at once.
@Injectable()
export class SharedService {
public clickedItemInformation: Subject<string> = new Subject();
}
In your list component you can publish clicked item information,
this.sharedService.clikedItemInformation.next("something");
and then you can fetch this information at your detail component:
this.sharedService.clikedItemInformation.subscribe((information) => {
// do something
});
Obviously, the data that list component shares can be anything. Hope this helps.
u can simply use "width" attribute of "style" to change the length of the dropdown box
<select class="my_dropdown" id="my_dropdown" style="width:APPROPRIATE WIDTH IN PIXLES">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>
e.g.
style="width:200px"
To remove all OIDs from your database tables, you can use this Linux script:
First, login as PostgreSQL superuser:
sudo su postgres
Now run this script, changing YOUR_DATABASE_NAME with you database name:
for tbl in `psql -qAt -c "select schemaname || '.' || tablename from pg_tables WHERE schemaname <> 'pg_catalog' AND schemaname <> 'information_schema';" YOUR_DATABASE_NAME` ; do psql -c "alter table $tbl SET WITHOUT OIDS" YOUR_DATABASE_NAME ; done
I used this script to remove all my OIDs, since Npgsql 3.0 doesn't work with this, and it isn't important to PostgreSQL anymore.
Are you using sublime text on linux? I got the same problem and it was solved! Here is my c.sublime-build:
{
"shell_cmd" : "gcc $file_name -o $file_base_name && ./$file_base_name",
"selector" : "source.c",
"shell":true,
"working_dir" : "$file_path"
}
var today = new Date();_x000D_
var yesterday1 = new Date(new Date().setDate(new Date().getDate() - 1));_x000D_
var yesterday2 = new Date(Date.now() - 86400000);_x000D_
var yesterday3 = new Date(Date.now() - 1000*60*60*24);_x000D_
var yesterday4 = new Date((new Date()).valueOf() - 1000*60*60*24);_x000D_
console.log("Today: "+today);_x000D_
console.log("Yesterday: "+yesterday1);_x000D_
console.log("Yesterday: "+yesterday2);_x000D_
console.log("Yesterday: "+yesterday3);_x000D_
console.log("Yesterday: "+yesterday4);
_x000D_
As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"}
however there is a neat trick that allows you to do something like
array("blah", "hey", "yo")
with the type automatically inferred.
I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here
df[!(is.na(df$start_pc) | df$start_pc==""), ]
In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:
const tampax = require('tampax');
const yamlString = `
dude:
name: Arthur
weapon:
favorite: Excalibur
useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;
const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);
// output : "Arthur use Excalibur. The goal is to kill Mordred."
Editor's Note: poster is also the author of this package.
I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:
public IHttpActionResult Post(Task task)
What worked for me was to create my own entity "DTOTask" like:
public IHttpActionResult Post(DTOTask task)
What you have done is perfect and very good practice.
The reason I say its good practice... For example, if for some reason you are using a "primitive" type of database pooling and you call connection.close()
, the connection will be returned to the pool and the ResultSet
/Statement
will never be closed and then you will run into many different new problems!
So you can't always count on connection.close()
to clean up.
I hope this helps :)
There are actually two ways of doing this:
st = "Line 1" + vbCrLf + "Line 2"
st = "Line 1" + vbNewLine + "Line 2"
These even work for message boxes (and all other places where strings are used).
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
The way that I have found best - and also to show in Allure report as fail - is to try-catch the findelement and in the catch block, set the assertTrue to false, like this:
try {
element = driver.findElement(By.linkText("Test Search"));
}catch(Exception e) {
assertTrue(false, "Test Search link was not displayed");
}
Simple fix:
Targets -> Build Settings -> Build Options -> Enable Bitcode -> No
Works on device with iOS 9.3.3
Try something like this when you are applying focus that way if the element is hidden, it won't throw an error:
$("#elementid").filter(':visible').focus();
It may make more sense to make the element visible, though that will require code specific to your layout.
In my case I made the mistake of copying *ng-for=
from the docs.
https://angular.io/guide/user-input
Correct me if I am wrong. But it seems *ng-for=
has been changed to *ngFor=
This works in latest Chrome, FireFox and Edge, but not IE11:
document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';
And if you want to ignore spaces around the title:
document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'
I think if you want to use extension methods you need to use the GroupJoin
var query =
people.GroupJoin(pets,
person => person,
pet => pet.Owner,
(person, petCollection) =>
new { OwnerName = person.Name,
Pet = PetCollection.Select( p => p.Name )
.DefaultIfEmpty() }
).ToList();
You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.
I think it's a little easier with the LINQ Query syntax
var query = (from person in context.People
join pet in context.Pets on person equals pet.Owner
into tempPets
from pets in tempPets.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name })
.ToList();
Pure numpy
numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)
Check out the loadtxt documentation.
You can also use python's csv module:
import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")
You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:
result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")
Added Hint:
You could also use pandas.io.parsers.read_csv
and get the associated numpy
array which can be faster.
I too get this error sometimes when I dismiss dialog and finish activity from onPostExecute method. I guess sometimes activity gets finished before dialog successfully dismisses.
Simple, yet effective solution that works for me
@Override
protected void onPostExecute(MyResult result) {
try {
if ((this.mDialog != null) && this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.mDialog = null;
}
}
For Kotlin fans:
private fun Bitmap.addOverlay(@DimenRes marginTop: Int, @DimenRes marginLeft: Int, overlay: Bitmap): Bitmap? {
val bitmapWidth = this.width
val bitmapHeight = this.height
val marginLeft = shareBitmapWidth - overlay.width - resources.getDimension(marginLeft)
val finalBitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, this
.config)
val canvas = Canvas(finalBitmap)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlay, marginLeft, resources.getDimension(marginTop), null)
return finalBitmap
}
bitmap.addOverlay( R.dimen.top_margin, R.dimen.left_margin, overlayBitmap)
import os
import os.path
def get_files(target_dir):
item_list = os.listdir(target_dir)
file_list = list()
for item in item_list:
item_dir = os.path.join(target_dir,item)
if os.path.isdir(item_dir):
file_list += get_files(item_dir)
else:
file_list.append(item_dir)
return file_list
Here I use a recursive structure.
Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.
Found the answer in How to lay out Views in RelativeLayout programmatically?
We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.
Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control
The most portable way to get the hostname of the current computer in Java is as follows:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class getHostName {
public static void main(String[] args) throws UnknownHostException {
InetAddress iAddress = InetAddress.getLocalHost();
String hostName = iAddress.getHostName();
//To get the Canonical host name
String canonicalHostName = iAddress.getCanonicalHostName();
System.out.println("HostName:" + hostName);
System.out.println("Canonical Host Name:" + canonicalHostName);
}
}
You can certainly do something like
SQL> ed
Wrote file afiedt.buf
1 begin
2 for d in (select * from dept)
3 loop
4 for e in (select * from emp where deptno=d.deptno)
5 loop
6 dbms_output.put_line( 'Employee ' || e.ename ||
7 ' in department ' || d.dname );
8 end loop;
9 end loop;
10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
Or something equivalent using explicit cursors.
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor dept_cur
3 is select *
4 from dept;
5 d dept_cur%rowtype;
6 cursor emp_cur( p_deptno IN dept.deptno%type )
7 is select *
8 from emp
9 where deptno = p_deptno;
10 e emp_cur%rowtype;
11 begin
12 open dept_cur;
13 loop
14 fetch dept_cur into d;
15 exit when dept_cur%notfound;
16 open emp_cur( d.deptno );
17 loop
18 fetch emp_cur into e;
19 exit when emp_cur%notfound;
20 dbms_output.put_line( 'Employee ' || e.ename ||
21 ' in department ' || d.dname );
22 end loop;
23 close emp_cur;
24 end loop;
25 close dept_cur;
26* end;
27 /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of
FOR x IN (SELECT *
FROM all_users,
org
WHERE length(all_users.username) = 3
AND all_users.username = org.username )
LOOP
<<do something>>
END LOOP;
WAMP = Windows + Apache + MySQL/MariaDB + PHP/Python/Perl
You can't use MongoDB in wamp.You need to install MongoDB separately
I know this post is old, but what i had to do in the case of the above answers on Linux machine was:
sudo chmod +x directory
When I am reading numbers from contact book, then it doesn't worked I used
number=number.replaceAll("\\s+", "");
It worked and for url you may use
url=url.replaceAll(" ", "%20");
I have a clearer proposal on automatic search in a DataGridView
this is an example
private void searchTb_TextChanged(object sender, EventArgs e)
{
try
{
(lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
"lename IS NOT NULL" :
String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
}
catch (Exception ex) {
MessageBox.Show(ex.StackTrace);
}
}
i have a pretty answer try this code ;)
<div id="DivID">
</div>
$("#DivID").scrollview({ direction: 'y' });
$("#DivID > .ui-scrollbar").addClass("ui-scrollbar-visible");
Try this:
SELECT DISTINCT * FROM (
SELECT column1, column2 FROM Table1
UNION ALL
SELECT column1, column2 FROM Table2
UNION ALL
SELECT column1, column2 FROM Table3
) X ORDER BY Column1
origin/xxx
branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).
What you need to do to update the remote is to force push your local changes to master:
git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master
Just pick the columns you want directly....
df[['A','E','I','C']]
When you save your file, make sure it has the extension .java. If it does not, Eclipse won't know to read it as a java file.
No need to use the JavaScript or jquery, CSS is enough:
.child{ display:none; }
.parent:hover .child{ display:block; }
Here's a no framework code, only pure js :
document.querySelectorAll('img.svg').forEach(function(element) {
var imgID = element.getAttribute('id')
var imgClass = element.getAttribute('class')
var imgURL = element.getAttribute('src')
xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var svg = xhr.responseXML.getElementsByTagName('svg')[0];
if(imgID != null) {
svg.setAttribute('id', imgID);
}
if(imgClass != null) {
svg.setAttribute('class', imgClass + ' replaced-svg');
}
svg.removeAttribute('xmlns:a')
if(!svg.hasAttribute('viewBox') && svg.hasAttribute('height') && svg.hasAttribute('width')) {
svg.setAttribute('viewBox', '0 0 ' + svg.getAttribute('height') + ' ' + svg.getAttribute('width'))
}
element.parentElement.replaceChild(svg, element)
}
}
xhr.open('GET', imgURL, true)
xhr.send(null)
})